Compare commits

...

10 Commits

Author SHA1 Message Date
8bc4980aa4 better history delete 2025-07-03 10:19:50 +08:00
8c7a6f2174 better chinese prompt 2025-07-03 10:05:01 +08:00
327a32355a better chinese vs 2025-07-03 09:40:23 +08:00
6b02b2d00e better chinese 2025-07-03 00:51:22 +08:00
8c5273790a better layout 2025-07-03 00:49:29 +08:00
cbeca17ef0 add chinese 2025-07-03 00:45:59 +08:00
8cff9808f0 click to enter 2025-07-03 00:38:43 +08:00
e18588d5d4 add ad 2025-07-03 00:36:18 +08:00
4040116649 fix layout 2025-07-03 00:34:50 +08:00
6af5461bb8 add tracker code 2025-07-03 00:30:56 +08:00
15 changed files with 5601 additions and 38 deletions

View File

@ -22,10 +22,12 @@ npm install
cp .env.example .env.local
```
3. Add your Replicate API token to `.env.local`:
3. Add your OpenRouter API key to `.env.local`:
```
REPLICATE_API_TOKEN=your_replicate_api_token_here
REPLICATE_MODEL=meta/llama-2-70b-chat:02e509c789964a7ea8736978a43525956ef40397be9033abf9fd2badfe68c9e3
OPENROUTER_API_KEY=your_openrouter_api_key_here
OPENROUTER_MODEL=anthropic/claude-3.5-sonnet
OPENROUTER_CHINESE_MODEL=deepseek/deepseek-chat
NEXT_PUBLIC_SITE_URL=https://anything-vs-anything.com
```
4. Run the development server:
@ -44,16 +46,19 @@ npm run dev
## Environment Variables
- `REPLICATE_API_TOKEN`: Your Replicate API token (required)
- `REPLICATE_MODEL`: The Replicate model to use (optional, defaults to Llama 2 70B)
- `OPENROUTER_API_KEY`: Your OpenRouter API key (required)
- `OPENROUTER_MODEL`: The default model to use (optional, defaults to Claude 3.5 Sonnet)
- `OPENROUTER_CHINESE_MODEL`: The model to use for Chinese comparisons (optional, defaults to DeepSeek Chat for better Chinese support)
- `NEXT_PUBLIC_SITE_URL`: Your site URL for API referrer (optional)
## Tech Stack
- Next.js 15 with App Router
- TypeScript
- Tailwind CSS
- Replicate AI API
- OpenRouter AI API
- React Markdown for table rendering
- Automatic Chinese/English model switching for better localization
## Deploy on Vercel

4663
pnpm-lock.yaml generated Normal file

File diff suppressed because it is too large Load Diff

View File

@ -2,7 +2,7 @@ import { NextRequest, NextResponse } from 'next/server';
export async function POST(request: NextRequest) {
try {
const { item1, item2, description1, description2 } = await request.json();
const { item1, item2, description1, description2, language } = await request.json();
if (!item1 || !item2) {
return NextResponse.json(
@ -11,11 +11,41 @@ export async function POST(request: NextRequest) {
);
}
const prompt = `Compare ${item1} and ${item2} in a detailed table format. ${
description1 ? `Additional context for ${item1}: ${description1}` : ''
} ${
description2 ? `Additional context for ${item2}: ${description2}` : ''
}
// 根据传入的语言参数判断,默认为英文
const isChinese = language === 'zh-CN';
console.log(`isChinese? [${isChinese}]`)
const prompt = isChinese ?
`请详细比较 ${item1}${item2},用中文表格格式展示。${description1 ? `\n\n${item1} 的补充信息:${description1}` : ''
}${description2 ? `\n${item2} 的补充信息:${description2}` : ''
}
##
1. **使**
2. ****
3. **使**
4. **使**
##
-
-
-
-
-
- 使 markdown
##
-
- ${item1}
- ${item2}
` :
`Compare ${item1} and ${item2} in a detailed table format. ${description1 ? `Additional context for ${item1}: ${description1}` : ''
} ${description2 ? `Additional context for ${item2}: ${description2}` : ''
}
Please provide a comprehensive comparison in a markdown table format with the following structure:
- Create rows for different comparison aspects (features, pros, cons, price range, best use cases, etc.)
@ -35,7 +65,9 @@ The table should have three columns: Aspect, ${item1}, ${item2}`;
'X-Title': 'Anything vs Anything',
},
body: JSON.stringify({
model: process.env.OPENROUTER_MODEL || 'anthropic/claude-3.5-sonnet',
model: isChinese && process.env.OPENROUTER_CHINESE_MODEL
? process.env.OPENROUTER_CHINESE_MODEL
: process.env.OPENROUTER_MODEL || 'anthropic/claude-3.5-sonnet',
messages: [
{
role: 'user',

View File

@ -27,6 +27,10 @@ export const metadata: Metadata = {
metadataBase: new URL(process.env.NEXT_PUBLIC_SITE_URL || 'https://anything-vs-anything.com'),
alternates: {
canonical: '/',
languages: {
'en': '/',
'zh-CN': '/zh-CN',
},
},
openGraph: {
title: "Anything vs Anything - AI-Powered Comparison Tool",
@ -102,6 +106,17 @@ export default function RootLayout({
})
}}
/>
<script defer src="https://umami.frytea.com/script.js" data-website-id="9d16d648-a83d-4616-94d6-ec3bb1f8e0b7"></script>
<script
src="https://rybbit.frytea.com/api/script.js"
data-site-id="13"
defer
></script>
<script
async
src="https://pagead2.googlesyndication.com/pagead/js/adsbygoogle.js?client=ca-pub-7296634171837358"
crossOrigin="anonymous"
></script>
</head>
<body
className={`${geistSans.variable} ${geistMono.variable} antialiased`}

View File

@ -4,11 +4,27 @@ import { useState } from 'react';
import ComparisonForm from '@/components/ComparisonForm';
import ComparisonResults from '@/components/ComparisonResults';
import ComparisonHistory, { HistoryItem } from '@/components/ComparisonHistory';
import ComparisonTips from '@/components/ComparisonTips';
import AdBanner from '@/components/AdBanner';
import LanguageSwitcher from '@/components/LanguageSwitcher';
import { saveToHistory } from '@/utils/historyStorage';
export default function Home() {
const [comparisonResults, setComparisonResults] = useState<string | null>(null);
const [isLoading, setIsLoading] = useState(false);
const [selectedExample, setSelectedExample] = useState<{ item1: string; item2: string } | null>(null);
const popularExamples = [
{ item1: 'iPhone 15 Pro', item2: 'Samsung Galaxy S24 Ultra' },
{ item1: 'React', item2: 'Vue.js' },
{ item1: 'Coffee', item2: 'Tea' },
{ item1: 'Netflix', item2: 'Disney+' },
{ item1: 'Python', item2: 'JavaScript' }
];
const handleExampleClick = (example: { item1: string; item2: string }) => {
setSelectedExample(example);
};
const handleComparison = async (item1: string, item2: string, description1: string, description2: string) => {
setIsLoading(true);
@ -24,6 +40,7 @@ export default function Home() {
item2,
description1,
description2,
language: 'en',
}),
});
@ -55,6 +72,8 @@ export default function Home() {
<h1 className="text-4xl md:text-5xl font-bold text-gray-900 mb-6">
Anything vs Anything
</h1>
<LanguageSwitcher currentLang="en" />
<p className="text-xl md:text-2xl text-gray-600 mb-4">
Compare any two things using AI-powered analysis
</p>
@ -66,17 +85,30 @@ export default function Home() {
<div className="bg-gradient-to-r from-blue-50 to-indigo-50 rounded-xl p-6 mb-8">
<h2 className="text-lg font-semibold text-gray-800 mb-4">Popular Comparisons</h2>
<div className="flex flex-wrap justify-center gap-2 sm:gap-3">
<span className="px-3 sm:px-4 py-2 bg-white rounded-full text-xs sm:text-sm font-medium text-gray-700 shadow-sm hover:shadow-md transition-shadow cursor-pointer">iPhone vs Samsung Galaxy</span>
<span className="px-3 sm:px-4 py-2 bg-white rounded-full text-xs sm:text-sm font-medium text-gray-700 shadow-sm hover:shadow-md transition-shadow cursor-pointer">React vs Vue.js</span>
<span className="px-3 sm:px-4 py-2 bg-white rounded-full text-xs sm:text-sm font-medium text-gray-700 shadow-sm hover:shadow-md transition-shadow cursor-pointer">Coffee vs Tea</span>
<span className="px-3 sm:px-4 py-2 bg-white rounded-full text-xs sm:text-sm font-medium text-gray-700 shadow-sm hover:shadow-md transition-shadow cursor-pointer">Netflix vs Disney+</span>
<span className="px-3 sm:px-4 py-2 bg-white rounded-full text-xs sm:text-sm font-medium text-gray-700 shadow-sm hover:shadow-md transition-shadow cursor-pointer">Python vs JavaScript</span>
{popularExamples.map((example, index) => (
<button
key={index}
onClick={() => handleExampleClick(example)}
className="px-3 sm:px-4 py-2 bg-white rounded-full text-xs sm:text-sm font-medium text-gray-700 shadow-sm hover:shadow-md hover:bg-blue-50 hover:text-blue-700 transition-all cursor-pointer"
>
{example.item1} vs {example.item2}
</button>
))}
</div>
</div>
</div>
<div className={`bg-white rounded-xl shadow-lg p-6 sm:p-8 mb-8 transition-all duration-300 ${isLoading ? 'opacity-75 pointer-events-none' : ''}`}>
<ComparisonForm onSubmit={handleComparison} isLoading={isLoading} />
<ComparisonForm
onSubmit={handleComparison}
isLoading={isLoading}
selectedExample={selectedExample}
onExampleUsed={() => setSelectedExample(null)}
/>
</div>
<div className="mb-8">
<AdBanner />
</div>
<div className="mb-8">
@ -88,6 +120,10 @@ export default function Home() {
<ComparisonResults results={comparisonResults} />
</div>
)}
<div className="mt-8">
<ComparisonTips />
</div>
</div>
</main>
);

View File

@ -10,5 +10,11 @@ export default function sitemap(): MetadataRoute.Sitemap {
changeFrequency: 'daily',
priority: 1,
},
{
url: `${baseUrl}/zh-CN`,
lastModified: new Date(),
changeFrequency: 'daily',
priority: 0.9,
},
]
}

129
src/app/zh-CN/layout.tsx Normal file
View File

@ -0,0 +1,129 @@
import type { Metadata } from "next";
import { Geist, Geist_Mono } from "next/font/google";
import "../globals.css";
const geistSans = Geist({
variable: "--font-geist-sans",
subsets: ["latin"],
});
const geistMono = Geist_Mono({
variable: "--font-geist-mono",
subsets: ["latin"],
});
export const metadata: Metadata = {
title: "万物皆可比对 - AI智能比较工具",
description: "使用AI智能分析工具比较任何两个事物。获得产品、服务、概念等详细比较。免费在线比较生成器提供智能洞察。",
keywords: "比较工具, AI比较, 产品比较, 服务比较, 对比工具, 万物比较, 分析工具, 决策辅助",
authors: [{ name: "万物皆可比对" }],
creator: "万物皆可比对",
publisher: "万物皆可比对",
formatDetection: {
email: false,
address: false,
telephone: false,
},
metadataBase: new URL(process.env.NEXT_PUBLIC_SITE_URL || 'https://anything-vs-anything.com'),
alternates: {
canonical: '/zh-CN',
languages: {
'en': '/',
'zh-CN': '/zh-CN',
},
},
openGraph: {
title: "万物皆可比对 - AI智能比较工具",
description: "使用AI智能分析工具比较任何两个事物。获得产品、服务、概念等详细比较。",
url: '/zh-CN',
siteName: "万物皆可比对",
locale: 'zh_CN',
type: 'website',
images: [
{
url: '/og-image.png',
width: 1200,
height: 630,
alt: '万物皆可比对 - AI比较工具',
},
],
},
twitter: {
card: 'summary_large_image',
title: "万物皆可比对 - AI智能比较工具",
description: "使用AI智能分析工具比较任何两个事物。获得产品、服务、概念等详细比较。",
images: ['/og-image.png'],
},
robots: {
index: true,
follow: true,
googleBot: {
index: true,
follow: true,
'max-video-preview': -1,
'max-image-preview': 'large',
'max-snippet': -1,
},
},
verification: {
google: process.env.GOOGLE_SITE_VERIFICATION,
},
};
export default function RootLayout({
children,
}: Readonly<{
children: React.ReactNode;
}>) {
return (
<html lang="zh-CN">
<head>
<meta name="viewport" content="width=device-width, initial-scale=1" />
<link rel="icon" href="/favicon.ico" />
<link rel="apple-touch-icon" href="/apple-touch-icon.png" />
<link rel="manifest" href="/manifest.json" />
<meta name="theme-color" content="#3B82F6" />
<script
type="application/ld+json"
dangerouslySetInnerHTML={{
__html: JSON.stringify({
"@context": "https://schema.org",
"@type": "WebApplication",
"name": "万物皆可比对",
"description": "AI智能比较工具帮助您比较任何两个事物提供详细分析和洞察",
"url": process.env.NEXT_PUBLIC_SITE_URL + "/zh-CN" || "https://anything-vs-anything.com/zh-CN",
"applicationCategory": "Utility",
"operatingSystem": "Web",
"inLanguage": "zh-CN",
"offers": {
"@type": "Offer",
"price": "0",
"priceCurrency": "CNY"
},
"author": {
"@type": "Organization",
"name": "万物皆可比对"
}
})
}}
/>
<script defer src="https://umami.frytea.com/script.js" data-website-id="9d16d648-a83d-4616-94d6-ec3bb1f8e0b7"></script>
<script
src="https://rybbit.frytea.com/api/script.js"
data-site-id="13"
defer
></script>
<script
async
src="https://pagead2.googlesyndication.com/pagead/js/adsbygoogle.js?client=ca-pub-7296634171837358"
crossOrigin="anonymous"
></script>
</head>
<body
className={`${geistSans.variable} ${geistMono.variable} antialiased`}
>
{children}
</body>
</html>
);
}

530
src/app/zh-CN/page.tsx Normal file
View File

@ -0,0 +1,530 @@
'use client';
import { useState } from 'react';
import React from 'react';
import ReactMarkdown from 'react-markdown';
import remarkGfm from 'remark-gfm';
import { HistoryItem } from '@/components/ComparisonHistory';
import AdBanner from '@/components/AdBanner';
import LanguageSwitcher from '@/components/LanguageSwitcher';
import { saveToHistory, deleteHistoryItem } from '@/utils/historyStorage';
export default function HomePage() {
const [comparisonResults, setComparisonResults] = useState<string | null>(null);
const [isLoading, setIsLoading] = useState(false);
const [selectedExample, setSelectedExample] = useState<{ item1: string; item2: string } | null>(null);
const popularExamples = [
{ item1: 'iPhone 15 Pro', item2: '三星 Galaxy S24 Ultra' },
{ item1: 'React', item2: 'Vue.js' },
{ item1: '咖啡', item2: '茶' },
{ item1: 'Netflix', item2: 'Disney+' },
{ item1: 'Python', item2: 'JavaScript' }
];
const handleExampleClick = (example: { item1: string; item2: string }) => {
setSelectedExample(example);
};
const handleComparison = async (item1: string, item2: string, description1: string, description2: string) => {
setIsLoading(true);
try {
const response = await fetch('/api/compare', {
method: 'POST',
headers: {
'Content-Type': 'application/json',
},
body: JSON.stringify({
item1,
item2,
description1,
description2,
language: 'zh-CN',
}),
});
if (!response.ok) {
throw new Error('Failed to get comparison');
}
const data = await response.json();
setComparisonResults(data.comparison);
// Save to history
saveToHistory(item1, item2, description1, description2, data.comparison);
} catch (error) {
console.error('Error:', error);
setComparisonResults('比较过程中出现错误,请重试。');
} finally {
setIsLoading(false);
}
};
const handleSelectHistory = (historyItem: HistoryItem) => {
setComparisonResults(historyItem.result);
};
return (
<main className="min-h-screen bg-gradient-to-br from-blue-50 to-indigo-100 py-6 md:py-12">
<div className="max-w-4xl mx-auto px-4 sm:px-6 lg:px-8">
<div className="text-center mb-12">
<h1 className="text-4xl md:text-5xl font-bold text-gray-900 mb-6">
</h1>
<LanguageSwitcher currentLang="zh-CN" />
<p className="text-xl md:text-2xl text-gray-600 mb-4">
使AI智能分析比较任何两个事物
</p>
<p className="text-lg text-gray-500 max-w-3xl mx-auto mb-8">
-
</p>
<div className="bg-gradient-to-r from-blue-50 to-indigo-50 rounded-xl p-6 mb-8">
<h2 className="text-lg font-semibold text-gray-800 mb-4"></h2>
<div className="flex flex-wrap justify-center gap-2 sm:gap-3">
{popularExamples.map((example, index) => (
<button
key={index}
onClick={() => handleExampleClick(example)}
className="px-3 sm:px-4 py-2 bg-white rounded-full text-xs sm:text-sm font-medium text-gray-700 shadow-sm hover:shadow-md hover:bg-blue-50 hover:text-blue-700 transition-all cursor-pointer"
>
{example.item1} vs {example.item2}
</button>
))}
</div>
</div>
</div>
<div className={`bg-white rounded-xl shadow-lg p-6 sm:p-8 mb-8 transition-all duration-300 ${isLoading ? 'opacity-75 pointer-events-none' : ''}`}>
<ComparisonFormZH
onSubmit={handleComparison}
isLoading={isLoading}
selectedExample={selectedExample}
onExampleUsed={() => setSelectedExample(null)}
/>
</div>
<div className="mb-8">
<AdBanner />
</div>
<div className="mb-8">
<ComparisonHistoryZH onSelectHistory={handleSelectHistory} />
</div>
{comparisonResults && (
<div className="bg-white rounded-xl shadow-lg p-8 mt-8">
<ComparisonResultsZH results={comparisonResults} />
</div>
)}
<div className="mt-8">
<ComparisonTipsZH />
</div>
</div>
</main>
);
}
// Chinese version of ComparisonForm
function ComparisonFormZH({ onSubmit, isLoading, selectedExample, onExampleUsed }: {
onSubmit: (item1: string, item2: string, description1: string, description2: string) => void;
isLoading: boolean;
selectedExample?: { item1: string; item2: string } | null;
onExampleUsed?: () => void;
}) {
const [item1, setItem1] = useState('');
const [item2, setItem2] = useState('');
const [description1, setDescription1] = useState('');
const [description2, setDescription2] = useState('');
const [showDescriptions, setShowDescriptions] = useState(false);
// Handle selected example
React.useEffect(() => {
if (selectedExample) {
setItem1(selectedExample.item1);
setItem2(selectedExample.item2);
onExampleUsed?.();
}
}, [selectedExample, onExampleUsed]);
const examples = [
{ item1: 'iPhone 15 Pro', item2: '三星 Galaxy S24 Ultra', category: '智能手机' },
{ item1: 'React', item2: 'Vue.js', category: '前端框架' },
{ item1: '特斯拉 Model 3', item2: '宝马 i4', category: '电动汽车' },
{ item1: 'Netflix', item2: 'Disney+', category: '流媒体服务' },
{ item1: 'MacBook Pro', item2: 'ThinkPad X1 Carbon', category: '笔记本电脑' },
{ item1: '咖啡', item2: '茶', category: '饮品' }
];
const getRandomExample = () => {
return examples[Math.floor(Math.random() * examples.length)];
};
const fillRandomExample = () => {
const example = getRandomExample();
setItem1(example.item1);
setItem2(example.item2);
};
const handleSubmit = (e: React.FormEvent) => {
e.preventDefault();
if (item1.trim() && item2.trim()) {
onSubmit(item1.trim(), item2.trim(), description1.trim(), description2.trim());
}
};
return (
<div className="space-y-6">
<div className="text-center mb-6">
<h2 className="text-2xl font-bold text-gray-900 mb-2"></h2>
<p className="text-gray-600 mb-4"> - </p>
<button
type="button"
onClick={fillRandomExample}
className="text-blue-600 hover:text-blue-800 text-sm font-medium underline"
>
</button>
</div>
<form onSubmit={handleSubmit} className="space-y-6">
<div className="grid grid-cols-1 md:grid-cols-2 gap-6">
<div>
<label htmlFor="item1" className="block text-sm font-medium text-gray-700 mb-2">
</label>
<div className="relative">
<input
type="text"
id="item1"
value={item1}
onChange={(e) => setItem1(e.target.value)}
placeholder="例如iPhone 15 Pro、React、特斯拉 Model 3"
className={`w-full px-4 py-3 border border-gray-300 rounded-lg focus:ring-2 focus:ring-blue-500 focus:border-transparent transition-all duration-200 ${isLoading ? 'bg-gray-50 cursor-not-allowed' : 'bg-white'}`}
disabled={isLoading}
required
/>
{isLoading && (
<div className="absolute inset-0 flex items-center justify-center bg-gray-50 bg-opacity-75 rounded-lg">
<div className="animate-spin rounded-full h-5 w-5 border-b-2 border-blue-600"></div>
</div>
)}
</div>
</div>
<div>
<label htmlFor="item2" className="block text-sm font-medium text-gray-700 mb-2">
</label>
<div className="relative">
<input
type="text"
id="item2"
value={item2}
onChange={(e) => setItem2(e.target.value)}
placeholder="例如:三星 Galaxy S24、Vue.js、宝马 i4"
className={`w-full px-4 py-3 border border-gray-300 rounded-lg focus:ring-2 focus:ring-blue-500 focus:border-transparent transition-all duration-200 ${isLoading ? 'bg-gray-50 cursor-not-allowed' : 'bg-white'}`}
disabled={isLoading}
required
/>
{isLoading && (
<div className="absolute inset-0 flex items-center justify-center bg-gray-50 bg-opacity-75 rounded-lg">
<div className="animate-spin rounded-full h-5 w-5 border-b-2 border-blue-600"></div>
</div>
)}
</div>
</div>
</div>
<div className="text-center">
<button
type="button"
onClick={() => setShowDescriptions(!showDescriptions)}
className="text-blue-600 hover:text-blue-800 text-sm font-medium"
>
{showDescriptions ? '隐藏' : '添加'}
</button>
</div>
{showDescriptions && (
<div className="grid grid-cols-1 md:grid-cols-2 gap-6">
<div>
<label htmlFor="description1" className="block text-sm font-medium text-gray-700 mb-2">
{item1 || '第一个项目'}
</label>
<div className="relative">
<textarea
id="description1"
value={description1}
onChange={(e) => setDescription1(e.target.value)}
placeholder="关于第一个项目的额外详情、规格或背景..."
rows={3}
className={`w-full px-4 py-3 border border-gray-300 rounded-lg focus:ring-2 focus:ring-blue-500 focus:border-transparent transition-all duration-200 ${isLoading ? 'bg-gray-50 cursor-not-allowed' : 'bg-white'}`}
disabled={isLoading}
/>
{isLoading && (
<div className="absolute inset-0 flex items-center justify-center bg-gray-50 bg-opacity-75 rounded-lg">
<div className="animate-spin rounded-full h-5 w-5 border-b-2 border-blue-600"></div>
</div>
)}
</div>
</div>
<div>
<label htmlFor="description2" className="block text-sm font-medium text-gray-700 mb-2">
{item2 || '第二个项目'}
</label>
<div className="relative">
<textarea
id="description2"
value={description2}
onChange={(e) => setDescription2(e.target.value)}
placeholder="关于第二个项目的额外详情、规格或背景..."
rows={3}
className={`w-full px-4 py-3 border border-gray-300 rounded-lg focus:ring-2 focus:ring-blue-500 focus:border-transparent transition-all duration-200 ${isLoading ? 'bg-gray-50 cursor-not-allowed' : 'bg-white'}`}
disabled={isLoading}
/>
{isLoading && (
<div className="absolute inset-0 flex items-center justify-center bg-gray-50 bg-opacity-75 rounded-lg">
<div className="animate-spin rounded-full h-5 w-5 border-b-2 border-blue-600"></div>
</div>
)}
</div>
</div>
</div>
)}
<div className="text-center">
<button
type="submit"
disabled={isLoading || !item1.trim() || !item2.trim()}
className="px-8 py-4 bg-blue-600 text-white font-medium rounded-lg hover:bg-blue-700 focus:ring-2 focus:ring-blue-500 focus:ring-offset-2 disabled:opacity-50 disabled:cursor-not-allowed transition-all duration-200 flex items-center justify-center gap-2 mx-auto"
>
{isLoading ? (
<>
<div className="animate-spin rounded-full h-5 w-5 border-b-2 border-white"></div>
...
</>
) : (
'开始比较'
)}
</button>
</div>
</form>
</div>
);
}
// Chinese version of ComparisonHistory
function ComparisonHistoryZH({ onSelectHistory }: { onSelectHistory: (item: HistoryItem) => void }) {
const [history, setHistory] = useState<HistoryItem[]>([]);
const [isExpanded, setIsExpanded] = useState(false);
React.useEffect(() => {
const loadHistory = () => {
try {
const stored = localStorage.getItem('comparison-history');
if (stored) {
const parsed = JSON.parse(stored);
setHistory(parsed.slice(0, 10));
}
} catch (error) {
console.error('Error loading history:', error);
}
};
loadHistory();
const handleStorageChange = () => {
loadHistory();
};
window.addEventListener('storage', handleStorageChange);
window.addEventListener('comparison-history-updated', handleStorageChange);
return () => {
window.removeEventListener('storage', handleStorageChange);
window.removeEventListener('comparison-history-updated', handleStorageChange);
};
}, []);
const clearHistory = () => {
localStorage.removeItem('comparison-history');
setHistory([]);
window.dispatchEvent(new Event('comparison-history-updated'));
};
const handleDeleteItem = (e: React.MouseEvent, itemId: string) => {
e.stopPropagation();
deleteHistoryItem(itemId);
};
const formatDate = (timestamp: number) => {
return new Date(timestamp).toLocaleDateString('zh-CN', {
month: 'short',
day: 'numeric',
hour: '2-digit',
minute: '2-digit'
});
};
if (history.length === 0) {
return null;
}
return (
<div className="bg-white rounded-xl shadow-lg p-6">
<div className="flex items-center justify-between mb-4">
<h2 className="text-xl font-bold text-gray-900"></h2>
<div className="flex items-center gap-3">
<button
onClick={() => setIsExpanded(!isExpanded)}
className="text-blue-600 hover:text-blue-800 text-sm font-medium"
>
{isExpanded ? '显示更少' : `显示全部 (${history.length})`}
</button>
<button
onClick={clearHistory}
className="text-red-600 hover:text-red-800 text-sm font-medium"
>
</button>
</div>
</div>
<div className="space-y-3">
{(isExpanded ? history : history.slice(0, 3)).map((item) => (
<div
key={item.id}
onClick={() => onSelectHistory(item)}
className="p-4 border border-gray-200 rounded-lg hover:border-blue-300 hover:bg-blue-50 cursor-pointer transition-all duration-200 group relative"
>
<div className="flex items-center justify-between mb-2">
<div className="font-medium text-gray-900 flex-1">
<span className="text-blue-600">{item.item1}</span>
<span className="text-gray-400 mx-2">vs</span>
<span className="text-green-600">{item.item2}</span>
</div>
<div className="flex items-center gap-2">
<span className="text-xs text-gray-500">
{formatDate(item.timestamp)}
</span>
<button
onClick={(e) => handleDeleteItem(e, item.id)}
className="text-red-500 hover:text-red-700 p-1 rounded transition-all duration-200"
title="删除此比较"
>
<svg className="w-4 h-4" fill="none" stroke="currentColor" viewBox="0 0 24 24">
<path strokeLinecap="round" strokeLinejoin="round" strokeWidth={2} d="M19 7l-.867 12.142A2 2 0 0116.138 21H7.862a2 2 0 01-1.995-1.858L5 7m5 4v6m4-6v6m1-10V4a1 1 0 00-1-1h-4a1 1 0 00-1 1v3M4 7h16" />
</svg>
</button>
</div>
</div>
{(item.description1 || item.description2) && (
<div className="text-sm text-gray-600">
{item.description1 && (
<div className="truncate">
<strong>{item.item1}:</strong> {item.description1}
</div>
)}
{item.description2 && (
<div className="truncate">
<strong>{item.item2}:</strong> {item.description2}
</div>
)}
</div>
)}
</div>
))}
</div>
{!isExpanded && history.length > 3 && (
<div className="text-center mt-4">
<button
onClick={() => setIsExpanded(true)}
className="text-blue-600 hover:text-blue-800 text-sm font-medium"
>
{history.length - 3} ...
</button>
</div>
)}
</div>
);
}
// Chinese version of ComparisonResults
function ComparisonResultsZH({ results }: { results: string }) {
return (
<div>
<h2 className="text-2xl font-bold text-gray-900 mb-6"></h2>
<div className="prose prose-lg max-w-none">
<ReactMarkdown
remarkPlugins={[remarkGfm]}
components={{
table: ({ children }) => (
<div className="overflow-x-auto">
<table className="min-w-full divide-y divide-gray-200 border border-gray-300">
{children}
</table>
</div>
),
thead: ({ children }) => (
<thead className="bg-gray-50">{children}</thead>
),
tbody: ({ children }) => (
<tbody className="bg-white divide-y divide-gray-200">{children}</tbody>
),
tr: ({ children }) => (
<tr className="hover:bg-gray-50">{children}</tr>
),
th: ({ children }) => (
<th className="px-6 py-3 text-left text-xs font-medium text-gray-500 uppercase tracking-wider border-r border-gray-200 last:border-r-0">
{children}
</th>
),
td: ({ children }) => (
<td className="px-6 py-4 whitespace-pre-wrap text-sm text-gray-900 border-r border-gray-200 last:border-r-0">
{children}
</td>
),
}}
>
{results}
</ReactMarkdown>
</div>
</div>
);
}
// Chinese version of ComparisonTips
function ComparisonTipsZH() {
return (
<div className="bg-white rounded-xl shadow-lg p-6">
<h3 className="text-lg font-semibold text-gray-800 mb-4">💡 </h3>
<ul className="text-sm text-gray-600 space-y-2">
<li className="flex items-start">
<span className="text-blue-500 mr-2"></span>
<span>&quot;iPhone 15 Pro&quot; vs &quot;iPhone 15&quot;</span>
</li>
<li className="flex items-start">
<span className="text-blue-500 mr-2"></span>
<span></span>
</li>
<li className="flex items-start">
<span className="text-blue-500 mr-2"></span>
<span></span>
</li>
<li className="flex items-start">
<span className="text-blue-500 mr-2"></span>
<span>&quot;&quot; vs &quot;&quot;</span>
</li>
</ul>
</div>
);
}

View File

@ -0,0 +1,33 @@
'use client';
import { useEffect } from 'react';
declare global {
interface Window {
adsbygoogle: unknown[];
}
}
export default function AdBanner() {
useEffect(() => {
try {
(window.adsbygoogle = window.adsbygoogle || []).push({});
} catch (err) {
console.error('AdSense error:', err);
}
}, []);
return (
<div className="w-full">
{/* ava-horizon */}
<ins
className="adsbygoogle"
style={{ display: 'block' }}
data-ad-client="ca-pub-7296634171837358"
data-ad-slot="1608102231"
data-ad-format="auto"
data-full-width-responsive="true"
/>
</div>
);
}

View File

@ -1,19 +1,30 @@
'use client';
import { useState } from 'react';
import { useState, useEffect } from 'react';
interface ComparisonFormProps {
onSubmit: (item1: string, item2: string, description1: string, description2: string) => void;
isLoading: boolean;
selectedExample?: { item1: string; item2: string } | null;
onExampleUsed?: () => void;
}
export default function ComparisonForm({ onSubmit, isLoading }: ComparisonFormProps) {
export default function ComparisonForm({ onSubmit, isLoading, selectedExample, onExampleUsed }: ComparisonFormProps) {
const [item1, setItem1] = useState('');
const [item2, setItem2] = useState('');
const [description1, setDescription1] = useState('');
const [description2, setDescription2] = useState('');
const [showDescriptions, setShowDescriptions] = useState(false);
// Handle selected example
useEffect(() => {
if (selectedExample) {
setItem1(selectedExample.item1);
setItem2(selectedExample.item2);
onExampleUsed?.();
}
}, [selectedExample, onExampleUsed]);
const examples = [
{ item1: 'iPhone 15 Pro', item2: 'Samsung Galaxy S24 Ultra', category: 'Smartphones' },
{ item1: 'React', item2: 'Vue.js', category: 'Frontend Frameworks' },
@ -165,7 +176,7 @@ export default function ComparisonForm({ onSubmit, isLoading }: ComparisonFormPr
<button
type="submit"
disabled={isLoading || !item1.trim() || !item2.trim()}
className="px-8 py-4 bg-blue-600 text-white font-medium rounded-lg hover:bg-blue-700 focus:ring-2 focus:ring-blue-500 focus:ring-offset-2 disabled:opacity-50 disabled:cursor-not-allowed transition-all duration-200 flex items-center justify-center gap-2"
className="px-8 py-4 bg-blue-600 text-white font-medium rounded-lg hover:bg-blue-700 focus:ring-2 focus:ring-blue-500 focus:ring-offset-2 disabled:opacity-50 disabled:cursor-not-allowed transition-all duration-200 flex items-center justify-center gap-2 mx-auto"
>
{isLoading ? (
<>

View File

@ -1,6 +1,7 @@
'use client';
import { useState, useEffect } from 'react';
import { deleteHistoryItem } from '@/utils/historyStorage';
export interface HistoryItem {
id: string;
@ -55,6 +56,11 @@ export default function ComparisonHistory({ onSelectHistory }: ComparisonHistory
setHistory([]);
window.dispatchEvent(new Event('comparison-history-updated'));
};
const handleDeleteItem = (e: React.MouseEvent, itemId: string) => {
e.stopPropagation(); // Prevent triggering the onClick of the parent div
deleteHistoryItem(itemId);
};
const formatDate = (timestamp: number) => {
return new Date(timestamp).toLocaleDateString('en-US', {
@ -94,17 +100,28 @@ export default function ComparisonHistory({ onSelectHistory }: ComparisonHistory
<div
key={item.id}
onClick={() => onSelectHistory(item)}
className="p-4 border border-gray-200 rounded-lg hover:border-blue-300 hover:bg-blue-50 cursor-pointer transition-all duration-200"
className="p-4 border border-gray-200 rounded-lg hover:border-blue-300 hover:bg-blue-50 cursor-pointer transition-all duration-200 group relative"
>
<div className="flex items-center justify-between mb-2">
<div className="font-medium text-gray-900">
<div className="font-medium text-gray-900 flex-1">
<span className="text-blue-600">{item.item1}</span>
<span className="text-gray-400 mx-2">vs</span>
<span className="text-green-600">{item.item2}</span>
</div>
<span className="text-xs text-gray-500">
{formatDate(item.timestamp)}
</span>
<div className="flex items-center gap-2">
<span className="text-xs text-gray-500">
{formatDate(item.timestamp)}
</span>
<button
onClick={(e) => handleDeleteItem(e, item.id)}
className="text-red-500 hover:text-red-700 p-1 rounded transition-all duration-200"
title="Delete this comparison"
>
<svg className="w-4 h-4" fill="none" stroke="currentColor" viewBox="0 0 24 24">
<path strokeLinecap="round" strokeLinejoin="round" strokeWidth={2} d="M19 7l-.867 12.142A2 2 0 0116.138 21H7.862a2 2 0 01-1.995-1.858L5 7m5 4v6m4-6v6m1-10V4a1 1 0 00-1-1h-4a1 1 0 00-1 1v3M4 7h16" />
</svg>
</button>
</div>
</div>
{(item.description1 || item.description2) && (
<div className="text-sm text-gray-600">

View File

@ -11,7 +11,7 @@ export default function ComparisonResults({ results }: ComparisonResultsProps) {
return (
<div>
<h2 className="text-2xl font-bold text-gray-900 mb-6">Comparison Results</h2>
<div className="prose prose-lg max-w-none mb-8">
<div className="prose prose-lg max-w-none">
<ReactMarkdown
remarkPlugins={[remarkGfm]}
components={{
@ -46,16 +46,6 @@ export default function ComparisonResults({ results }: ComparisonResultsProps) {
{results}
</ReactMarkdown>
</div>
<div className="mt-8 p-4 bg-gray-50 rounded-lg border-t">
<h3 className="text-sm font-semibold text-gray-700 mb-2">💡 Tips for better comparisons:</h3>
<ul className="text-sm text-gray-600 space-y-1">
<li> Be specific: &quot;iPhone 15 Pro&quot; vs &quot;iPhone 15&quot;</li>
<li> Add context in descriptions for nuanced analysis</li>
<li> Compare similar categories for meaningful results</li>
<li> Try abstract concepts too: &quot;Remote work&quot; vs &quot;Office work&quot;</li>
</ul>
</div>
</div>
);
}

View File

@ -0,0 +1,25 @@
export default function ComparisonTips() {
return (
<div className="bg-white rounded-xl shadow-lg p-6">
<h3 className="text-lg font-semibold text-gray-800 mb-4">💡 Tips for better comparisons</h3>
<ul className="text-sm text-gray-600 space-y-2">
<li className="flex items-start">
<span className="text-blue-500 mr-2"></span>
<span>Be specific: &quot;iPhone 15 Pro&quot; vs &quot;iPhone 15&quot;</span>
</li>
<li className="flex items-start">
<span className="text-blue-500 mr-2"></span>
<span>Add context in descriptions for nuanced analysis</span>
</li>
<li className="flex items-start">
<span className="text-blue-500 mr-2"></span>
<span>Compare similar categories for meaningful results</span>
</li>
<li className="flex items-start">
<span className="text-blue-500 mr-2"></span>
<span>Try abstract concepts too: &quot;Remote work&quot; vs &quot;Office work&quot;</span>
</li>
</ul>
</div>
);
}

View File

@ -0,0 +1,52 @@
'use client';
import Link from 'next/link';
interface Language {
code: string;
name: string;
nativeName: string;
flag: string;
}
interface LanguageSwitcherProps {
currentLang: string;
}
const languages: Language[] = [
{ code: 'en', name: 'English', nativeName: 'English', flag: '🇺🇸' },
{ code: 'zh-CN', name: 'Chinese (Simplified)', nativeName: '简体中文', flag: '🇨🇳' },
];
export default function LanguageSwitcher({ currentLang }: LanguageSwitcherProps) {
const getLocalizedPath = (langCode: string) => {
if (langCode === 'en') {
return '/';
}
return `/${langCode}`;
};
const otherLanguages = languages.filter(lang => lang.code !== currentLang);
if (otherLanguages.length === 0) {
return null;
}
return (
<div className="flex items-center justify-center gap-3 mb-6">
<span className="text-sm text-gray-500">Switch language:</span>
<div className="flex gap-2">
{otherLanguages.map((lang) => (
<Link
key={lang.code}
href={getLocalizedPath(lang.code)}
className="flex items-center gap-2 px-3 py-1.5 bg-white rounded-lg shadow-sm hover:shadow-md border border-gray-200 hover:border-blue-300 transition-all duration-200 text-sm font-medium text-gray-700 hover:text-blue-700"
>
<span className="text-base">{lang.flag}</span>
<span>{lang.nativeName}</span>
</Link>
))}
</div>
</div>
);
}

View File

@ -51,4 +51,23 @@ export const getHistory = (): HistoryItem[] => {
console.error('Error loading history:', error);
return [];
}
};
export const deleteHistoryItem = (id: string) => {
try {
const existing = localStorage.getItem('comparison-history');
if (existing) {
const history: HistoryItem[] = JSON.parse(existing);
const updatedHistory = history.filter(item => item.id !== id);
localStorage.setItem('comparison-history', JSON.stringify(updatedHistory));
// Dispatch custom event for same-page updates
window.dispatchEvent(new Event('comparison-history-updated'));
return true;
}
return false;
} catch (error) {
console.error('Error deleting history item:', error);
return false;
}
};