feat: redesign typed bracket poster editor
Verify mini program and deploy preview / verify-deploy (push) Successful in 3m9s

This commit is contained in:
2026-09-20 16:37:35 +08:00
parent b5ee950142
commit 5051466692
28 changed files with 282 additions and 258 deletions
+1 -1
View File
@@ -1,6 +1,6 @@
# PK 研究所(综合版)
原生小红书小程序源码,同时提供由 Next.js 常驻托管的公网功能预览。综合版包含瀑布流测试广场、二选一淘汰赛、我的历史、跨小程序绑定码与可编辑、可保存的晋级图分享海报。
原生小红书小程序源码,同时提供由 Next.js、React 与严格 TypeScript 构建的公网功能预览。综合版包含瀑布流测试广场、二选一淘汰赛、我的历史、跨小程序绑定码与可编辑、可保存的完整晋级图分享海报。
## 接入
+1 -1
View File
@@ -1,5 +1,5 @@
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/package.json','web/next.config.mjs','web/app/page.jsx','web/app/api/[...path]/route.js','web/components/TestArena.jsx','web/components/PosterEditor.jsx'];
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/tsconfig.json','web/next.config.mjs','web/app/page.tsx','web/app/api/[...path]/route.ts','web/components/TestArena.tsx','web/components/PosterEditor.tsx'];
for (const file of required) if (!existsSync(file)) throw new Error(`Missing ${file}`);
JSON.parse(readFileSync('app.json','utf8'));
const nextConfig = readFileSync('web/next.config.mjs','utf8');
+5 -4
View File
@@ -11,11 +11,12 @@ required = [
"assets/test-covers/rice.jpg",
"vendor/poster-editor.cjs",
"web/package.json",
"web/tsconfig.json",
"web/next.config.mjs",
"web/app/page.jsx",
"web/app/api/[...path]/route.js",
"web/components/TestArena.jsx",
"web/components/PosterEditor.jsx",
"web/app/page.tsx",
"web/app/api/[...path]/route.ts",
"web/components/TestArena.tsx",
"web/components/PosterEditor.tsx",
]
missing = [name for name in required if not Path(name).is_file()]
if missing:
@@ -1,6 +1,6 @@
const API_BASE = process.env.API_INTERNAL_URL || 'http://pk-lab-api:8000';
async function forward(request, context) {
async function forward(request: Request, context: { params: Promise<{ path: string[] }> }): Promise<Response> {
const { path } = await context.params;
const incoming = new URL(request.url);
const target = new URL(`/api/${path.join('/')}${incoming.search}`, API_BASE);
@@ -1,5 +1,5 @@
import DiscoverFeed from '../../components/DiscoverFeed';
export default function DiscoverPage() {
export default function DiscoverPage(): React.ReactElement {
return <DiscoverFeed />;
}
File diff suppressed because one or more lines are too long
@@ -1,3 +1,3 @@
export function GET() {
export function GET(): Response {
return Response.json({ status: 'ok' });
}
+5 -3
View File
@@ -1,17 +1,19 @@
import './globals.css';
import type { Metadata, Viewport } from 'next';
import type { ReactNode } from 'react';
export const metadata = {
export const metadata: Metadata = {
title: '偏爱研究所',
description: '每轮二选一,让偏爱一路赢到底。'
};
export const viewport = {
export const viewport: Viewport = {
width: 'device-width',
initialScale: 1,
themeColor: '#fffaf6'
};
export default function RootLayout({ children }) {
export default function RootLayout({ children }: Readonly<{ children: ReactNode }>) {
return (
<html lang="zh-CN">
<body>{children}</body>
+1 -1
View File
@@ -1,5 +1,5 @@
import Profile from '../../components/Profile';
export default function MePage() {
export default function MePage(): React.ReactElement {
return <Profile />;
}
+1 -1
View File
@@ -1,5 +1,5 @@
import HomeFeed from '../components/HomeFeed';
export default function HomePage() {
export default function HomePage(): React.ReactElement {
return <HomeFeed />;
}
@@ -1,6 +1,6 @@
import PosterEditor from '../../../components/PosterEditor';
export default async function ResultPage({ params }) {
export default async function ResultPage({ params }: { params: Promise<{ id: string }> }) {
const { id } = await params;
return <PosterEditor runId={id} />;
}
@@ -1,6 +1,6 @@
import TestArena from '../../../components/TestArena';
export default async function TestPage({ params }) {
export default async function TestPage({ params }: { params: Promise<{ slug: string }> }) {
const { slug } = await params;
return <TestArena slug={slug} />;
}
@@ -1,4 +1,4 @@
export default function AppLogo({ title = '偏爱研究所' }) {
export default function AppLogo({ title = '偏爱研究所' }: { title?: string }) {
return (
<header className="masthead">
<span className="logoMark">PK</span>
@@ -9,7 +9,7 @@ const ITEMS = [
{ href: '/me', label: '我的', icon: 'me' }
];
export default function BottomNav() {
export default function BottomNav(): React.ReactElement {
const pathname = usePathname();
return (
<nav className="bottomNav" aria-label="主导航">
@@ -6,12 +6,13 @@ import { useEffect, useState } from 'react';
import AppLogo from './AppLogo';
import BottomNav from './BottomNav';
import { apiRequest } from '../lib/api';
import type { TestResult } from '../lib/types';
export default function DiscoverFeed() {
const [results, setResults] = useState([]);
const [results, setResults] = useState<TestResult[]>([]);
const [error, setError] = useState('');
useEffect(() => {
apiRequest('/api/v1/results/discover').then(setResults).catch(error => setError(error.message));
apiRequest<TestResult[]>('/api/v1/results/discover').then(setResults).catch((error: Error) => setError(error.message));
}, []);
return (
<main className="pageShell feedPage">
@@ -7,14 +7,15 @@ import { useEffect, useMemo, useState } from 'react';
import AppLogo from './AppLogo';
import BottomNav from './BottomNav';
import { apiRequest } from '../lib/api';
import type { TestSummary } from '../lib/types';
export default function HomeFeed() {
const [tests, setTests] = useState([]);
const [tests, setTests] = useState<TestSummary[]>([]);
const [query, setQuery] = useState('');
const [error, setError] = useState('');
useEffect(() => {
apiRequest('/api/v1/tests').then(setTests).catch(error => setError(error.message));
apiRequest<TestSummary[]>('/api/v1/tests').then(setTests).catch((error: Error) => setError(error.message));
}, []);
const visible = useMemo(() => {
@@ -57,6 +58,6 @@ export default function HomeFeed() {
);
}
function ErrorState({ message }) {
function ErrorState({ message }: { message: string }) {
return <div className="emptyState"><strong>暂时没接上服务</strong><p>{message}</p></div>;
}
-195
View File
@@ -1,195 +0,0 @@
'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);
});
}
+22
View File
@@ -0,0 +1,22 @@
'use client';
import { motion } from 'motion/react';
import { useRouter } from 'next/navigation';
import { useCallback, useEffect, useRef, useState, type ChangeEvent } from 'react';
import { apiRequest, ensureLogin } from '../lib/api';
import { drawPoster } from '../lib/bracketPoster';
import type { TestResult } from '../lib/types';
type ThemeId='clean'|'cream'|'night';type LayoutId='symmetric'|'single';type ViewId='overview'|'left'|'right'|'top16'|'top8'|'final';type ToolId='filter'|'text'|'sticker'|'crop'|'adjust'|'layout'|'brush';type Adjustments={brightness:number;contrast:number;saturate:number};
const TOOLS:readonly [ToolId,string,string][]=[['filter','滤镜','◌'],['text','文字','T'],['sticker','贴纸','▣'],['crop','裁剪','⌗'],['adjust','调整','☷'],['layout','布局','▦'],['brush','画笔','⌁']];
const VIEWS:readonly [ViewId,string][]=[['overview','总览'],['left','左半区'],['right','右半区'],['top16','16 强'],['top8','8 强'],['final','决赛']];
export default function PosterEditor({runId}:{runId:string}){
const router=useRouter(),canvasRef=useRef<HTMLCanvasElement>(null);const[result,setResult]=useState<TestResult|null>(null),[error,setError]=useState(''),[theme,setTheme]=useState<ThemeId>('clean'),[layout,setLayout]=useState<LayoutId>('symmetric'),[view,setView]=useState<ViewId>('overview'),[tool,setTool]=useState<ToolId>('filter'),[sticker,setSticker]=useState(true),[caption,setCaption]=useState(''),[background,setBackground]=useState<HTMLImageElement|null>(null),[adjust,setAdjust]=useState<Adjustments>({brightness:100,contrast:100,saturate:100});
useEffect(()=>{async function load(){const cached=sessionStorage.getItem('pk_last_result');if(cached){const parsed=JSON.parse(cached) as TestResult;if(parsed.id===runId)return parsed;}await ensureLogin();return apiRequest<TestResult>(`/api/v1/me/results/${runId}`);}load().then(setResult).catch((reason:Error)=>setError(reason.message));},[runId]);
const draw=useCallback(()=>{const canvas=canvasRef.current;if(!result||!canvas)return;const ctx=canvas.getContext('2d');if(ctx)drawPoster(ctx,result,{themeId:theme,layout,view,caption,sticker,background,adjust});},[adjust,background,caption,layout,result,sticker,theme,view]);useEffect(()=>draw(),[draw]);
function pickBackground(event:ChangeEvent<HTMLInputElement>){const file=event.target.files?.[0];if(!file)return;const image=new Image();const url=URL.createObjectURL(file);image.onload=()=>{setBackground(image);URL.revokeObjectURL(url);};image.src=url;}
function save(){const canvas=canvasRef.current;if(!canvas||!result)return;const link=document.createElement('a');link.download=`我的PK晋级图-${result.champion_name}.png`;link.href=canvas.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 className="backButton" onClick={()=>router.push('/me')} aria-label="返回">‹</button><div><strong>编辑分享图</strong><small>{result.test_title} · {result.champion_name}</small></div><button className="exportButton" onClick={save}>保存</button></header><section className="editorWorkspace"><div className="canvasStage"><canvas ref={canvasRef} width="1080" height="1440"/></div><aside className="editorControls"><div className="scrollRow viewTabs"><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 className="bracketThumb"><b>树</b><small>晋级图</small></span><label className="addMedia"><b>+</b><small>添加底图</small><input type="file" accept="image/*" onChange={pickBackground}/></label></div><nav className="toolRow">{TOOLS.map(([id,label,icon])=><button key={id} className={tool===id?'active':''} onClick={()=>setTool(id)}><i>{icon}</i><span>{label}</span></button>)}</nav><motion.div key={tool} className="toolPanel" initial={{opacity:0,y:6}} animate={{opacity:1,y:0}}>{tool==='filter'?<div className="presetRow"><button className={theme==='clean'?'selected':''} onClick={()=>setTheme('clean')}><i className="swatch clean"/>清透</button><button className={theme==='cream'?'selected':''} onClick={()=>setTheme('cream')}><i className="swatch cream"/>暖白</button><button className={theme==='night'?'selected':''} onClick={()=>setTheme('night')}><i className="swatch night"/>夜色</button></div>:null}{tool==='text'?<input value={caption} maxLength={24} onChange={event=>setCaption(event.target.value)} placeholder="添加一句话…"/>:null}{tool==='sticker'?<button className="settingButton" onClick={()=>setSticker(value=>!value)}><span>冠军标记</span><b>{sticker?'开启':'关闭'}</b></button>:null}{tool==='adjust'?<AdjustControls value={adjust} onChange={setAdjust}/>:null}{['crop','layout','brush'].includes(tool)?<p>更多预设将从素材服务加载;当前不会破坏原始晋级数据。</p>:null}</motion.div></aside></section></main>;
}
function AdjustControls({value,onChange}:{value:Adjustments;onChange:(value:Adjustments)=>void}){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>;}
@@ -5,19 +5,20 @@ import { useEffect, useState } from 'react';
import AppLogo from './AppLogo';
import BottomNav from './BottomNav';
import { apiRequest, ensureLogin } from '../lib/api';
import type { TestResult } from '../lib/types';
export default function Profile() {
const [results, setResults] = useState([]);
const [results, setResults] = useState<TestResult[]>([]);
const [linkCode, setLinkCode] = useState('');
const [error, setError] = useState('');
useEffect(() => {
ensureLogin().then(() => apiRequest('/api/v1/me/results')).then(setResults).catch(error => setError(error.message));
ensureLogin().then(() => apiRequest<TestResult[]>('/api/v1/me/results')).then(setResults).catch((error: Error) => setError(error.message));
}, []);
async function createLinkCode() {
try {
const data = await apiRequest('/api/v1/me/link-code', { method: 'POST' });
const data = await apiRequest<{ code: string }>('/api/v1/me/link-code', { method: 'POST' });
setLinkCode(data.code);
} catch (error) { setError(error.message); }
} catch (error) { setError(error instanceof Error ? error.message : '生成失败'); }
}
return (
<main className="pageShell profilePage">
@@ -5,43 +5,47 @@ 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';
import type { BracketState, ChoiceSide, TestDetail, TestResult } from '../lib/types';
const MODES = [
type Mode = 'single' | 'multi' | 'swipe';
const MODES: readonly { id: Mode; label: string }[] = [
{ id: 'single', label: '一对' },
{ id: 'multi', label: '多对' },
{ id: 'swipe', label: '滑动' }
];
export default function TestArena({ slug }) {
export default function TestArena({ slug }: { slug: string }) {
const router = useRouter();
const [test, setTest] = useState(null);
const [bracket, setBracket] = useState(null);
const [mode, setMode] = useState('single');
const [test, setTest] = useState<TestDetail | null>(null);
const [bracket, setBracket] = useState<BracketState | null>(null);
const [mode, setMode] = useState<Mode>('single');
const [error, setError] = useState('');
const [saving, setSaving] = useState(false);
const pointerStart = useRef(null);
const pointerStart = useRef<number | null>(null);
useEffect(() => {
apiRequest(`/api/v1/tests/${slug}`).then(data => {
apiRequest<TestDetail>(`/api/v1/tests/${slug}`).then(data => {
setTest(data);
setBracket(createBracket(data.candidates));
}).catch(error => setError(error.message));
}).catch((error: 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 current = bracket && currentIndex >= 0 ? bracket.matches[currentIndex] : null;
const visibleMatches = useMemo(() => bracket?.matches.slice(bracket.offset, bracket.offset + 4) || [], [bracket]);
async function complete(finalState) {
async function complete(finalState: BracketState) {
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`, {
if (!champion || !finalDecision) throw new Error('晋级结果不完整');
const runnerUp = finalDecision.left_id === champion.id ? finalDecision.right_id : finalDecision.left_id;
const result = await apiRequest<TestResult>(`/api/v1/tests/${slug}/runs`, {
method: 'POST',
body: {
app_key: 'hub',
@@ -54,13 +58,13 @@ export default function TestArena({ slug }) {
sessionStorage.setItem('pk_last_result', JSON.stringify(result));
router.replace(`/results/${result.id}`);
} catch (error) {
setError(error.message);
setError(error instanceof Error ? error.message : '保存失败');
setSaving(false);
}
}
function select(matchIndex, side) {
if (saving) return;
function select(matchIndex: number, side: ChoiceSide) {
if (saving || !bracket) return;
const outcome = chooseMatch(bracket, matchIndex, side);
let next = outcome.state;
if (!outcome.finished && mode === 'multi') {
@@ -71,7 +75,7 @@ export default function TestArena({ slug }) {
if (outcome.finished) complete(next);
}
function pointerUp(event) {
function pointerUp(event: React.PointerEvent<HTMLElement>) {
if (mode !== 'swipe' || pointerStart.current === null) return;
const delta = event.clientX - pointerStart.current;
pointerStart.current = null;
@@ -80,6 +84,7 @@ export default function TestArena({ slug }) {
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>;
if (!current && mode !== 'multi') return <main className="arenaState">正在生成晋级图…</main>;
return (
<main className="arenaPage">
@@ -99,7 +104,7 @@ export default function TestArena({ slug }) {
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></>}
{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>
);
})}
@@ -107,9 +112,9 @@ export default function TestArena({ slug }) {
</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>
<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>
<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}
+7 -5
View File
@@ -1,8 +1,10 @@
'use client';
export async function apiRequest(path, options = {}) {
interface ApiOptions { method?: string; headers?: Record<string,string>; body?: unknown }
export async function apiRequest<T = unknown>(path: string, options: ApiOptions = {}): Promise<T> {
const token = typeof window === 'undefined' ? null : localStorage.getItem('pk_token');
const headers = { Accept: 'application/json', ...(options.headers || {}) };
const headers: Record<string,string> = { 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, {
@@ -16,17 +18,17 @@ export async function apiRequest(path, options = {}) {
const detail = typeof data.detail === 'string' ? data.detail : '请求失败';
throw new Error(detail);
}
return data;
return data as T;
}
export async function ensureLogin() {
export async function ensureLogin(): Promise<void> {
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', {
const session = await apiRequest<{ token: string }>('/api/v1/auth/xhs', {
method: 'POST',
body: { app_key: 'hub', code: `dev:web-${previewId}` }
});
+8 -6
View File
@@ -1,5 +1,7 @@
export function buildMatches(pool) {
const matches = [];
import type { BracketState, Candidate, ChoiceSide, Match } from './types';
export function buildMatches(pool: Candidate[]): Match[] {
const matches: Match[] = [];
for (let index = 0; index < pool.length; index += 2) {
matches.push({
left: pool[index],
@@ -10,7 +12,7 @@ export function buildMatches(pool) {
return matches;
}
export function createBracket(candidates) {
export function createBracket(candidates: Candidate[]): BracketState {
return {
round: 1,
pool: [...candidates],
@@ -21,7 +23,7 @@ export function createBracket(candidates) {
};
}
export function chooseMatch(state, matchIndex, side) {
export function chooseMatch(state: BracketState, matchIndex: number, side: ChoiceSide): { state: BracketState; finished: boolean } {
const match = state.matches[matchIndex];
if (!match?.right || match.winner) return { state, finished: false };
const winner = side === 'right' ? match.right : match.left;
@@ -41,13 +43,13 @@ export function chooseMatch(state, matchIndex, side) {
}]
};
if (matches.every(item => item.winner)) {
const pool = matches.map(item => item.winner);
const pool = matches.map(item => item.winner).filter((item): item is Candidate => Boolean(item));
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) {
export function firstOpenMatch(state: BracketState): number {
return state.matches.findIndex(match => match.right && !match.winner);
}
+67
View File
@@ -0,0 +1,67 @@
import type { TestResult } from './types';
type ThemeId=keyof typeof POSTER_THEMES;type LayoutId='symmetric'|'single';type ViewId='overview'|'left'|'right'|'top16'|'top8'|'final';
interface TreeNode{id:string;name:string;round:number;children:TreeNode[];x:number;y:number}
interface Box{x:number;y:number;width:number;height:number}interface Theme{page:string;paper:string;ink:string;muted:string;grid:string;soft:string;accent:string}
interface PosterOptions{themeId?:ThemeId;layout?:LayoutId;view?:ViewId;caption?:string;sticker?:boolean;background?:HTMLImageElement|null;adjust?:Partial<Record<'brightness'|'contrast'|'saturate',number>>}
export const POSTER_THEMES = {
clean: { page:'#f4f4f4', paper:'#ffffff', ink:'#151515', muted:'#929292', grid:'#d8d8d8', soft:'#f7f7f7', accent:'#ff2442' },
cream: { page:'#eee9df', paper:'#fbf8f2', ink:'#24211d', muted:'#8f887e', grid:'#d5cec3', soft:'#f1ece4', accent:'#e34d35' },
night: { page:'#111114', paper:'#1b1b1f', ink:'#f7f7f7', muted:'#888891', grid:'#414148', soft:'#26262b', accent:'#ff3855' }
};
export function drawPoster(ctx:CanvasRenderingContext2D,result:TestResult,{themeId='clean',layout='symmetric',view='overview',caption='',sticker=true,background=null,adjust={}}:PosterOptions={}):void{
const theme=POSTER_THEMES[themeId]||POSTER_THEMES.clean,W=1080,H=1440;
ctx.clearRect(0,0,W,H);ctx.fillStyle=theme.page;ctx.fillRect(0,0,W,H);
if(background){ctx.save();ctx.filter=`brightness(${adjust.brightness??100}%) contrast(${adjust.contrast??100}%) saturate(${adjust.saturate??100}%)`;cover(ctx,background,0,0,W,H);ctx.restore();ctx.fillStyle=themeId==='night'?'#111114e8':'#f4f4f4e8';ctx.fillRect(0,0,W,H);}
ctx.fillStyle=theme.ink;ctx.font='700 22px system-ui';ctx.fillText('PK LAB / MY BRACKET',54,54);
ctx.font='800 48px system-ui';ctx.fillText(result.test_title,54,115);
ctx.fillStyle=theme.muted;ctx.font='400 20px system-ui';ctx.fillText('每一次选择,都留在这张晋级路线里',54,151);
rounded(ctx,48,184,984,1110,18);ctx.fillStyle=theme.paper;ctx.fill();
const tree=buildTree(result),selected=selectTree(tree,view);
drawBracketTree(ctx,selected,{x:72,y:250,width:936,height:980},theme,layout,view);
ctx.fillStyle=theme.ink;ctx.font='700 26px system-ui';ctx.fillText(caption||`最终选择 ${result.champion_name}`,54,1350);
ctx.fillStyle=theme.muted;ctx.font='400 17px system-ui';ctx.fillText('保存图片,分享你的完整晋级路线',54,1385);
if(sticker){rounded(ctx,884,50,142,48,24);ctx.fillStyle=theme.accent;ctx.fill();ctx.fillStyle='#fff';ctx.font='800 17px system-ui';ctx.textAlign='center';ctx.fillText('NO.1 PICK',955,81);ctx.textAlign='left';}
}
export function buildTree(result:TestResult):TreeNode{
const decisions=[...(result.decisions||[])],names=result.candidate_names||{},maxRound=Math.max(1,...decisions.map(item=>item.round));
const build=(id:string,before:number):TreeNode=>{const decision=decisions.filter(item=>item.winner_id===id&&item.round<before).sort((a,b)=>b.round-a.round)[0];if(!decision)return{id,name:names[id]||id,round:0,children:[],x:0,y:0};return{id,name:names[id]||id,round:decision.round,children:[build(decision.left_id,decision.round),build(decision.right_id,decision.round)],x:0,y:0};};
return build(result.champion_id||decisions.at(-1)?.winner_id||'',maxRound+1);
}
function selectTree(tree:TreeNode,view:ViewId):TreeNode{if(view==='left'&&tree.children[0])return tree.children[0];if(view==='right'&&tree.children[1])return tree.children[1];const levels:Partial<Record<ViewId,number>>={top16:3,top8:2,final:1};const level=levels[view];if(!level)return tree;const minimum=Math.max(0,tree.round-level);const prune=(node:TreeNode):TreeNode=>node.round<=minimum?{...node,children:[]}:{...node,children:node.children.map(prune)};return prune(tree);}
function drawBracketTree(ctx:CanvasRenderingContext2D,tree:TreeNode,box:Box,theme:Theme,layout:LayoutId,view:ViewId):void{
if(!tree){ctx.fillStyle=theme.muted;ctx.font='24px system-ui';ctx.fillText('暂无晋级数据',box.x,box.y+60);return;}
const symmetric=layout==='symmetric'&&view!=='left'&&view!=='right'&&tree.children.length===2;
if(symmetric)drawSymmetric(ctx,tree,box,theme);else drawSingle(ctx,tree,box,theme);
}
function drawSingle(ctx:CanvasRenderingContext2D,tree:TreeNode,box:Box,theme:Theme):void{
const leaves:TreeNode[]=[];collectLeaves(tree,leaves);const minRound=Math.min(...leaves.map(node=>node.round)),maxRound=Math.max(tree.round,minRound+1);assignLeafY(leaves,box.y+48,box.y+box.height-38);assignInternalY(tree);
walk(tree,node=>{node.x=box.x+22+(node.round-minRound)/(maxRound-minRound)*(box.width-154);});
roundHeaders(ctx,box,minRound,maxRound,theme);
drawEdges(ctx,tree,theme);drawNodes(ctx,tree,theme,{width:122,align:'left'});
}
function drawSymmetric(ctx:CanvasRenderingContext2D,tree:TreeNode,box:Box,theme:Theme):void{
const left=tree.children[0],right=tree.children[1],middle=box.x+box.width/2,sideWidth=box.width/2-46;
if(!left||!right)return;
const leftLeaves:TreeNode[]=[],rightLeaves:TreeNode[]=[];collectLeaves(left,leftLeaves);collectLeaves(right,rightLeaves);assignLeafY(leftLeaves,box.y+48,box.y+box.height-38);assignLeafY(rightLeaves,box.y+48,box.y+box.height-38);assignInternalY(left);assignInternalY(right);tree.y=(left.y+right.y)/2;tree.x=middle;
const depth=Math.max(1,tree.round);walk(left,node=>{node.x=middle-32-(tree.round-node.round)/depth*sideWidth;});walk(right,node=>{node.x=middle+32+(tree.round-node.round)/depth*sideWidth;});
ctx.fillStyle=theme.muted;ctx.font='600 13px system-ui';ctx.fillText('LEFT BRACKET',box.x+4,box.y+17);ctx.textAlign='right';ctx.fillText('RIGHT BRACKET',box.x+box.width-4,box.y+17);ctx.textAlign='left';
drawEdges(ctx,tree,theme);drawNodes(ctx,tree,theme,{width:76,align:'center'});
}
function roundHeaders(ctx:CanvasRenderingContext2D,box:Box,minRound:number,maxRound:number,theme:Theme):void{ctx.fillStyle=theme.muted;ctx.font='600 12px system-ui';for(let round=minRound;round<=maxRound;round+=1){const x=box.x+22+(round-minRound)/(maxRound-minRound)*(box.width-154);ctx.fillText(round===minRound?'候选':round===maxRound?'冠军':`第 ${round} 轮`,x,box.y+17);}}
function drawEdges(ctx:CanvasRenderingContext2D,tree:TreeNode,theme:Theme):void{ctx.strokeStyle=theme.grid;ctx.lineWidth=1.4;walk(tree,parent=>{for(const child of parent.children){const turn=child.x+(parent.x-child.x)*.52;ctx.beginPath();ctx.moveTo(child.x,child.y);ctx.lineTo(turn,child.y);ctx.lineTo(turn,parent.y);ctx.lineTo(parent.x,parent.y);ctx.stroke();}});}
function drawNodes(ctx:CanvasRenderingContext2D,tree:TreeNode,theme:Theme,{width,align}:{width:number;align:'left'|'center'}):void{walk(tree,node=>{const champion=node===tree,h=24,x=align==='center'?node.x-width/2:node.x,y=node.y-h/2;ctx.fillStyle=champion?theme.accent:theme.soft;ctx.strokeStyle=champion?theme.accent:theme.grid;ctx.lineWidth=1;ctx.fillRect(x,y,width,h);ctx.strokeRect(x,y,width,h);ctx.fillStyle=champion?'#fff':theme.ink;ctx.font=`${champion?'700':'500'} ${width<90?10:12}px system-ui`;ctx.textAlign='center';ctx.textBaseline='middle';ctx.fillText(clip(node.name,width<90?5:8),x+width/2,node.y+.5);ctx.textAlign='left';ctx.textBaseline='alphabetic';});}
function assignLeafY(leaves:TreeNode[],start:number,end:number):void{const gap=(end-start)/Math.max(1,leaves.length-1);leaves.forEach((node,index)=>{node.y=leaves.length===1?(start+end)/2:start+index*gap;});}
function assignInternalY(node:TreeNode):number{if(!node.children.length)return node.y;node.children.forEach(assignInternalY);node.y=node.children.reduce((sum,child)=>sum+child.y,0)/node.children.length;return node.y;}
function collectLeaves(node:TreeNode,out:TreeNode[]):void{if(!node.children.length)out.push(node);else node.children.forEach(child=>collectLeaves(child,out));}
function walk(node:TreeNode,visit:(node:TreeNode)=>void):void{visit(node);node.children.forEach(child=>walk(child,visit));}
function clip(value:string,length:number):string{return value.length>length?`${value.slice(0,length-1)}…`:value;}
function rounded(ctx:CanvasRenderingContext2D,x:number,y:number,w:number,h:number,r:number):void{ctx.beginPath();ctx.roundRect(x,y,w,h,r);}
function cover(ctx:CanvasRenderingContext2D,image:HTMLImageElement,x:number,y:number,w:number,h:number):void{const ratio=Math.max(w/image.width,h/image.height),dw=image.width*ratio,dh=image.height*ratio;ctx.drawImage(image,x+(w-dw)/2,y+(h-dh)/2,dw,dh);}
+12
View File
@@ -0,0 +1,12 @@
export interface Candidate { id: string; name: string; title?: string; description?: string; image_url?: string | null }
export interface TestSummary { slug: string; title: string; subtitle: string; description: string; candidate_count: number; run_count: number }
export interface TestDetail extends TestSummary { candidates: Candidate[] }
export interface Decision { round: number; left_id: string; right_id: string; winner_id: string }
export interface TestResult {
id: string; test_slug: string; test_title: string; champion_id: string; champion_name: string;
runner_up_name?: string | null; completed_at: string; ranking_names?: string[];
decisions: Decision[]; candidate_names: Record<string,string>;
}
export interface Match { left: Candidate; right: Candidate | null; winner: Candidate | null }
export interface BracketState { round: number; pool: Candidate[]; matches: Match[]; eliminated: Candidate[]; decisions: Decision[]; offset: number }
export type ChoiceSide = 'left' | 'right';
+7
View File
@@ -0,0 +1,7 @@
/// <reference types="next" />
/// <reference types="next/image-types/global" />
import "./.next/types/routes.d.ts";
import "./.next/types/root-params.d.ts";
// NOTE: This file should not be edited
// see https://nextjs.org/docs/app/api-reference/config/typescript for more information.
+52 -5
View File
@@ -14,8 +14,12 @@
"react-dom": "19.3.0"
},
"devDependencies": {
"@types/node": "^24.7.0",
"@types/react": "^19.2.2",
"@types/react-dom": "^19.2.2",
"eslint": "^9.35.0",
"eslint-config-next": "16.3.5"
"eslint-config-next": "16.3.5",
"typescript": "^5.9.3"
}
},
"node_modules/@babel/code-frame": {
@@ -1347,6 +1351,36 @@
"dev": true,
"license": "MIT"
},
"node_modules/@types/node": {
"version": "24.13.6",
"resolved": "https://registry.npmjs.org/@types/node/-/node-24.13.6.tgz",
"integrity": "sha512-SGrw/h3KPFshy3OE6ZL53LMBG5vGQQ8/gIpiqz/kRZhPJ7HgwCEs8LBuNtWLa8dvGZVpSF7+Bf+c11HUrCb/yg==",
"dev": true,
"license": "MIT",
"dependencies": {
"undici-types": "~7.18.0"
}
},
"node_modules/@types/react": {
"version": "19.3.0",
"resolved": "https://registry.npmjs.org/@types/react/-/react-19.3.0.tgz",
"integrity": "sha512-N0rFCuH9YoxG9/m61l9MfpJKfmLOVU0em7ipIz6TRgSSkvReLB9vL85GB+yr8Bs5leqpvg96JSwF4ZS1s4viQg==",
"dev": true,
"license": "MIT",
"dependencies": {
"csstype": "^3.2.2"
}
},
"node_modules/@types/react-dom": {
"version": "19.3.0",
"resolved": "https://registry.npmjs.org/@types/react-dom/-/react-dom-19.3.0.tgz",
"integrity": "sha512-ZI7bU42mZXXKHn/qNLEw2IrbiINU7X5+vfgdixBHkCNpYWXjKgfQ/P+uyGb5CjOLB9UcnTeg3rylQtV2hym44Q==",
"dev": true,
"license": "MIT",
"peerDependencies": {
"@types/react": "^19.3.0"
}
},
"node_modules/@typescript-eslint/eslint-plugin": {
"version": "8.70.0",
"resolved": "https://registry.npmjs.org/@typescript-eslint/eslint-plugin/-/eslint-plugin-8.70.0.tgz",
@@ -2481,6 +2515,13 @@
"node": ">= 8"
}
},
"node_modules/csstype": {
"version": "3.2.3",
"resolved": "https://registry.npmjs.org/csstype/-/csstype-3.2.3.tgz",
"integrity": "sha512-z1HGKcYy2xA8AGQfwrn0PAy+PB7X/GSj3UVJW9qKyn43xWa+gl5nXmU4qqLMRzWVLFC8KusUX8T/0kCiOYpAIQ==",
"dev": true,
"license": "MIT"
},
"node_modules/damerau-levenshtein": {
"version": "1.0.8",
"resolved": "https://registry.npmjs.org/damerau-levenshtein/-/damerau-levenshtein-1.0.8.tgz",
@@ -5867,12 +5908,11 @@
}
},
"node_modules/typescript": {
"version": "6.0.3",
"resolved": "https://registry.npmjs.org/typescript/-/typescript-6.0.3.tgz",
"integrity": "sha512-y2TvuxSZPDyQakkFRPZHKFm+KKVqIisdg9/CZwm9ftvKXLP8NRWj38/ODjNbr43SsoXqNuAisEf1GdCxqWcdBw==",
"version": "5.9.3",
"resolved": "https://registry.npmjs.org/typescript/-/typescript-5.9.3.tgz",
"integrity": "sha512-jl1vZzPDinLr9eUt3J/t7V6FgNEw9QjvBPdysz9KfQDD41fQrC2Y4vKQdiaUpFT4bXlb1RHhLpp8wtm6M5TgSw==",
"dev": true,
"license": "Apache-2.0",
"peer": true,
"bin": {
"tsc": "bin/tsc",
"tsserver": "bin/tsserver"
@@ -5924,6 +5964,13 @@
"url": "https://github.com/sponsors/ljharb"
}
},
"node_modules/undici-types": {
"version": "7.18.2",
"resolved": "https://registry.npmjs.org/undici-types/-/undici-types-7.18.2.tgz",
"integrity": "sha512-AsuCzffGHJybSaRrmr5eHr81mwJU3kjw6M+uprWvCXiNeN9SOGwQ3Jn8jb8m3Z6izVgknn1R0FTCEAP2QrLY/w==",
"dev": true,
"license": "MIT"
},
"node_modules/unrs-resolver": {
"version": "1.12.2",
"resolved": "https://registry.npmjs.org/unrs-resolver/-/unrs-resolver-1.12.2.tgz",
+5 -1
View File
@@ -15,7 +15,11 @@
"react-dom": "19.3.0"
},
"devDependencies": {
"@types/node": "^24.7.0",
"@types/react": "^19.2.2",
"@types/react-dom": "^19.2.2",
"eslint": "^9.35.0",
"eslint-config-next": "16.3.5"
"eslint-config-next": "16.3.5",
"typescript": "^5.9.3"
}
}
+41
View File
@@ -0,0 +1,41 @@
{
"compilerOptions": {
"target": "ES2022",
"lib": [
"dom",
"dom.iterable",
"esnext"
],
"allowJs": false,
"skipLibCheck": true,
"strict": true,
"noEmit": true,
"esModuleInterop": true,
"module": "esnext",
"moduleResolution": "bundler",
"resolveJsonModule": true,
"isolatedModules": true,
"jsx": "react-jsx",
"incremental": true,
"plugins": [
{
"name": "next"
}
],
"paths": {
"@/*": [
"./*"
]
}
},
"include": [
"next-env.d.ts",
"**/*.ts",
"**/*.tsx",
".next/types/**/*.ts",
".next/dev/types/**/*.ts"
],
"exclude": [
"node_modules"
]
}