feat: migrate web preview to Next.js
Verify mini program and deploy preview / verify-deploy (push) Successful in 3m30s
Verify mini program and deploy preview / verify-deploy (push) Successful in 3m30s
This commit is contained in:
+2
-1
@@ -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
|
||||
|
||||
|
||||
@@ -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 pk-lab-xhs-preview 2>/dev/null || true
|
||||
docker run -d --name pk-lab-xhs-preview --restart unless-stopped --network pk-lab-public --read-only --tmpfs /var/cache/nginx --tmpfs /var/run -p "$DEPLOY_PORT:8080" "pk-lab-xhs:$SOURCE_REVISION"
|
||||
docker run -d --name pk-lab-xhs-preview --restart unless-stopped --network pk-lab-public --read-only --tmpfs /tmp:rw,noexec,nosuid,size=64m -p "$DEPLOY_PORT:8080" "pk-lab-xhs:$SOURCE_REVISION"
|
||||
for i in 1 2 3 4 5 6 7 8 9 10; do
|
||||
status="$(docker inspect --format '{{.State.Health.Status}}' pk-lab-xhs-preview)"
|
||||
[ "$status" = healthy ] && break
|
||||
|
||||
@@ -1,4 +1,5 @@
|
||||
.DS_Store
|
||||
node_modules/
|
||||
.next/
|
||||
dist/
|
||||
project.private.config.json
|
||||
|
||||
+18
-9
@@ -1,14 +1,23 @@
|
||||
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 package.json package-lock.json vite.config.js ./
|
||||
RUN npm ci
|
||||
COPY web ./web
|
||||
RUN npm run build:web
|
||||
COPY --from=dependencies /app/node_modules ./node_modules
|
||||
COPY web ./
|
||||
COPY assets ./public/assets
|
||||
RUN npm run build
|
||||
|
||||
FROM nginx:1.27-alpine
|
||||
COPY --from=web-build /app/dist /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 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"]
|
||||
|
||||
@@ -1,6 +1,6 @@
|
||||
# PK 研究所(综合版)
|
||||
|
||||
原生小红书小程序源码,同时提供由 Nginx 常驻托管的公网功能预览。综合版包含瀑布流测试广场、二选一淘汰赛、我的历史、跨小程序绑定码与三种可保存的分享图模板。
|
||||
原生小红书小程序源码,同时提供由 Next.js 常驻托管的公网功能预览。综合版包含瀑布流测试广场、二选一淘汰赛、我的历史、跨小程序绑定码与可编辑、可保存的晋级图分享海报。
|
||||
|
||||
## 接入
|
||||
|
||||
@@ -9,4 +9,6 @@
|
||||
3. 用小红书开发者工具打开仓库根目录,绑定综合版 App ID。
|
||||
4. 后端配置同一 App ID/Secret 后重新部署。
|
||||
|
||||
CI 默认把公网预览持续部署到宿主机 `3000` 端口,并加入 `pk-lab-public` Docker 网络。浏览器固定同源请求 `/api`,Nginx 转发给网络内的 `pk-lab-api:8000`,不写死服务器 IP,也不暴露后端端口。预览使用后端显式开启的 `TEST_AUTH_ENABLED` 测试身份,正式小程序使用 `xhs.login()`。
|
||||
CI 默认把 Next.js standalone 服务持续部署到宿主机 `3000` 端口,并加入 `pk-lab-public` Docker 网络。浏览器固定同源请求 `/api`,Next.js Route Handler 转发给网络内的 `pk-lab-api:8000`,不写死服务器 IP,也不暴露后端端口。预览使用后端显式开启的 `TEST_AUTH_ENABLED` 测试身份,正式小程序使用 `xhs.login()`。
|
||||
|
||||
本地 Web 开发使用 `npm --prefix web install && npm --prefix web run dev`;仓库根目录仍是小红书开发者工具所需的原生项目,不会由 Next.js 替换。
|
||||
|
||||
-26
@@ -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;
|
||||
}
|
||||
}
|
||||
Generated
-1199
File diff suppressed because it is too large
Load Diff
+2
-4
@@ -5,8 +5,6 @@
|
||||
"scripts": {
|
||||
"check": "node scripts/check.mjs",
|
||||
"test": "node --test test/*.test.cjs",
|
||||
"build:web": "vite build --config vite.config.js"
|
||||
},
|
||||
"dependencies": { "motion": "^12.23.24" },
|
||||
"devDependencies": { "vite": "^7.1.7" }
|
||||
"build:web": "npm --prefix web run build"
|
||||
}
|
||||
}
|
||||
|
||||
+3
-3
@@ -1,7 +1,7 @@
|
||||
import { readFileSync, existsSync } from 'node:fs';
|
||||
const required = ['app.js','app.json','pages/index/index.xhsml','pages/discover/discover.xhsml','pages/test/test.js','pages/result/result.js','assets/test-covers/rice.jpg','vendor/poster-editor.cjs','web/index.html','web/app.js'];
|
||||
const required = ['app.js','app.json','pages/index/index.xhsml','pages/discover/discover.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/TestArena.jsx','web/components/PosterEditor.jsx'];
|
||||
for (const file of required) if (!existsSync(file)) throw new Error(`Missing ${file}`);
|
||||
JSON.parse(readFileSync('app.json','utf8'));
|
||||
const web = readFileSync('web/index.html','utf8');
|
||||
if (!web.includes('./app.js') || !web.includes('./style.css')) throw new Error('Preview assets are not linked');
|
||||
const nextConfig = readFileSync('web/next.config.mjs','utf8');
|
||||
if (!nextConfig.includes("output: 'standalone'")) throw new Error('Next.js standalone output is required');
|
||||
console.log(`Static checks passed (${required.length} required files).`);
|
||||
|
||||
+9
-5
@@ -10,16 +10,20 @@ 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/TestArena.jsx",
|
||||
"web/components/PosterEditor.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())
|
||||
web = Path("web/index.html").read_text()
|
||||
if "./app.js" not in web or "./style.css" not in web:
|
||||
raise SystemExit("Preview assets are not linked")
|
||||
next_config = Path("web/next.config.mjs").read_text()
|
||||
if "output: 'standalone'" not in next_config:
|
||||
raise SystemExit("Next.js standalone output is required")
|
||||
|
||||
print(f"Static checks passed ({len(required)} required files).")
|
||||
|
||||
@@ -1,7 +0,0 @@
|
||||
import { defineConfig } from 'vite';
|
||||
|
||||
export default defineConfig({
|
||||
root: 'web',
|
||||
base: './',
|
||||
build: { outDir: '../dist', emptyOutDir: true }
|
||||
});
|
||||
-79
@@ -1,79 +0,0 @@
|
||||
import { animate, stagger } from 'motion';
|
||||
|
||||
(function () {
|
||||
'use strict';
|
||||
var root = document.getElementById('app');
|
||||
var apiBase = (window.PK_CONFIG.apiBase || '').replace(/\/$/, '');
|
||||
var state = { tests: [], test: null, bracket: null, result: null, template: 'celebration', sticker: true, mode: 'single', bracketLayout: 'symmetric', bracketView: 'overview' };
|
||||
|
||||
function toast(message) { var el = document.getElementById('toast'); el.textContent = message; el.classList.add('show'); setTimeout(function () { el.classList.remove('show'); }, 2200); }
|
||||
function escapeHtml(value) { return String(value).replace(/[&<>"']/g, function (char) { return ({'&':'&','<':'<','>':'>','"':'"',"'":'''})[char]; }); }
|
||||
function request(path, options) {
|
||||
options = options || {}; var token = localStorage.getItem('pk_token');
|
||||
var headers = {'Content-Type':'application/json'}; if (token) headers.Authorization = 'Bearer ' + token;
|
||||
return fetch(apiBase + path, {method:options.method || 'GET',headers:headers,body:options.data ? JSON.stringify(options.data) : undefined}).then(function (response) {
|
||||
return response.json().catch(function () { return {}; }).then(function (data) { if (!response.ok) throw new Error(data.detail || '请求失败'); return data; });
|
||||
});
|
||||
}
|
||||
function ensureLogin() {
|
||||
if (localStorage.getItem('pk_token')) return Promise.resolve();
|
||||
var id = localStorage.getItem('pk_preview_id') || (Date.now().toString(36) + Math.random().toString(36).slice(2)); localStorage.setItem('pk_preview_id', id);
|
||||
return request('/api/v1/auth/xhs', {method:'POST',data:{app_key:'hub',code:'dev:web-' + id}}).then(function (data) { localStorage.setItem('pk_token', data.token); });
|
||||
}
|
||||
function loadHome() {
|
||||
root.innerHTML = '<div class="loading">正在摆好擂台…</div>';
|
||||
request('/api/v1/tests').then(function (tests) { state.tests = tests; renderHome(); }).catch(renderError);
|
||||
}
|
||||
function renderHome() {
|
||||
root.innerHTML = '<div class="shell home-shell"><div class="mast"><div class="logo-mark">PK</div><strong>偏爱研究所</strong></div><label class="search"><span>⌕</span><input id="searchTests" placeholder="搜索测试"></label><section class="grid">' + state.tests.map(function (test) {
|
||||
return '<button class="test-card" data-search="' + escapeHtml(test.title + ' ' + test.subtitle) + '" data-slug="' + test.slug + '"><img class="art" src="./assets/test-covers/' + test.slug + '.jpg" alt=""><div class="card-body"><h3>' + escapeHtml(test.title) + '</h3><p>' + escapeHtml(test.subtitle) + '</p><div class="meta"><span>' + test.candidate_count + ' 强</span><span>' + test.run_count + ' 人完成</span></div></div></button>';
|
||||
}).join('') + '</section></div>';
|
||||
root.querySelectorAll('.test-card').forEach(function (el) { el.addEventListener('click', function () { loadTest(el.dataset.slug); }); });
|
||||
document.getElementById('searchTests').addEventListener('input', function (event) { var value = event.target.value.toLowerCase(); root.querySelectorAll('.test-card').forEach(function (card) { card.hidden = card.dataset.search.toLowerCase().indexOf(value) < 0; }); });
|
||||
animate('.test-card', { opacity: [0, 1], y: [20, 0] }, { delay: stagger(.045), duration: .35 });
|
||||
}
|
||||
function buildMatches(pool) { var matches=[];for(var i=0;i<pool.length;i+=2)matches.push({left:pool[i],right:pool[i+1]||null,winner:pool[i+1]?null:pool[i]});return matches; }
|
||||
function loadTest(slug) { root.innerHTML = '<div class="loading">正在抽签…</div>'; request('/api/v1/tests/' + slug).then(function (test) { state.test = test; state.bracket = {round:1,pool:test.candidates.slice(),matches:buildMatches(test.candidates),eliminated:[],decisions:[],offset:0}; renderPair(); }).catch(renderError); }
|
||||
function pair() { var match=state.bracket.matches.find(function(item){return item.right&&!item.winner;});return match?[match.left,match.right]:null; }
|
||||
function renderPair() {
|
||||
var items = pair(), done = state.bracket.decisions.length, total = state.test.candidates.length - 1;
|
||||
var tabs='<div class="mode-tabs"><button data-mode="single">一对</button><button data-mode="multi">多对</button><button data-mode="swipe">滑动</button></div>';
|
||||
var content;
|
||||
if(state.mode==='multi'){var block=state.bracket.matches.slice(state.bracket.offset,state.bracket.offset+4);content='<div class="multi-pairs">'+block.map(function(m,i){var mi=state.bracket.offset+i;return m.winner?'<div class="mini-pair winner">晋级<br><strong>'+escapeHtml(m.winner.name)+'</strong></div>':'<div class="mini-pair"><button data-match="'+mi+'" data-side="0">'+escapeHtml(m.left.name)+'</button><span>VS</span><button data-match="'+mi+'" data-side="1">'+escapeHtml(m.right.name)+'</button></div>';}).join('')+'</div>';}else{content='<div class="pair swipeable"><button class="choice" data-side="0"><span class="choice-letter">A</span><strong class="choice-name">'+escapeHtml(items[0].name)+'</strong><span class="choice-hint">'+(state.mode==='swipe'?'向左滑选它':'点它晋级')+'</span></button><span class="vs">VS</span><button class="choice" data-side="1"><span class="choice-letter">B</span><strong class="choice-name">'+escapeHtml(items[1].name)+'</strong><span class="choice-hint">'+(state.mode==='swipe'?'向右滑选它':'点它晋级')+'</span></button></div>';}
|
||||
root.innerHTML = '<div class="shell arena"><div class="arena-top"><span>第 ' + state.bracket.round + ' 轮</span><span class="muted">' + done + ' / ' + total + '</span></div><div class="progress"><span style="width:' + Math.round(done/total*100) + '%"></span></div>'+tabs+content+'</div>';
|
||||
root.querySelectorAll('[data-mode]').forEach(function(el){el.classList.toggle('active',el.dataset.mode===state.mode);el.onclick=function(){state.mode=el.dataset.mode;renderPair();};});
|
||||
root.querySelectorAll('.choice').forEach(function (el) { el.addEventListener('click', function () { chooseAt(state.bracket.matches.findIndex(function(m){return m.right&&!m.winner;}),Number(el.dataset.side)); }); });
|
||||
root.querySelectorAll('[data-match]').forEach(function(el){el.onclick=function(){chooseAt(Number(el.dataset.match),Number(el.dataset.side));};});
|
||||
var swipe=root.querySelector('.swipeable'),startX;if(swipe){swipe.onpointerdown=function(e){startX=e.clientX;};swipe.onpointerup=function(e){var d=e.clientX-startX;if(state.mode==='swipe'&&Math.abs(d)>60)chooseAt(state.bracket.matches.findIndex(function(m){return m.right&&!m.winner;}),d<0?0:1);};}
|
||||
}
|
||||
function chooseAt(index,side) {
|
||||
var b=state.bracket,m=b.matches[index];if(!m||m.winner)return;var winner=side?m.right:m.left,loser=side?m.left:m.right;m.winner=winner;b.eliminated.unshift(loser);b.decisions.push({round:b.round,left_id:m.left.id,right_id:m.right.id,winner_id:winner.id});
|
||||
if(b.matches.every(function(item){return item.winner;})){b.pool=b.matches.map(function(item){return item.winner;});if(b.pool.length===1){complete();return;}b.round++;b.matches=buildMatches(b.pool);b.offset=0;}else if(state.mode==='multi'){var block=b.matches.slice(b.offset,b.offset+4);if(block.length&&block.every(function(item){return item.winner;}))b.offset+=4;}
|
||||
renderPair();
|
||||
}
|
||||
function complete() {
|
||||
var b = state.bracket, champion = b.pool[0], final = b.decisions[b.decisions.length - 1], runner = final.left_id === champion.id ? final.right_id : final.left_id;
|
||||
root.innerHTML = '<div class="loading">正在保存你的冠军…</div>';
|
||||
ensureLogin().then(function () { return request('/api/v1/tests/' + state.test.slug + '/runs',{method:'POST',data:{app_key:'hub',champion_id:champion.id,runner_up_id:runner,ranking_ids:b.pool.concat(b.eliminated).map(function(i){return i.id;}),decisions:b.decisions}}); }).then(function (result) { state.result = result; renderResult(); }).catch(renderError);
|
||||
}
|
||||
function renderResult() {
|
||||
var r = state.result;
|
||||
root.innerHTML = '<div class="shell result-shell editor-shell"><div class="editor-title"><div><small>分享图编辑器</small><h2>'+escapeHtml(r.test_title)+' · '+escapeHtml(r.champion_name)+'</h2></div><button id="savePoster" class="button">导出 PNG</button></div><div class="result-layout"><canvas id="poster" class="poster" width="750" height="1000"></canvas><aside class="control"><h3>晋级图</h3><div class="control-grid"><button class="theme active" data-layout="symmetric">对称</button><button class="theme" data-layout="single">单边</button><button class="theme" data-view="overview">总览</button><button class="theme" data-view="left">左半区</button><button class="theme" data-view="right">右半区</button><button class="theme" data-view="top16">16 强</button><button class="theme" data-view="top8">8 强</button><button class="theme" data-view="final">决赛</button></div><h3>编辑工具</h3><div class="editor-tools"><button>滤镜</button><button>文字</button><button id="stickerToggle">贴纸</button><button>裁剪</button><button>调整</button><button>布局</button><button>画笔</button></div><button class="theme active" data-theme="celebration">庆祝派对</button><button class="theme" data-theme="editorial">杂志封面</button><button class="theme" data-theme="sticker">贴纸手账</button><button id="replay" class="button outline wide">再测一次</button></aside></div></div>';
|
||||
drawPoster(); root.querySelectorAll('[data-theme]').forEach(function (el) { el.addEventListener('click', function () { state.template = el.dataset.theme; root.querySelectorAll('[data-theme]').forEach(function(x){x.classList.remove('active');});el.classList.add('active');drawPoster(); }); });
|
||||
root.querySelectorAll('[data-layout]').forEach(function(el){el.onclick=function(){state.bracketLayout=el.dataset.layout;drawPoster();};});
|
||||
root.querySelectorAll('[data-view]').forEach(function(el){el.onclick=function(){state.bracketView=el.dataset.view;drawPoster();};});
|
||||
document.getElementById('stickerToggle').addEventListener('click',function(){state.sticker=!state.sticker;this.textContent='手绘贴纸:'+(state.sticker?'开启':'关闭');drawPoster();});
|
||||
document.getElementById('savePoster').addEventListener('click',function(){var a=document.createElement('a');a.download='我的PK冠军-'+r.champion_name+'.png';a.href=document.getElementById('poster').toDataURL('image/png');a.click();toast('分享图已保存');});
|
||||
document.getElementById('replay').addEventListener('click',function(){loadTest(r.test_slug);});
|
||||
}
|
||||
function drawPoster() {
|
||||
var canvas=document.getElementById('poster'),ctx=canvas.getContext('2d'),r=state.result,themes={celebration:['#ff6b35','#fffaf4','#25211f','#ffe568'],editorial:['#f3eadf','#201d1b','#fff','#285ee8'],sticker:['#c9f06b','#1e2810','#ff72a7','#fff']},t=themes[state.template];
|
||||
ctx.fillStyle=t[0];ctx.fillRect(0,0,750,1000);ctx.fillStyle=t[1];ctx.font='700 24px system-ui';ctx.fillText('PK 研究所 / BRACKET',42,62);ctx.font='900 48px system-ui';ctx.fillText(r.test_title,42,125);ctx.fillStyle=t[2];ctx.fillRect(28,165,694,690);drawBracketWeb(ctx,r,t);if(state.sticker){ctx.fillStyle=t[3];ctx.beginPath();ctx.arc(660,100,48,0,Math.PI*2);ctx.fill();ctx.fillStyle=t[2];ctx.font='900 22px system-ui';ctx.fillText('WIN',635,108);}ctx.fillStyle=t[1];ctx.font='700 25px system-ui';ctx.fillText('冠军 '+r.champion_name,42,915);ctx.font='18px system-ui';ctx.fillText('保存分享图,看看朋友的晋级路线',42,962);
|
||||
}
|
||||
function drawBracketWeb(ctx,r,t){var ds=r.decisions||[],names=r.candidate_names||{};if(!ds.length){ctx.fillStyle=t[1];ctx.font='900 72px system-ui';ctx.fillText(r.champion_name,70,500);return;}var max=ds.reduce(function(m,d){return Math.max(m,d.round);},1),min=state.bracketView==='final'?max:state.bracketView==='top8'?Math.max(1,max-2):state.bracketView==='top16'?Math.max(1,max-3):1,visible=ds.filter(function(d,i){if(d.round<min)return false;if(state.bracketView==='left'||state.bracketView==='right')return d.round===max||i%2===(state.bracketView==='left'?0:1);return true;}),groups={},pos={};visible.forEach(function(d){(groups[d.round]||(groups[d.round]=[])).push(d);});Object.keys(groups).forEach(function(k){var round=Number(k),arr=groups[k];arr.forEach(function(d,i){var sym=state.bracketLayout==='symmetric',side=sym&&round<max&&i%2?1:-1,x=sym?375+side*Math.min(260,78+(max-round)*62):70+(round-min)*(580/Math.max(1,max-min)),y=230+(i+1)*(520/(arr.length+1));pos[d.winner_id+':'+d.round]={x:x,y:y,d:d};});});ctx.strokeStyle=t[3];ctx.lineWidth=3;Object.keys(pos).forEach(function(k){var p=pos[k],parent;visible.forEach(function(d){if(!parent&&d.round>p.d.round&&(d.left_id===p.d.winner_id||d.right_id===p.d.winner_id))parent=pos[d.winner_id+':'+d.round];});if(parent){ctx.beginPath();ctx.moveTo(p.x,p.y);ctx.lineTo((p.x+parent.x)/2,p.y);ctx.lineTo((p.x+parent.x)/2,parent.y);ctx.lineTo(parent.x,parent.y);ctx.stroke();}});Object.keys(pos).forEach(function(k){var p=pos[k],label=names[p.d.winner_id]||r.champion_name;ctx.fillStyle=p.d.round===max?t[3]:t[0];ctx.fillRect(p.x-56,p.y-20,112,40);ctx.fillStyle=t[1];ctx.font=(label.length>6?'13':'16')+'px system-ui';ctx.fillText(label.slice(0,8),p.x-47,p.y+6);});}
|
||||
function loadHistory() { root.innerHTML='<div class="loading">正在翻档案…</div>';ensureLogin().then(function(){return request('/api/v1/me/results');}).then(renderHistory).catch(renderError); }
|
||||
function loadDiscover() { root.innerHTML='<div class="loading">正在收集答案…</div>';request('/api/v1/results/discover').then(function(results){root.innerHTML='<div class="shell"><div class="mast"><div class="logo-mark">PK</div><strong>大家最近选了什么</strong></div><section class="grid">'+results.map(function(r){return '<article class="test-card"><img class="art" src="./assets/test-covers/'+r.test_slug+'.jpg" alt=""><div class="card-body"><p>'+escapeHtml(r.test_title)+'</p><h3>'+escapeHtml(r.champion_name)+'</h3></div></article>';}).join('')+'</section></div>';animate('.test-card',{opacity:[0,1],scale:[.96,1]},{delay:stagger(.04)});}).catch(renderError); }
|
||||
function renderHistory(results) { root.innerHTML='<div class="shell history"><div class="hero"><div class="eyebrow">MY TASTE ARCHIVE</div><h1>我的偏爱档案</h1><p>每一次纠结,都算数。</p></div><div class="section-head"><h2>做过的测试</h2><span class="muted">'+results.length+' 条结果</span></div><div class="link-box"><strong>连接独立饭类版</strong><p class="muted">两个小程序需要一次确认才能合并身份。</p><button id="linkCode" class="button">生成 10 分钟绑定码</button><div id="code" class="link-code"></div></div><div id="rows">'+(results.length?results.map(function(r,i){return '<button class="result-row" data-i="'+i+'"><span class="medal">#1</span><span><small>'+escapeHtml(r.test_title)+'</small><strong>'+escapeHtml(r.champion_name)+'</strong></span><span>→</span></button>';}).join(''):'<div class="empty">还没有结果,去选第一个冠军吧。</div>')+'</div></div>';document.getElementById('linkCode').addEventListener('click',function(){request('/api/v1/me/link-code',{method:'POST'}).then(function(d){document.getElementById('code').textContent=d.code;}).catch(renderError);});root.querySelectorAll('.result-row').forEach(function(el){el.addEventListener('click',function(){state.result=results[Number(el.dataset.i)];renderResult();});}); }
|
||||
function renderError(error) { root.innerHTML='<div class="shell empty"><h2>暂时没接上服务</h2><p>'+escapeHtml(error.message||'未知错误')+'</p><button class="button" id="retry">重新加载</button></div>';document.getElementById('retry').addEventListener('click',loadHome); }
|
||||
document.getElementById('homeButton').addEventListener('click',loadHome); document.getElementById('discoverButton').addEventListener('click',loadDiscover); document.getElementById('meButton').addEventListener('click',loadHistory); loadHome();
|
||||
}());
|
||||
@@ -0,0 +1,29 @@
|
||||
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;
|
||||
@@ -0,0 +1,5 @@
|
||||
import DiscoverFeed from '../../components/DiscoverFeed';
|
||||
|
||||
export default function DiscoverPage() {
|
||||
return <DiscoverFeed />;
|
||||
}
|
||||
File diff suppressed because one or more lines are too long
@@ -0,0 +1,3 @@
|
||||
export function GET() {
|
||||
return Response.json({ status: 'ok' });
|
||||
}
|
||||
@@ -0,0 +1,20 @@
|
||||
import './globals.css';
|
||||
|
||||
export const metadata = {
|
||||
title: '偏爱研究所',
|
||||
description: '每轮二选一,让偏爱一路赢到底。'
|
||||
};
|
||||
|
||||
export const viewport = {
|
||||
width: 'device-width',
|
||||
initialScale: 1,
|
||||
themeColor: '#fffaf6'
|
||||
};
|
||||
|
||||
export default function RootLayout({ children }) {
|
||||
return (
|
||||
<html lang="zh-CN">
|
||||
<body>{children}</body>
|
||||
</html>
|
||||
);
|
||||
}
|
||||
@@ -0,0 +1,5 @@
|
||||
import Profile from '../../components/Profile';
|
||||
|
||||
export default function MePage() {
|
||||
return <Profile />;
|
||||
}
|
||||
@@ -0,0 +1,5 @@
|
||||
import HomeFeed from '../components/HomeFeed';
|
||||
|
||||
export default function HomePage() {
|
||||
return <HomeFeed />;
|
||||
}
|
||||
@@ -0,0 +1,6 @@
|
||||
import PosterEditor from '../../../components/PosterEditor';
|
||||
|
||||
export default async function ResultPage({ params }) {
|
||||
const { id } = await params;
|
||||
return <PosterEditor runId={id} />;
|
||||
}
|
||||
@@ -0,0 +1,6 @@
|
||||
import TestArena from '../../../components/TestArena';
|
||||
|
||||
export default async function TestPage({ params }) {
|
||||
const { slug } = await params;
|
||||
return <TestArena slug={slug} />;
|
||||
}
|
||||
@@ -1 +0,0 @@
|
||||
.mode-tabs{display:flex;width:320px;margin:18px auto;padding:5px;border-radius:8px;background:#eee}.mode-tabs button{flex:1;padding:10px;border-radius:6px;background:transparent;color:#777}.mode-tabs button.active{background:#111;color:#fff}.arena{height:calc(100vh - 110px);overflow:hidden;margin-top:24px}.arena .pair{height:calc(100% - 120px)}.arena .choice{border-radius:8px}.multi-pairs{display:grid;grid-template-columns:1fr 1fr;grid-template-rows:1fr 1fr;gap:10px;height:calc(100% - 110px)}.mini-pair{display:grid;grid-template-columns:1fr 40px 1fr;min-height:0;border:2px solid #111;background:#fff}.mini-pair button{padding:14px;background:#fff;font-weight:800}.mini-pair span{display:grid;place-items:center;background:#111;color:#fff;font-size:12px}.mini-pair.winner{display:grid;place-items:center;text-align:center;background:#111;color:#fff;animation:winner-in .32s cubic-bezier(.2,1.4,.4,1)}@keyframes winner-in{from{opacity:0;transform:scale(.7)}to{opacity:1;transform:scale(1)}}@media(max-width:700px){.arena{height:calc(100vh - 95px);width:calc(100% - 20px)}.arena .pair{grid-template-columns:1fr 1fr}.arena .choice{min-height:0}.multi-pairs{gap:6px}.mini-pair{grid-template-columns:1fr 28px 1fr}.mini-pair button{padding:8px;font-size:13px}}
|
||||
@@ -0,0 +1,8 @@
|
||||
export default function AppLogo({ title = '偏爱研究所' }) {
|
||||
return (
|
||||
<header className="masthead">
|
||||
<span className="logoMark">PK</span>
|
||||
<strong>{title}</strong>
|
||||
</header>
|
||||
);
|
||||
}
|
||||
@@ -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>
|
||||
);
|
||||
}
|
||||
@@ -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>
|
||||
);
|
||||
}
|
||||
@@ -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>;
|
||||
}
|
||||
@@ -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);
|
||||
});
|
||||
}
|
||||
@@ -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>
|
||||
);
|
||||
}
|
||||
@@ -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>
|
||||
);
|
||||
}
|
||||
@@ -1 +0,0 @@
|
||||
.editor-shell{padding-bottom:100px}.editor-title{display:flex;align-items:center;justify-content:space-between;margin-bottom:18px}.editor-title h2{margin:5px 0 0}.editor-title small{color:#777}.control-grid{display:grid;grid-template-columns:1fr 1fr;gap:6px}.control-grid .theme{margin:0}.editor-tools{display:grid;grid-template-columns:repeat(4,1fr);gap:6px;margin-bottom:18px}.editor-tools button{padding:12px 4px;border:1px solid #ddd;border-radius:8px;background:#fff;font-size:12px}.editor-shell .poster{border-radius:8px}.editor-shell .control{border-radius:8px}@media(max-width:800px){.editor-title{align-items:flex-end}.editor-title h2{font-size:17px}.editor-shell .result-layout{grid-template-columns:minmax(0,1fr)}.editor-shell .control{padding:18px}}
|
||||
@@ -0,0 +1,7 @@
|
||||
import { defineConfig, globalIgnores } from 'eslint/config';
|
||||
import nextVitals from 'eslint-config-next/core-web-vitals';
|
||||
|
||||
export default defineConfig([
|
||||
...nextVitals,
|
||||
globalIgnores(['.next/**', 'public/**'])
|
||||
]);
|
||||
@@ -1 +0,0 @@
|
||||
.home-shell{max-width:920px;margin-top:24px;padding-bottom:100px}.mast{display:flex;align-items:center;gap:14px;margin:0 0 20px;font-size:24px}.logo-mark{display:grid;width:54px;height:42px;place-items:center;background:#111;color:#fff;font-weight:950;letter-spacing:-2px}.search{display:flex;align-items:center;gap:10px;margin-bottom:18px;padding:13px 16px;background:#f2f2f2;border-radius:5px}.search input{width:100%;border:0;outline:0;background:transparent;font:inherit}.home-shell .grid{grid-template-columns:repeat(2,minmax(0,1fr));gap:10px;align-items:start}.home-shell .test-card{border-radius:0;box-shadow:none}.home-shell .test-card:nth-child(3n+2) .art{height:390px}.home-shell .art{display:block;width:100%;height:330px;object-fit:cover}.home-shell .card-body{padding:14px 4px 22px}.bottom-nav{position:fixed;z-index:40;left:50%;bottom:22px;display:flex;width:min(360px,calc(100% - 36px));height:72px;padding:0 12px;transform:translateX(-50%);border-radius:16px;background:#080808;box-shadow:0 16px 44px rgba(0,0,0,.28)}.nav-tab{position:relative;flex:1;display:flex;flex-direction:column;align-items:center;justify-content:center;background:none;color:#888;font-size:12px}.nav-tab i{width:18px;height:18px;margin-bottom:5px;border:3px solid currentColor;border-radius:50%}.nav-tab:first-child{color:#fff}.nav-tab:first-child:before{content:"";position:absolute;top:-17px;width:62px;height:62px;border:9px solid #fff;border-radius:50%;background:#080808}.nav-tab i,.nav-tab span{z-index:1}@media(max-width:520px){.home-shell{width:calc(100% - 16px)}.home-shell .grid{gap:8px}.home-shell .art{height:250px}.home-shell .test-card:nth-child(3n+2) .art{height:300px}.home-shell .card-body{padding:12px 3px 18px}.choice-emoji{display:none}}
|
||||
@@ -1,20 +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">
|
||||
<link rel="stylesheet" href="./home.css">
|
||||
<link rel="stylesheet" href="./arena.css">
|
||||
<link rel="stylesheet" href="./editor.css">
|
||||
</head>
|
||||
<body>
|
||||
<main id="app" aria-live="polite"></main>
|
||||
<nav class="bottom-nav"><button id="homeButton" class="nav-tab active"><i></i><span>测试</span></button><button id="discoverButton" class="nav-tab"><i></i><span>发现</span></button><button id="meButton" class="nav-tab"><i></i><span>我的</span></button></nav>
|
||||
<div id="toast" class="toast" role="status"></div>
|
||||
<script type="module" src="./runtime-env.js"></script>
|
||||
<script type="module" src="./app.js"></script>
|
||||
</body>
|
||||
</html>
|
||||
@@ -0,0 +1,34 @@
|
||||
'use client';
|
||||
|
||||
export async function apiRequest(path, options = {}) {
|
||||
const token = typeof window === 'undefined' ? null : localStorage.getItem('pk_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) {
|
||||
const detail = typeof data.detail === 'string' ? data.detail : '请求失败';
|
||||
throw new Error(detail);
|
||||
}
|
||||
return data;
|
||||
}
|
||||
|
||||
export async function ensureLogin() {
|
||||
if (localStorage.getItem('pk_token')) return;
|
||||
let previewId = localStorage.getItem('pk_preview_id');
|
||||
if (!previewId) {
|
||||
previewId = `${Date.now().toString(36)}${Math.random().toString(36).slice(2)}`;
|
||||
localStorage.setItem('pk_preview_id', previewId);
|
||||
}
|
||||
const session = await apiRequest('/api/v1/auth/xhs', {
|
||||
method: 'POST',
|
||||
body: { app_key: 'hub', code: `dev:web-${previewId}` }
|
||||
});
|
||||
localStorage.setItem('pk_token', session.token);
|
||||
}
|
||||
@@ -0,0 +1,53 @@
|
||||
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, matchIndex, side) {
|
||||
const match = state.matches[matchIndex];
|
||||
if (!match?.right || match.winner) return { state, finished: false };
|
||||
const winner = side === 'right' ? match.right : match.left;
|
||||
const loser = side === 'right' ? match.left : match.right;
|
||||
const matches = state.matches.map((item, index) =>
|
||||
index === matchIndex ? { ...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);
|
||||
}
|
||||
@@ -0,0 +1,9 @@
|
||||
/** @type {import('next').NextConfig} */
|
||||
const nextConfig = {
|
||||
output: 'standalone',
|
||||
poweredByHeader: false,
|
||||
reactStrictMode: true,
|
||||
images: { unoptimized: true }
|
||||
};
|
||||
|
||||
export default nextConfig;
|
||||
Generated
+6165
File diff suppressed because it is too large
Load Diff
@@ -0,0 +1,21 @@
|
||||
{
|
||||
"name": "pk-lab-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 +0,0 @@
|
||||
window.PK_CONFIG = { apiBase: '' };
|
||||
File diff suppressed because one or more lines are too long
Reference in New Issue
Block a user