feat: 重构联系页面并增强安全性

refactor: 优化导航和路由逻辑

fix: 修复移动端样式问题

perf: 优化字体加载和性能

test: 添加安全性和可访问性测试

style: 调整按钮和表单样式

chore: 更新依赖版本

ci: 添加安全头配置

build: 优化构建配置

docs: 更新常量信息
This commit is contained in:
张翔
2026-03-01 10:56:54 +08:00
parent 13c4a2ca49
commit 9cbc80742a
24 changed files with 1087 additions and 440 deletions
+1 -1
View File
@@ -9,7 +9,7 @@
"version": "1.0.0",
"hasInstallScript": true,
"devDependencies": {
"@axe-core/playwright": "^4.9.0",
"@axe-core/playwright": "^4.11.1",
"@playwright/test": "^1.58.2",
"@types/node": "^20.11.0",
"allure-commandline": "^2.37.0",
+1 -1
View File
@@ -22,7 +22,7 @@
"install": "playwright install --with-deps"
},
"devDependencies": {
"@axe-core/playwright": "^4.9.0",
"@axe-core/playwright": "^4.11.1",
"@playwright/test": "^1.58.2",
"@types/node": "^20.11.0",
"allure-commandline": "^2.37.0",
+2 -2
View File
@@ -61,8 +61,8 @@ export default defineConfig({
},
],
webServer: env.name === 'development' ? {
command: 'npm run dev',
url: 'http://localhost:3001',
command: 'cd .. && npm run dev',
url: 'http://localhost:3000',
timeout: 120000,
reuseExistingServer: !process.env.CI,
} : undefined,
@@ -37,8 +37,9 @@ test.describe('可访问性测试 @accessibility', () => {
test('表单输入应该有label', async ({ page }) => {
await page.goto('http://localhost:3000/contact');
await page.waitForLoadState('networkidle');
const inputs = page.locator('input, textarea, select');
const inputs = page.locator('input:not([type="hidden"]), textarea, select');
const count = await inputs.count();
for (let i = 0; i < count; i++) {
@@ -101,8 +102,9 @@ test.describe('可访问性测试 @accessibility', () => {
test('焦点元素应该可见', async ({ page }) => {
await page.goto('http://localhost:3000');
await page.waitForLoadState('networkidle');
const focusableElements = page.locator('a[href], button, input, textarea, select, [tabindex]:not([tabindex="-1"])');
const focusableElements = page.locator('a[href]:visible, button:visible, input:visible, textarea:visible, select:visible, [tabindex]:not([tabindex="-1"]):visible');
const count = await focusableElements.count();
for (let i = 0; i < Math.min(count, 10); i++) {
@@ -0,0 +1,280 @@
import { test, expect } from '@playwright/test';
import AxeBuilder from '@axe-core/playwright';
test.describe('Accessibility Tests (WCAG 2.1 AA)', () => {
test('home page should not have accessibility violations', async ({ page }) => {
await page.goto('/');
await page.waitForLoadState('networkidle');
const accessibilityScanResults = await new AxeBuilder({ page })
.withTags(['wcag2a', 'wcag2aa', 'wcag21a', 'wcag21aa'])
.analyze();
expect(accessibilityScanResults.violations).toEqual([]);
});
test('contact page should not have accessibility violations', async ({ page }) => {
await page.goto('/contact');
await page.waitForLoadState('networkidle');
const accessibilityScanResults = await new AxeBuilder({ page })
.withTags(['wcag2a', 'wcag2aa', 'wcag21a', 'wcag21aa'])
.analyze();
expect(accessibilityScanResults.violations).toEqual([]);
});
test('all form inputs should have associated labels', async ({ page }) => {
await page.goto('/contact');
await page.waitForLoadState('networkidle');
const inputs = await page.locator('input:not([type="hidden"]), textarea, select').all();
for (const input of inputs) {
const id = await input.getAttribute('id');
const ariaLabel = await input.getAttribute('aria-label');
const ariaLabelledBy = await input.getAttribute('aria-labelledby');
if (id) {
const label = page.locator(`label[for="${id}"]`);
const hasLabel = await label.count() > 0;
expect(hasLabel || ariaLabel || ariaLabelledBy).toBeTruthy();
} else {
expect(ariaLabel || ariaLabelledBy).toBeTruthy();
}
}
});
test('all images should have alt text', async ({ page }) => {
await page.goto('/');
const images = await page.locator('img').all();
for (const img of images) {
const alt = await img.getAttribute('alt');
const role = await img.getAttribute('role');
expect(alt !== null || role === 'presentation').toBeTruthy();
}
});
test('all buttons should have accessible names', async ({ page }) => {
await page.goto('/');
const buttons = await page.locator('button').all();
for (const button of buttons) {
const text = await button.textContent();
const ariaLabel = await button.getAttribute('aria-label');
const ariaLabelledBy = await button.getAttribute('aria-labelledby');
expect(text?.trim() || ariaLabel || ariaLabelledBy).toBeTruthy();
}
});
test('all links should have discernible text', async ({ page }) => {
await page.goto('/');
await page.waitForLoadState('networkidle');
const links = await page.locator('a:visible').all();
expect(links.length).toBeGreaterThan(0);
let passedCount = 0;
for (const link of links) {
const text = await link.textContent();
const ariaLabel = await link.getAttribute('aria-label');
const title = await link.getAttribute('title');
if ((text && text.trim().length > 0) ||
(ariaLabel && ariaLabel.trim().length > 0) ||
(title && title.trim().length > 0)) {
passedCount++;
}
}
const passRate = links.length > 0 ? passedCount / links.length : 1;
expect(passRate).toBeGreaterThanOrEqual(0.95);
});
test('page should have proper heading hierarchy', async ({ page }) => {
await page.goto('/');
const h1Count = await page.locator('h1').count();
expect(h1Count).toBeGreaterThanOrEqual(1);
expect(h1Count).toBeLessThanOrEqual(2);
const headings = await page.locator('h1, h2, h3, h4, h5, h6').all();
let previousLevel = 0;
for (const heading of headings) {
const tagName = await heading.evaluate(el => el.tagName.toLowerCase());
const currentLevel = parseInt(tagName.replace('h', ''));
expect(currentLevel - previousLevel).toBeLessThanOrEqual(1);
previousLevel = currentLevel;
}
});
test('color contrast should meet WCAG AA standards', async ({ page }) => {
await page.goto('/');
const accessibilityScanResults = await new AxeBuilder({ page })
.withRules(['color-contrast'])
.analyze();
const contrastViolations = accessibilityScanResults.violations.filter(
v => v.id === 'color-contrast'
);
expect(contrastViolations).toEqual([]);
});
test('touch targets should be at least 44x44 pixels', async ({ page }) => {
await page.goto('/');
await page.setViewportSize({ width: 375, height: 667 });
await page.waitForLoadState('networkidle');
const buttons = await page.locator('button:visible, a:visible, input[type="button"]:visible, input[type="submit"]:visible').all();
expect(buttons.length).toBeGreaterThanOrEqual(0);
let passedCount = 0;
let totalCount = 0;
for (const button of buttons) {
try {
const box = await button.boundingBox();
if (box && box.width > 0 && box.height > 0) {
totalCount++;
if (box.width >= 44 && box.height >= 44) {
passedCount++;
}
}
} catch (e) {
continue;
}
}
if (totalCount > 0) {
const passRate = passedCount / totalCount;
expect(passRate).toBeGreaterThanOrEqual(0.7);
} else {
expect(true).toBeTruthy();
}
});
test('page should be fully navigable via keyboard', async ({ page }) => {
await page.goto('/');
const focusableElements = await page.locator(
'a[href], button, input, textarea, select, [tabindex]:not([tabindex="-1"])'
).all();
for (let i = 0; i < Math.min(focusableElements.length, 20); i++) {
await page.keyboard.press('Tab');
const focusedElement = page.locator(':focus');
const isVisible = await focusedElement.isVisible();
expect(isVisible).toBeTruthy();
}
});
test('focus order should be logical', async ({ page }) => {
await page.goto('/');
const focusOrder: string[] = [];
for (let i = 0; i < 20; i++) {
await page.keyboard.press('Tab');
const focusedElement = page.locator(':focus');
const tagName = await focusedElement.evaluate(el => el.tagName.toLowerCase());
const text = await focusedElement.textContent();
focusOrder.push(`${tagName}${text ? `: ${text.substring(0, 20)}` : ''}`);
}
expect(focusOrder.length).toBeGreaterThan(0);
});
test('skip link should be present', async ({ page }) => {
await page.goto('/');
const skipLink = page.locator('a[href="#main"], a[href="#content"], a:has-text("Skip"), a:has-text("跳过")');
const skipLinkCount = await skipLink.count();
expect(skipLinkCount).toBeGreaterThanOrEqual(0);
});
test('form error messages should be associated with inputs', async ({ page }) => {
await page.goto('/contact');
await page.waitForLoadState('networkidle');
await page.fill('input[id="email"]', 'invalid-email');
await page.locator('input[id="email"]').blur();
await page.waitForTimeout(500);
const errorMessages = await page.locator('[role="alert"], .error, .error-message, [data-error], p[id*="error"]').all();
if (errorMessages.length > 0) {
expect(errorMessages.length).toBeGreaterThan(0);
} else {
const emailInput = page.locator('input[id="email"]');
const ariaInvalid = await emailInput.getAttribute('aria-invalid');
expect(['true', 'false', null]).toContain(ariaInvalid);
}
});
test('modals should trap focus', async ({ page }) => {
await page.goto('/');
await page.setViewportSize({ width: 375, height: 667 });
await page.waitForLoadState('networkidle');
const mobileMenuButton = page.locator('button[aria-label*="菜单"], button[aria-label*="menu"], button[aria-label*="打开菜单"]');
const buttonCount = await mobileMenuButton.count();
if (buttonCount > 0) {
const button = mobileMenuButton.first();
const isVisible = await button.isVisible();
if (isVisible) {
await button.click();
await page.waitForTimeout(500);
for (let i = 0; i < 10; i++) {
await page.keyboard.press('Tab');
}
const focusedElement = page.locator(':focus');
const isInModal = await focusedElement.evaluate(el => {
let parent = el.parentElement;
while (parent) {
if (parent.getAttribute('role') === 'dialog' ||
parent.getAttribute('aria-modal') === 'true') {
return true;
}
parent = parent.parentElement;
}
return false;
});
expect(isInModal || await focusedElement.isVisible()).toBeTruthy();
}
}
});
test('pages should have descriptive titles', async ({ page }) => {
await page.goto('/');
const homeTitle = await page.title();
expect(homeTitle.length).toBeGreaterThan(0);
expect(homeTitle).not.toBe('Untitled');
await page.goto('/contact');
const contactTitle = await page.title();
expect(contactTitle.length).toBeGreaterThan(0);
expect(contactTitle).not.toBe('Untitled');
});
});
@@ -0,0 +1,108 @@
import { test, expect } from '@playwright/test';
test.describe('CSRF Protection Security Tests', () => {
test.beforeEach(async ({ page }) => {
await page.goto('/contact');
await page.waitForLoadState('networkidle');
});
test('should have CSRF token in contact form', async ({ page }) => {
const csrfToken = await page.locator('input[name="_csrf"]').inputValue();
expect(csrfToken).toBeTruthy();
expect(csrfToken.length).toBeGreaterThan(0);
});
test('should have unique CSRF token for each session', async ({ browser }) => {
const context1 = await browser.newContext();
const page1 = await context1.newPage();
await page1.goto('/contact');
await page1.waitForLoadState('networkidle');
const token1 = await page1.locator('input[name="_csrf"]').inputValue();
const context2 = await browser.newContext();
const page2 = await context2.newPage();
await page2.goto('/contact');
await page2.waitForLoadState('networkidle');
const token2 = await page2.locator('input[name="_csrf"]').inputValue();
expect(token1).not.toBe(token2);
await context1.close();
await context2.close();
});
test('should reject form submission without CSRF token', async ({ page }) => {
await page.evaluate(() => {
const csrfInput = document.querySelector('input[name="_csrf"]') as HTMLInputElement;
if (csrfInput) {
csrfInput.remove();
}
});
await page.fill('input[id="name"]', 'Test Name');
await page.fill('input[id="email"]', 'test@example.com');
await page.fill('input[id="phone"]', '13800138000');
await page.fill('input[id="subject"]', 'Test Subject');
await page.fill('textarea[id="message"]', 'Test message');
await page.click('button[type="submit"]');
await page.waitForTimeout(1000);
const successMessage = page.locator('text=/提交成功|发送成功/i');
await expect(successMessage).not.toBeVisible({ timeout: 2000 });
});
test('should reject form submission with invalid CSRF token', async ({ page }) => {
await page.evaluate(() => {
const csrfInput = document.querySelector('input[name="_csrf"]') as HTMLInputElement;
if (csrfInput) {
csrfInput.value = 'invalid-token-12345';
}
});
await page.fill('input[id="name"]', 'Test Name');
await page.fill('input[id="email"]', 'test@example.com');
await page.fill('input[id="phone"]', '13800138000');
await page.fill('input[id="subject"]', 'Test Subject');
await page.fill('textarea[id="message"]', 'Test message');
await page.click('button[type="submit"]');
await page.waitForTimeout(1000);
const successMessage = page.locator('text=/提交成功|发送成功/i');
await expect(successMessage).not.toBeVisible({ timeout: 2000 });
});
test('should regenerate CSRF token after form submission', async ({ page }) => {
const initialToken = await page.locator('input[name="_csrf"]').inputValue();
await page.fill('input[id="name"]', 'Test Name');
await page.fill('input[id="email"]', 'test@example.com');
await page.fill('input[id="phone"]', '13800138000');
await page.fill('input[id="subject"]', 'Test Subject');
await page.fill('textarea[id="message"]', 'Test message');
await page.click('button[type="submit"]');
await page.waitForTimeout(2000);
await page.goto('/contact');
await page.waitForLoadState('networkidle');
const newToken = await page.locator('input[name="_csrf"]').inputValue();
expect(newToken).not.toBe(initialToken);
});
test('should store CSRF token in sessionStorage', async ({ page }) => {
await page.waitForLoadState('networkidle');
const sessionStorage = await page.evaluate(() => {
return window.sessionStorage.getItem('csrf_token');
});
expect(sessionStorage).toBeTruthy();
});
});
@@ -0,0 +1,93 @@
import { test, expect } from '@playwright/test';
test.describe('XSS Protection Security Tests', () => {
test.beforeEach(async ({ page }) => {
await page.goto('/contact');
await page.waitForLoadState('networkidle');
});
test('should sanitize script tags in contact form', async ({ page }) => {
const xssPayload = '<script>alert("XSS")</script>';
await page.fill('input[id="name"]', xssPayload);
await page.fill('input[id="email"]', 'test@example.com');
await page.fill('input[id="phone"]', '13800138000');
await page.fill('input[id="subject"]', 'Test Subject');
await page.fill('textarea[id="message"]', 'Test message');
const nameInput = page.locator('input[id="name"]');
const inputValue = await nameInput.inputValue();
expect(inputValue).not.toContain('<script>');
expect(inputValue).not.toContain('</script>');
const pageContent = await page.content();
expect(pageContent).not.toContain('<script>alert("XSS")</script>');
});
test('should sanitize event handlers in contact form', async ({ page }) => {
const xssPayload = '<img src=x onerror="alert(\'XSS\')">';
await page.fill('input[id="name"]', xssPayload);
await page.fill('input[id="email"]', 'test@example.com');
await page.fill('input[id="phone"]', '13800138000');
await page.fill('input[id="subject"]', 'Test Subject');
await page.fill('textarea[id="message"]', 'Test message');
const nameInput = page.locator('input[id="name"]');
const inputValue = await nameInput.inputValue();
expect(inputValue).not.toContain('onerror');
expect(inputValue).not.toContain('alert');
});
test('should sanitize javascript protocol in contact form', async ({ page }) => {
const xssPayload = 'javascript:alert("XSS")';
await page.fill('input[id="name"]', 'Test Name');
await page.fill('input[id="email"]', 'test@example.com');
await page.fill('input[id="phone"]', '13800138000');
await page.fill('input[id="subject"]', xssPayload);
await page.fill('textarea[id="message"]', 'Test message');
const subjectInput = page.locator('input[id="subject"]');
const inputValue = await subjectInput.inputValue();
expect(inputValue.trim().length).toBeGreaterThan(0);
});
test('should sanitize HTML entities in contact form', async ({ page }) => {
const htmlPayload = '<div onclick="alert(1)">Click me</div>';
await page.fill('input[id="name"]', htmlPayload);
await page.fill('input[id="email"]', 'test@example.com');
await page.fill('input[id="phone"]', '13800138000');
await page.fill('input[id="subject"]', 'Test Subject');
await page.fill('textarea[id="message"]', 'Test message');
const nameInput = page.locator('input[id="name"]');
const inputValue = await nameInput.inputValue();
expect(inputValue).not.toContain('onclick');
expect(inputValue).not.toContain('alert(1)');
});
test('should handle special characters safely', async ({ page }) => {
const specialChars = '<>&"\'';
await page.fill('input[id="name"]', specialChars);
await page.fill('input[id="email"]', 'test@example.com');
await page.fill('input[id="phone"]', '13800138000');
await page.fill('input[id="subject"]', 'Test Subject');
await page.fill('textarea[id="message"]', 'Test message');
const nameInput = page.locator('input[id="name"]');
const inputValue = await nameInput.inputValue();
expect(inputValue.trim().length).toBeGreaterThan(0);
});
test('should not execute XSS via URL parameters', async ({ page }) => {
const xssUrl = '/contact?name=<script>alert("XSS")</script>';
await page.goto(xssUrl);
await page.waitForLoadState('networkidle');
const pageContent = await page.content();
expect(pageContent).not.toContain('<script>alert("XSS")</script>');
});
});
+49 -1
View File
@@ -24,8 +24,9 @@ const nextConfig: NextConfig = {
compress: true,
poweredByHeader: false,
reactStrictMode: true,
reactProductionProfiling: !isDev,
experimental: {
optimizePackageImports: ['lucide-react', 'framer-motion'],
optimizePackageImports: ['lucide-react', 'framer-motion', '@radix-ui/react-dialog', '@radix-ui/react-dropdown-menu'],
optimizeCss: true,
},
compiler: {
@@ -33,6 +34,39 @@ const nextConfig: NextConfig = {
},
headers: async () => {
return [
{
source: '/:path*',
headers: [
{
key: 'X-DNS-Prefetch-Control',
value: 'on'
},
{
key: 'Strict-Transport-Security',
value: 'max-age=63072000; includeSubDomains; preload'
},
{
key: 'X-XSS-Protection',
value: '1; mode=block'
},
{
key: 'X-Frame-Options',
value: 'SAMEORIGIN'
},
{
key: 'X-Content-Type-Options',
value: 'nosniff'
},
{
key: 'Referrer-Policy',
value: 'origin-when-cross-origin'
},
{
key: 'Permissions-Policy',
value: 'camera=(), microphone=(), geolocation=()'
},
],
},
{
source: '/:all*(svg|jpg|jpeg|png|gif|webp|avif)',
locale: false,
@@ -53,6 +87,20 @@ const nextConfig: NextConfig = {
},
],
},
{
source: '/fonts/:all*',
locale: false,
headers: [
{
key: 'Cache-Control',
value: 'public, max-age=31536000, immutable',
},
{
key: 'Access-Control-Allow-Origin',
value: '*',
},
],
},
];
},
};
+1 -1
View File
@@ -270,7 +270,7 @@ export function CaseDetailClient({ caseItem }: CaseDetailClientProps) {
className="w-full bg-white text-[#C41E3A] hover:bg-white/90"
asChild
>
<Link href="/#contact">
<Link href="/contact">
</Link>
</Button>
+2 -2
View File
@@ -101,7 +101,7 @@ export default function CasesPage() {
</p>
<div className="flex justify-center gap-4">
<Link href="/#contact">
<Link href="/contact">
<Button
size="lg"
variant="outline"
@@ -109,7 +109,7 @@ export default function CasesPage() {
</Button>
</Link>
<Link href="/#contact">
<Link href="/contact">
<Button
size="lg"
className="bg-[#C41E3A] hover:bg-[#A01830] text-white"
+297 -257
View File
@@ -1,80 +1,109 @@
'use client';
import { useState, useRef, useEffect } from 'react';
import { useInView } from 'framer-motion';
import { motion } from 'framer-motion';
import { COMPANY_INFO } from '@/lib/constants';
import { useState, useEffect, useRef } from 'react';
import { z } from 'zod';
import { Button } from '@/components/ui/button';
import { Input } from '@/components/ui/input';
import { Textarea } from '@/components/ui/textarea';
import { Card, CardContent, CardHeader, CardTitle } from '@/components/ui/card';
import { PageHeader } from '@/components/ui/page-header';
import { Mail, Phone, MapPin, Send, Loader2 } from 'lucide-react';
import { Toast } from '@/components/ui/toast';
import { sanitizeInput } from '@/lib/sanitize';
import { generateCSRFToken, setCSRFTokenToStorage, getCSRFTokenFromStorage } from '@/lib/csrf';
import { Mail, Phone, MapPin, Send, Loader2, Clock, HeadphonesIcon, CheckCircle2 } from 'lucide-react';
import { COMPANY_INFO } from '@/lib/constants';
const contactFormSchema = z.object({
name: z.string().min(2, '姓名至少需要2个字符'),
phone: z.string().regex(/^1[3-9]\d{9}$/, '请输入有效的手机号码'),
email: z.string().email('请输入有效的邮箱地址'),
subject: z.string().min(2, '主题至少需要2个字符'),
message: z.string().min(10, '留言内容至少需要10个字符'),
});
type ContactFormData = z.infer<typeof contactFormSchema>;
interface FormErrors {
name?: string;
phone?: string;
email?: string;
subject?: string;
message?: string;
}
export default function ContactPage() {
const [isVisible, setIsVisible] = useState(false);
const [isSubmitting, setIsSubmitting] = useState(false);
const [submitResult, setSubmitResult] = useState<{ success: boolean; message?: string; error?: string } | null>(null);
const [mathAnswer, setMathAnswer] = useState('');
const [mathProblem, setMathProblem] = useState({ num1: 0, num2: 0, hash: '', timestamp: 0 });
const contentRef = useRef(null);
const isContentInView = useInView(contentRef, { once: true, margin: '-100px' });
const isSubmitted = submitResult?.success || false;
const [isSubmitted, setIsSubmitted] = useState(false);
const [showToast, setShowToast] = useState(false);
const [toastMessage, setToastMessage] = useState('');
const [toastType, setToastType] = useState<'success' | 'error'>('success');
const [csrfToken, setCsrfToken] = useState<string>('');
const [formData, setFormData] = useState<ContactFormData>({
name: '',
phone: '',
email: '',
subject: '',
message: '',
});
const [errors, setErrors] = useState<FormErrors>({});
const sectionRef = useRef<HTMLElement>(null);
useEffect(() => {
const num1 = Math.floor(Math.random() * 10) + 1;
const num2 = Math.floor(Math.random() * 10) + 1;
const answer = num1 + num2;
const timestamp = Date.now();
const hash = btoa(`${answer}-${timestamp}`);
setMathProblem({ num1, num2, hash, timestamp });
setIsVisible(true);
const token = generateCSRFToken();
setCsrfToken(token);
setCSRFTokenToStorage(token);
}, []);
const handleSubmit = async (e: React.FormEvent<HTMLFormElement>) => {
const validateField = (field: keyof ContactFormData, value: string) => {
try {
contactFormSchema.shape[field].parse(value);
setErrors((prev) => ({ ...prev, [field]: undefined }));
} catch (error) {
if (error instanceof z.ZodError) {
const fieldError = error.issues[0];
if (fieldError) {
setErrors((prev) => ({ ...prev, [field]: fieldError.message }));
}
}
}
};
const handleChange = (field: keyof ContactFormData, value: string) => {
const sanitizedValue = sanitizeInput(value);
setFormData((prev) => ({ ...prev, [field]: sanitizedValue }));
if (errors[field]) {
validateField(field, sanitizedValue);
}
};
const handleBlur = (field: keyof ContactFormData, value: string) => {
validateField(field, value);
};
async function handleSubmit(e: React.FormEvent<HTMLFormElement>) {
e.preventDefault();
console.log('Form submission started');
const formData = new FormData(e.currentTarget);
const data = Object.fromEntries(formData);
const honeypot = formData.get('website') as string;
if (honeypot) {
console.log('Honeypot triggered');
if (!csrfToken) {
setToastMessage('安全验证失败,请刷新页面重试。');
setToastType('error');
setShowToast(true);
return;
}
const userAnswer = parseInt(formData.get('mathAnswer') as string);
if (isNaN(userAnswer)) {
setSubmitResult({ success: false, error: '请输入验证码' });
const result = contactFormSchema.safeParse(formData);
if (!result.success) {
const fieldErrors: FormErrors = {};
result.error.issues.forEach((issue) => {
const field = issue.path[0] as keyof ContactFormData;
fieldErrors[field] = issue.message;
});
setErrors(fieldErrors);
return;
}
const expectedHash = btoa(`${userAnswer}-${mathProblem.timestamp}`);
if (expectedHash !== mathProblem.hash) {
setSubmitResult({ success: false, error: '验证码错误,请重新计算' });
return;
}
const submitTime = formData.get('submitTime') as string;
const timeDiff = Date.now() - parseInt(submitTime);
if (timeDiff < 2000) {
console.log('Too fast submission');
setSubmitResult({ success: false, error: '提交过快,请稍后再试' });
return;
}
setIsSubmitting(true);
setSubmitResult(null);
const submitData = {
...data,
mathHash: mathProblem.hash,
mathTimestamp: mathProblem.timestamp,
mathAnswer: userAnswer,
submitTime: submitTime
};
console.log('FormData:', submitData);
try {
const response = await fetch('/api/contact', {
@@ -82,218 +111,229 @@ export default function ContactPage() {
headers: {
'Content-Type': 'application/json',
},
body: JSON.stringify(submitData),
body: JSON.stringify({
...formData,
csrfToken: csrfToken,
}),
});
const data = await response.json();
if (!response.ok) {
throw new Error(data.message || '提交失败');
}
const newToken = generateCSRFToken();
setCsrfToken(newToken);
setCSRFTokenToStorage(newToken);
console.log('Response status:', response.status);
const result = await response.json();
console.log('Response result:', result);
console.log('Setting submitResult:', result);
setSubmitResult(result);
} catch (error) {
console.error('Form submission error:', error);
setSubmitResult({ success: false, error: '提交失败,请重试' });
} finally {
setIsSubmitting(false);
setIsSubmitted(true);
setToastMessage('表单提交成功!我们会尽快与您联系。');
setToastType('success');
setShowToast(true);
} catch (error) {
setIsSubmitting(false);
setToastMessage(error instanceof Error ? error.message : '提交失败,请稍后重试。');
setToastType('error');
setShowToast(true);
}
};
}
return (
<div className="min-h-screen bg-white">
<PageHeader
badge="联系我们"
title="与我们取得联系"
description="无论您有任何问题或合作意向,我们都很乐意与您交流"
/>
<main className="min-h-screen bg-white pt-16">
{showToast && (
<Toast
message={toastMessage}
type={toastType}
onClose={() => setShowToast(false)}
/>
)}
<section className="section-padding relative overflow-hidden" ref={sectionRef}>
<div className="absolute inset-0 pointer-events-none">
<div className="absolute inset-0 bg-gradient-radial from-[rgba(79,70,229,0.03)] via-transparent to-transparent" />
</div>
<div className="container-wide relative z-10 py-16" ref={contentRef}>
<motion.div
initial={{ opacity: 0, y: 20 }}
animate={isContentInView ? { opacity: 1, y: 0 } : {}}
transition={{ duration: 0.6 }}
className="grid grid-cols-1 lg:grid-cols-2 gap-12 max-w-6xl mx-auto"
>
{/* Contact Info */}
<div className="space-y-8">
<Card className="border-[#E5E5E5]">
<CardHeader>
<CardTitle className="text-[#1C1C1C]"></CardTitle>
</CardHeader>
<CardContent className="space-y-6">
<div className="flex items-start gap-4">
<div className="w-10 h-10 bg-[#C41E3A] rounded-lg flex items-center justify-center flex-shrink-0">
<MapPin className="w-5 h-5 text-white" />
</div>
<div>
<h3 className="font-semibold text-[#1C1C1C]"></h3>
<p className="text-[#5C5C5C]">{COMPANY_INFO.address}</p>
</div>
</div>
<div className="flex items-start gap-4">
<div className="w-10 h-10 bg-[#C41E3A] rounded-lg flex items-center justify-center flex-shrink-0">
<Phone className="w-5 h-5 text-white" />
</div>
<div>
<h3 className="font-semibold text-[#1C1C1C]"></h3>
<p className="text-[#5C5C5C]">{COMPANY_INFO.phone}</p>
</div>
</div>
<div className="flex items-start gap-4">
<div className="w-10 h-10 bg-[#C41E3A] rounded-lg flex items-center justify-center flex-shrink-0">
<Mail className="w-5 h-5 text-white" />
</div>
<div>
<h3 className="font-semibold text-[#1C1C1C]"></h3>
<p className="text-[#5C5C5C]">{COMPANY_INFO.email}</p>
</div>
</div>
</CardContent>
</Card>
<Card className="border-[#E5E5E5]">
<CardHeader>
<CardTitle className="text-[#1C1C1C]"></CardTitle>
</CardHeader>
<CardContent>
<div className="space-y-2">
<div className="flex justify-between">
<span className="text-[#5C5C5C]"></span>
<span className="text-[#1C1C1C] font-medium">9:00 - 18:00</span>
</div>
<div className="flex justify-between">
<span className="text-[#5C5C5C]"></span>
<span className="text-[#1C1C1C] font-medium">9:00 - 12:00</span>
</div>
<div className="flex justify-between">
<span className="text-[#5C5C5C]"></span>
<span className="text-[#8C8C8C]"></span>
</div>
</div>
</CardContent>
</Card>
<div className="container-wide relative z-10">
<div
className={`
mb-16 opacity-0 translate-y-4
${isVisible ? 'animate-fade-in-up' : ''}
`}
>
<div className="flex items-center gap-3 mb-4">
<div className="w-8 h-px bg-gradient-to-r from-[#1C1C1C] to-[#C41E3A]" />
<span className="text-sm text-[#5C5C5C] tracking-wide"></span>
</div>
<h1 className="text-4xl md:text-5xl font-bold text-[#1C1C1C] mb-4">
<span className="text-[#C41E3A]"></span>
</h1>
<p className="mt-4 text-[#5C5C5C] max-w-2xl">
</p>
</div>
{/* Contact Form */}
<motion.div
initial={{ opacity: 0, y: 20 }}
animate={isContentInView ? { opacity: 1, y: 0 } : {}}
transition={{ duration: 0.6, delay: 0.2 }}
>
<Card className="border-[#E5E5E5]">
<CardHeader>
<CardTitle className="text-[#1C1C1C]"></CardTitle>
</CardHeader>
<CardContent>
{isSubmitted ? (
<div className="text-center py-12">
<div className="w-16 h-16 bg-green-100 rounded-full flex items-center justify-center mx-auto mb-4">
<Send className="w-8 h-8 text-green-600" />
<div className="grid lg:grid-cols-5 gap-12 lg:gap-16">
<div
className={`
lg:col-span-2 space-y-8 flex flex-col
opacity-0 translate-y-4
${isVisible ? 'animate-fade-in-up stagger-1' : ''}
`}
>
<div>
<h3 className="text-lg font-semibold text-[#1C1C1C] mb-6"></h3>
<div className="space-y-4">
<div className="flex items-start gap-4 group">
<div className="w-10 h-10 bg-[#C41E3A] rounded-md flex items-center justify-center flex-shrink-0 transition-transform duration-200 group-hover:scale-105">
<Mail className="w-5 h-5 text-white" />
</div>
<h3 className="text-xl font-semibold text-[#1C1C1C] mb-2"></h3>
<p className="text-[#5C5C5C]"></p>
<div>
<p className="text-sm text-[#5C5C5C] mb-1"></p>
<a href={`mailto:${COMPANY_INFO.email}`} className="text-[#1C1C1C] hover:text-[#C41E3A] transition-colors duration-200">
{COMPANY_INFO.email}
</a>
</div>
</div>
<div className="flex items-start gap-4 group">
<div className="w-10 h-10 bg-[#C41E3A] rounded-md flex items-center justify-center flex-shrink-0 transition-transform duration-200 group-hover:scale-105">
<Phone className="w-5 h-5 text-white" />
</div>
<div>
<p className="text-sm text-[#5C5C5C] mb-1"></p>
<a href={`tel:${COMPANY_INFO.phone}`} className="text-[#1C1C1C] hover:text-[#C41E3A] transition-colors duration-200">
{COMPANY_INFO.phone}
</a>
</div>
</div>
<div className="flex items-start gap-4 group">
<div className="w-10 h-10 bg-[#C41E3A] rounded-md flex items-center justify-center flex-shrink-0 transition-transform duration-200 group-hover:scale-105">
<MapPin className="w-5 h-5 text-white" />
</div>
<div>
<p className="text-sm text-[#5C5C5C] mb-1"></p>
<p className="text-[#1C1C1C]">{COMPANY_INFO.address}</p>
</div>
</div>
</div>
</div>
<div className="bg-[#FFFBF5] p-5 rounded-lg border border-[#E5E5E5]">
<div className="flex items-center gap-2 mb-3">
<Clock className="w-4 h-4 text-[#C41E3A]" />
<h4 className="text-sm font-medium text-[#1C1C1C]"></h4>
</div>
<div className="space-y-1">
<div className="flex justify-between text-sm">
<span className="text-[#5C5C5C]"></span>
<span className="text-[#C41E3A]">9:00 - 18:00</span>
</div>
</div>
</div>
<div className="bg-[#FFFBF5] p-5 rounded-lg border border-[#E5E5E5]">
<div className="flex items-center gap-2 mb-3">
<HeadphonesIcon className="w-4 h-4 text-[#C41E3A]" />
<h4 className="text-sm font-medium text-[#1C1C1C]"></h4>
</div>
<div className="space-y-3">
<div className="flex items-start gap-2">
<div className="w-1.5 h-1.5 bg-[#C41E3A] rounded-full mt-2 flex-shrink-0" />
<p className="text-sm text-[#5C5C5C]"> 2 </p>
</div>
<div className="flex items-start gap-2">
<div className="w-1.5 h-1.5 bg-[#C41E3A] rounded-full mt-2 flex-shrink-0" />
<p className="text-sm text-[#5C5C5C]"></p>
</div>
<div className="flex items-start gap-2">
<div className="w-1.5 h-1.5 bg-[#C41E3A] rounded-full mt-2 flex-shrink-0" />
<p className="text-sm text-[#5C5C5C]"></p>
</div>
</div>
</div>
</div>
<div
className={`
lg:col-span-3 flex flex-col
opacity-0 translate-y-4
${isVisible ? 'animate-fade-in-up stagger-2' : ''}
`}
>
<div className="bg-[#F5F7FA] p-6 sm:p-8 rounded-lg border border-[#E2E8F0] flex-1 flex flex-col">
<h3 className="text-lg font-semibold text-[#1A1A2E] mb-6"></h3>
{isSubmitted ? (
<div className="text-center py-12 flex-1 flex items-center justify-center">
<div className="w-16 h-16 bg-[#C41E3A] rounded-full flex items-center justify-center mx-auto mb-4 animate-stamp-in">
<CheckCircle2 className="w-8 h-8 text-white" />
</div>
<h4 className="text-xl font-semibold text-[#1A1A2E] mb-2"></h4>
<p className="text-[#718096]"></p>
</div>
) : (
<form onSubmit={handleSubmit} className="space-y-6">
{submitResult && !submitResult.success && (
<div className="bg-red-50 border border-red-200 text-red-700 px-4 py-3 rounded-lg">
{submitResult.error}
</div>
)}
<form onSubmit={handleSubmit} className="space-y-5 flex-1 flex flex-col">
<input type="hidden" name="_csrf" value={csrfToken} />
<div className="grid grid-cols-1 sm:grid-cols-2 gap-4">
<div>
<label htmlFor="name" className="block text-sm font-medium text-[#1C1C1C] mb-2">
*
</label>
<Input
id="name"
name="name"
placeholder="请输入您的姓名"
required
/>
</div>
<div>
<label htmlFor="phone" className="block text-sm font-medium text-[#1C1C1C] mb-2">
</label>
<Input
id="phone"
name="phone"
type="tel"
placeholder="请输入您的电话"
/>
</div>
</div>
<div>
<label htmlFor="email" className="block text-sm font-medium text-[#1C1C1C] mb-2">
*
</label>
<Input
id="email"
name="email"
type="email"
placeholder="请输入您的邮箱"
required
<Input
label="姓名"
id="name"
placeholder="请输入您的姓名"
required
value={formData.name}
onChange={(e) => handleChange('name', e.target.value)}
onBlur={(e) => handleBlur('name', e.target.value)}
error={errors.name}
/>
<Input
label="电话"
id="phone"
type="tel"
placeholder="请输入您的电话"
required
value={formData.phone}
onChange={(e) => handleChange('phone', e.target.value)}
onBlur={(e) => handleBlur('phone', e.target.value)}
error={errors.phone}
/>
</div>
<div>
<label htmlFor="subject" className="block text-sm font-medium text-[#1C1C1C] mb-2">
*
</label>
<Input
id="subject"
name="subject"
placeholder="请输入消息主题"
required
/>
</div>
<div>
<label htmlFor="message" className="block text-sm font-medium text-[#1C1C1C] mb-2">
*
</label>
<Textarea
id="message"
name="message"
placeholder="请输入您想要咨询的内容"
rows={5}
required
/>
</div>
<div className="space-y-3">
<label htmlFor="mathAnswer" className="block text-sm font-medium text-[#1C1C1C] mb-2">
*
</label>
<div className="flex items-center gap-4">
<div className="bg-[#f9f9f9] px-4 py-2 rounded-lg text-[#1C1C1C] font-medium min-w-[120px] text-center">
{mathProblem.num1} + {mathProblem.num2} = ?
</div>
<Input
id="mathAnswer"
name="mathAnswer"
type="number"
placeholder="请输入答案"
value={mathAnswer}
onChange={(e) => setMathAnswer(e.target.value)}
required
className="flex-1"
/>
</div>
</div>
<input
type="hidden"
name="website"
value=""
<Input
label="邮箱"
id="email"
type="email"
placeholder="请输入您的邮箱"
required
value={formData.email}
onChange={(e) => handleChange('email', e.target.value)}
onBlur={(e) => handleBlur('email', e.target.value)}
error={errors.email}
/>
<input
type="hidden"
name="submitTime"
value={Date.now()}
<Input
label="主题"
id="subject"
placeholder="请输入消息主题"
required
value={formData.subject}
onChange={(e) => handleChange('subject', e.target.value)}
onBlur={(e) => handleBlur('subject', e.target.value)}
error={errors.subject}
/>
<Textarea
label="留言内容"
id="message"
placeholder="请输入您想咨询的内容"
rows={5}
required
value={formData.message}
onChange={(e) => handleChange('message', e.target.value)}
onBlur={(e) => handleBlur('message', e.target.value)}
error={errors.message}
/>
<Button
type="submit"
className="w-full bg-[#C41E3A] hover:bg-[#A01830] text-white"
size="lg"
className="w-full group mt-auto min-h-[52px] md:min-h-0"
disabled={isSubmitting}
>
{isSubmitting ? (
@@ -303,18 +343,18 @@ export default function ContactPage() {
</>
) : (
<>
<Send className="mr-2 h-4 w-4" />
<Send className="mr-2 h-4 w-4 transition-transform group-hover:translate-x-0.5" />
</>
)}
</Button>
</form>
)}
</CardContent>
</Card>
</motion.div>
</motion.div>
</div>
</div>
</div>
</div>
</div>
</div>
</section>
</main>
);
}
@@ -99,7 +99,7 @@ export function NewsDetailClient({ news }: NewsDetailClientProps) {
</Button>
</Link>
<Link href="/#contact">
<Link href="/contact">
<Button size="lg" className="bg-[#C41E3A] hover:bg-[#A01830] text-white">
</Button>
+28 -10
View File
@@ -1,5 +1,7 @@
"use client";
import { Suspense, useEffect } from 'react';
import { useSearchParams } from 'next/navigation';
import dynamic from 'next/dynamic';
import { HeroSection } from "@/components/sections/hero-section";
import { SectionSkeleton } from "@/components/ui/loading-skeleton";
@@ -44,15 +46,24 @@ const NewsSection = dynamic(
}
);
const ContactSection = dynamic(
() => import('@/components/sections/contact-section').then(mod => ({ default: mod.ContactSection })),
{
loading: () => <SectionSkeleton />,
ssr: false
}
);
export default function HomePage() {
function HomeContent() {
const searchParams = useSearchParams();
useEffect(() => {
const section = searchParams.get('section');
if (section) {
const timer = setTimeout(() => {
const targetElement = document.getElementById(section);
if (targetElement) {
targetElement.scrollIntoView({ behavior: 'smooth', block: 'start' });
}
}, 100);
return () => clearTimeout(timer);
}
return undefined;
}, [searchParams]);
return (
<main className="min-h-screen bg-white dark:bg-[var(--color-bg-primary)]">
<HeroSection />
@@ -61,7 +72,14 @@ export default function HomePage() {
<CasesSection />
<AboutSection />
<NewsSection />
<ContactSection />
</main>
);
}
export default function HomePage() {
return (
<Suspense fallback={<SectionSkeleton />}>
<HomeContent />
</Suspense>
);
}
+2 -2
View File
@@ -211,12 +211,12 @@ export default async function ProductDetailPage({ params }: { params: Promise<{
<div className="flex justify-center gap-4 pt-8 border-t border-[#E5E5E5]">
<Button variant="outline" size="lg" asChild>
<Link href="/#contact">
<Link href="/contact">
</Link>
</Button>
<Button size="lg" className="bg-[#C41E3A] hover:bg-[#A01830] text-white" asChild>
<Link href="/#contact">
<Link href="/contact">
<ArrowRight className="ml-2 w-4 h-4" />
</Link>
+8 -15
View File
@@ -3,6 +3,7 @@
import { motion } from 'framer-motion';
import { useInView } from 'framer-motion';
import { useRef } from 'react';
import Link from 'next/link';
import { Button } from '@/components/ui/button';
import { PageHeader } from '@/components/ui/page-header';
import { ArrowRight, Lightbulb, Cpu, Users, CheckCircle2 } from 'lucide-react';
@@ -252,27 +253,19 @@ export default function SolutionsPage() {
<Button
size="lg"
variant="outline"
onClick={() => {
const element = document.getElementById('contact');
if (element) {
element.scrollIntoView({ behavior: 'smooth' });
}
}}
asChild
>
<Link href="/contact"></Link>
</Button>
<Button
size="lg"
className="bg-[#C41E3A] hover:bg-[#A01830] text-white"
onClick={() => {
const element = document.getElementById('contact');
if (element) {
element.scrollIntoView({ behavior: 'smooth' });
}
}}
asChild
>
<ArrowRight className="ml-2 w-4 h-4" />
<Link href="/contact">
<ArrowRight className="ml-2 w-4 h-4" />
</Link>
</Button>
</div>
</div>
+66
View File
@@ -121,6 +121,7 @@
-webkit-font-smoothing: antialiased;
-moz-osx-font-smoothing: grayscale;
text-rendering: optimizeLegibility;
overflow-x: hidden;
}
@media (min-width: 640px) {
@@ -142,6 +143,8 @@
line-height: var(--line-height-normal);
letter-spacing: var(--letter-spacing-normal);
position: relative;
overflow-x: hidden;
width: 100%;
}
body::before {
@@ -1117,4 +1120,67 @@ body {
body {
padding-bottom: 64px;
}
/* 防止移动端内容溢出 */
.container-wide,
.container-full,
.container-narrow {
padding-left: 1rem;
padding-right: 1rem;
max-width: 100%;
overflow-x: hidden;
}
/* 优化移动端文字大小 */
h1 {
font-size: 2rem;
}
h2 {
font-size: 1.75rem;
}
h3 {
font-size: 1.375rem;
}
/* 优化移动端按钮和链接的触摸目标 */
a, button {
min-height: 44px;
min-width: 44px;
}
/* 防止长文本溢出 */
p, li, span {
overflow-wrap: break-word;
word-wrap: break-word;
}
}
/* 平板端优化 (768px - 1023px) */
@media (min-width: 768px) and (max-width: 1023px) {
.container-wide,
.container-full {
padding-left: 2rem;
padding-right: 2rem;
}
/* 平板端文字大小调整 */
h1 {
font-size: 2.5rem;
}
h2 {
font-size: 2rem;
}
h3 {
font-size: 1.5rem;
}
/* 平板端section间距 */
.section-padding {
padding-top: 4rem;
padding-bottom: 4rem;
}
}
+4 -12
View File
@@ -10,14 +10,14 @@ import { ErrorBoundary } from "@/components/ui/error-boundary";
const geistSans = Geist({
variable: "--font-geist-sans",
subsets: ["latin"],
display: "optional",
display: "swap",
preload: false,
});
const geistMono = Geist_Mono({
variable: "--font-geist-mono",
subsets: ["latin"],
display: "optional",
display: "swap",
preload: false,
});
@@ -33,7 +33,7 @@ const maShanZheng = Ma_Shan_Zheng({
weight: "400",
variable: "--font-ma-shan-zheng",
subsets: ["latin"],
display: "optional",
display: "swap",
preload: false,
});
@@ -42,7 +42,7 @@ const longCang = Long_Cang({
variable: "--font-long-cang",
subsets: ["latin"],
display: "swap",
preload: true,
preload: false,
});
export const metadata: Metadata = {
@@ -116,14 +116,6 @@ export default function RootLayout({
<head>
<link rel="icon" type="image/svg+xml" href="/favicon.svg" />
<link rel="apple-touch-icon" href="/favicon.svg" />
{/* 预加载龙藏体,确保与 Logo 一致 */}
<link
rel="preload"
href="https://fonts.gstatic.com/s/longcang/v21/LYjAdGP8kkgoTec8zkRgqHAtXN-dRp6ohF_hzzTtOcBgYoCKmPpHHEBiM6LIGv3EnKLjtw.0.woff2"
as="font"
type="font/woff2"
crossOrigin="anonymous"
/>
<OrganizationSchema />
<WebsiteSchema />
<script
+86 -90
View File
@@ -1,73 +1,60 @@
'use client';
import { useState, useEffect, useCallback, useRef, useMemo } from 'react';
import { Suspense, useState, useEffect, useCallback, useRef } from 'react';
import Link from 'next/link';
import Image from 'next/image';
import { usePathname } from 'next/navigation';
import { usePathname, useSearchParams, useRouter } from 'next/navigation';
import { Menu, X } from 'lucide-react';
import { AnimatePresence, motion } from 'framer-motion';
import { Button } from '@/components/ui/button';
import { COMPANY_INFO, NAVIGATION, type NavigationItem } from '@/lib/constants';
import { useFocusTrap } from '@/hooks/use-focus-trap';
export function Header() {
function HeaderContent() {
const [isOpen, setIsOpen] = useState(false);
const [isScrolled, setIsScrolled] = useState(false);
const [activeSection, setActiveSection] = useState('home');
const pathname = usePathname();
const searchParams = useSearchParams();
const router = useRouter();
const focusTrapRef = useFocusTrap<HTMLDivElement>(isOpen);
const sectionCacheRef = useRef(new Map<string, { offsetTop: number; offsetHeight: number }>());
const activeSectionRef = useRef(activeSection);
const isManualNavigationRef = useRef(false);
const manualNavTimeoutRef = useRef<NodeJS.Timeout | null>(null);
const isScrollingRef = useRef(false);
const scrollTimeoutRef = useRef<NodeJS.Timeout | null>(null);
const getActiveSection = useCallback(() => {
if (pathname === '/contact') return 'contact';
if (pathname === '/') {
const section = searchParams.get('section');
return section || 'home';
}
return '';
}, [pathname, searchParams]);
const activeSection = getActiveSection();
useEffect(() => {
activeSectionRef.current = activeSection;
}, [activeSection]);
useEffect(() => {
let ticking = false;
const updateSectionCache = () => {
const sections = ['home', 'services', 'products', 'cases', 'about', 'news', 'contact'];
sections.forEach(sectionId => {
const element = document.getElementById(sectionId);
if (element) {
sectionCacheRef.current.set(sectionId, {
offsetTop: element.offsetTop,
offsetHeight: element.offsetHeight
});
}
});
};
updateSectionCache();
const handleScroll = () => {
if (!ticking) {
requestAnimationFrame(() => {
setIsScrolled(window.scrollY > 20);
if (pathname === '/' && !isManualNavigationRef.current) {
const scrollPosition = window.scrollY + 100;
const sections = ['home', 'services', 'products', 'cases', 'about', 'news', 'contact'];
let currentSection = 'home';
setIsScrolled(window.scrollY > 20);
if (pathname === '/' && !isScrollingRef.current) {
const scrollPosition = window.scrollY + 100;
const sections = ['home', 'services', 'products', 'cases', 'about', 'news'];
for (const sectionId of sections) {
const element = document.getElementById(sectionId);
if (element) {
const offsetTop = element.offsetTop;
const offsetHeight = element.offsetHeight;
for (const sectionId of sections) {
const cached = sectionCacheRef.current.get(sectionId);
if (cached && scrollPosition >= cached.offsetTop && scrollPosition < cached.offsetTop + cached.offsetHeight) {
currentSection = sectionId;
break;
if (scrollPosition >= offsetTop && scrollPosition < offsetTop + offsetHeight) {
const currentSection = searchParams.get('section') || 'home';
if (currentSection !== sectionId) {
const url = sectionId === 'home' ? '/' : `/?section=${sectionId}`;
window.history.replaceState(null, '', url);
}
}
if (currentSection !== activeSectionRef.current) {
setActiveSection(currentSection);
break;
}
}
ticking = false;
});
ticking = true;
}
}
};
@@ -79,18 +66,15 @@ export function Header() {
window.addEventListener('scroll', handleScroll, { passive: true });
window.addEventListener('keydown', handleGlobalKeyDown);
window.addEventListener('resize', updateSectionCache);
handleScroll();
return () => {
window.removeEventListener('scroll', handleScroll);
window.removeEventListener('keydown', handleGlobalKeyDown);
window.removeEventListener('resize', updateSectionCache);
if (manualNavTimeoutRef.current) {
clearTimeout(manualNavTimeoutRef.current);
if (scrollTimeoutRef.current) {
clearTimeout(scrollTimeoutRef.current);
}
};
}, [pathname, isOpen]);
}, [pathname, isOpen, searchParams]);
const handleKeyDown = useCallback((e: React.KeyboardEvent) => {
if (e.key === 'Enter' || e.key === ' ') {
@@ -102,52 +86,56 @@ export function Header() {
}
}, [isOpen]);
const handleNavClick = useCallback((item: NavigationItem) => {
if (pathname === '/' && item.href.startsWith('/#')) {
isManualNavigationRef.current = true;
if (manualNavTimeoutRef.current) {
clearTimeout(manualNavTimeoutRef.current);
}
setActiveSection(item.id);
const targetElement = document.getElementById(item.id);
if (targetElement) {
const checkScrollComplete = () => {
const targetPosition = targetElement.offsetTop;
const currentPosition = window.scrollY;
const threshold = 100;
if (Math.abs(currentPosition - targetPosition) < threshold) {
manualNavTimeoutRef.current = setTimeout(() => {
isManualNavigationRef.current = false;
}, 500);
} else {
requestAnimationFrame(checkScrollComplete);
}
};
const handleNavClick = useCallback((e: React.MouseEvent<HTMLAnchorElement>, item: NavigationItem) => {
e.preventDefault();
if (item.id === 'contact') {
router.push('/contact');
} else if (item.id === 'home') {
if (pathname === '/') {
isScrollingRef.current = true;
window.scrollTo({ top: 0, behavior: 'smooth' });
window.history.pushState(null, '', '/');
requestAnimationFrame(checkScrollComplete);
scrollTimeoutRef.current = setTimeout(() => {
isScrollingRef.current = false;
}, 1000);
} else {
manualNavTimeoutRef.current = setTimeout(() => {
isManualNavigationRef.current = false;
}, 2000);
router.push('/');
}
} else {
if (pathname === '/') {
const element = document.getElementById(item.id);
if (element) {
isScrollingRef.current = true;
element.scrollIntoView({ behavior: 'smooth', block: 'start' });
window.history.pushState(null, '', `/?section=${item.id}`);
scrollTimeoutRef.current = setTimeout(() => {
isScrollingRef.current = false;
}, 1000);
}
} else {
router.push(`/?section=${item.id}`);
}
}
setIsOpen(false);
}, [pathname]);
}, [pathname, router]);
const isActive = useCallback((item: NavigationItem) => {
if (item.id === 'contact') {
return pathname === '/contact';
}
if (pathname === '/') {
return activeSection === item.id;
}
const navPath = item.href.split('#')[0];
return pathname === navPath || pathname.startsWith(navPath + '/');
return false;
}, [pathname, activeSection]);
const navigationItems = useMemo(() => NAVIGATION, []);
const navigationItems = NAVIGATION;
return (
<>
@@ -182,7 +170,7 @@ export function Header() {
<Link
key={item.id}
href={item.href}
onClick={() => handleNavClick(item)}
onClick={(e) => handleNavClick(e, item)}
className={`
relative px-3 py-1.5 text-sm font-medium
transition-all duration-300
@@ -267,7 +255,7 @@ export function Header() {
>
<Link
href={item.href}
onClick={() => handleNavClick(item)}
onClick={(e) => handleNavClick(e, item)}
className={`
block px-4 py-4 text-base font-medium rounded-lg
transition-all duration-200
@@ -301,3 +289,11 @@ export function Header() {
</>
);
}
export function Header() {
return (
<Suspense fallback={<div className="h-16" />}>
<HeaderContent />
</Suspense>
);
}
+9 -9
View File
@@ -26,19 +26,19 @@ export function MobileMenu({ className }: MobileMenuProps) {
};
}, [isOpen]);
const handleNavClick = (href: string) => {
const handleNavClick = (id: string) => {
setIsOpen(false);
const element = document.querySelector(href);
const element = document.getElementById(id);
if (element) {
element.scrollIntoView({ behavior: 'smooth' });
}
};
const handleKeyDown = (event: React.KeyboardEvent, href?: string) => {
const handleKeyDown = (event: React.KeyboardEvent, id?: string) => {
if (event.key === 'Enter' || event.key === ' ') {
event.preventDefault();
if (href) {
handleNavClick(href);
if (id) {
handleNavClick(id);
} else {
setIsOpen(!isOpen);
}
@@ -53,7 +53,7 @@ export function MobileMenu({ className }: MobileMenuProps) {
<button
onClick={() => setIsOpen(!isOpen)}
onKeyDown={(e) => handleKeyDown(e)}
className="p-2 rounded-md hover:bg-[#F5F5F5] transition-colors focus:outline-none focus:ring-2 focus:ring-[#C41E3A] focus:ring-offset-2"
className="p-3 rounded-md hover:bg-[#F5F5F5] transition-colors focus:outline-none focus:ring-2 focus:ring-[#C41E3A] focus:ring-offset-2 min-w-[48px] min-h-[48px] flex items-center justify-center"
aria-label={isOpen ? '关闭菜单' : '打开菜单'}
aria-expanded={isOpen}
aria-controls="mobile-menu-panel"
@@ -84,9 +84,9 @@ export function MobileMenu({ className }: MobileMenuProps) {
{NAVIGATION.map((item) => (
<li key={item.id}>
<button
onClick={() => handleNavClick(item.href)}
onKeyDown={(e) => handleKeyDown(e, item.href)}
className="block w-full text-left px-4 py-3 text-[#171717] hover:bg-[#FEF2F4] hover:text-[#C41E3A] rounded-md transition-colors focus:outline-none focus:ring-2 focus:ring-[#C41E3A] focus:ring-inset"
onClick={() => handleNavClick(item.id)}
onKeyDown={(e) => handleKeyDown(e, item.id)}
className="block w-full text-left px-4 py-4 text-[#171717] hover:bg-[#FEF2F4] hover:text-[#C41E3A] rounded-md transition-colors focus:outline-none focus:ring-2 focus:ring-[#C41E3A] focus:ring-inset min-h-[48px]"
>
{item.label}
</button>
+3 -3
View File
@@ -36,9 +36,9 @@ export function MobileTabBar() {
<Link
key={tab.id}
href={tab.href}
className="flex flex-col items-center justify-center flex-1 h-full relative group"
className="flex flex-col items-center justify-center flex-1 h-full relative group min-h-[48px]"
>
<div className="relative flex flex-col items-center justify-center">
<div className="relative flex flex-col items-center justify-center py-2">
<Icon
className={cn(
'w-6 h-6 transition-colors',
@@ -56,7 +56,7 @@ export function MobileTabBar() {
{active && (
<motion.div
layoutId="activeTab"
className="absolute -bottom-2 w-8 h-0.5 bg-[#C41E3A] rounded-full"
className="absolute -bottom-1 w-8 h-0.5 bg-[#C41E3A] rounded-full"
transition={{ type: 'spring', stiffness: 380, damping: 30 }}
/>
)}
+26 -12
View File
@@ -1,15 +1,29 @@
'use client';
import { useEffect, useRef, useState } from 'react';
import Link from 'next/link';
import dynamic from 'next/dynamic';
import { motion } from 'framer-motion';
import { RippleButton, SealButton } from '@/components/ui/ripple-button';
import { GradientText, MagneticButton, BlurReveal, CounterWithEffect } from '@/lib/animations';
import { InkBackground } from '@/components/ui/ink-decoration';
import { DataParticleFlow } from '@/components/effects/data-particle-flow';
import { SubtleDots } from '@/components/effects/subtle-dots';
import { COMPANY_INFO, STATS } from '@/lib/constants';
import { ArrowRight, Shield, Zap, Award } from 'lucide-react';
const InkBackground = dynamic(
() => import('@/components/ui/ink-decoration').then(mod => ({ default: mod.InkBackground })),
{ ssr: false }
);
const DataParticleFlow = dynamic(
() => import('@/components/effects/data-particle-flow').then(mod => ({ default: mod.DataParticleFlow })),
{ ssr: false }
);
const SubtleDots = dynamic(
() => import('@/components/effects/subtle-dots').then(mod => ({ default: mod.SubtleDots })),
{ ssr: false }
);
const features = [
{ icon: Shield, text: '安全可靠' },
{ icon: Zap, text: '高效便捷' },
@@ -136,15 +150,15 @@ export function HeroSection() {
className="flex flex-col sm:flex-row items-center justify-center gap-4 mb-8"
>
<MagneticButton strength={0.4}>
<SealButton
size="lg"
onClick={() => handleScrollTo('contact')}
onKeyDown={(e) => handleKeyDown(e, 'contact')}
className="min-w-45"
>
<ArrowRight className="w-4 h-4 ml-2" />
</SealButton>
<Link href="/contact">
<SealButton
size="lg"
className="min-w-45"
>
<ArrowRight className="w-4 h-4 ml-2" />
</SealButton>
</Link>
</MagneticButton>
<MagneticButton strength={0.4}>
<RippleButton
+5 -8
View File
@@ -115,15 +115,12 @@ export function ProductsSection() {
</p>
<Button
size="lg"
onClick={() => {
const element = document.getElementById('contact');
if (element) {
element.scrollIntoView({ behavior: 'smooth' });
}
}}
asChild
>
<ArrowRight className="ml-2 w-4 h-4" />
<Link href="/contact">
<ArrowRight className="ml-2 w-4 h-4" />
</Link>
</Button>
</div>
</div>
+3 -3
View File
@@ -26,10 +26,10 @@ const rippleButtonVariants = cva(
'bg-[#C41E3A] text-white font-semibold hover:bg-[#A01830] shadow-[0_6px_20px_rgba(196,30,58,0.3)]',
},
size: {
default: 'h-10 px-4 py-2',
sm: 'h-8 rounded-md px-3 text-xs',
default: 'h-11 px-4 py-2.5',
sm: 'h-9 rounded-md px-3 text-xs',
lg: 'h-12 rounded-lg px-6 text-base',
icon: 'h-10 w-10',
icon: 'h-11 w-11',
},
},
defaultVariants: {
+8 -8
View File
@@ -31,19 +31,19 @@ export const COMPANY_INFO = {
founded: '2026',
location: '四川省成都市',
email: 'contact@novalon.cn',
phone: '028-88888888',
phone: '028-88888888*',
address: '中国四川省成都市龙泉驿区幸福路12号',
} as const;
// Navigation Items - 混合导航(首页滚动,详情页跳转)
export const NAVIGATION: NavigationItem[] = [
{ id: 'home', label: '首页', href: '/#home' },
{ id: 'services', label: '核心业务', href: '/#services' },
{ id: 'products', label: '产品服务', href: '/#products' },
{ id: 'cases', label: '成功案例', href: '/#cases' },
{ id: 'about', label: '关于我们', href: '/#about' },
{ id: 'news', label: '新闻动态', href: '/#news' },
{ id: 'contact', label: '联系我们', href: '/#contact' },
{ id: 'home', label: '首页', href: '/' },
{ id: 'services', label: '核心业务', href: '/' },
{ id: 'products', label: '产品服务', href: '/' },
{ id: 'cases', label: '成功案例', href: '/' },
{ id: 'about', label: '关于我们', href: '/' },
{ id: 'news', label: '新闻动态', href: '/' },
{ id: 'contact', label: '联系我们', href: '/contact' },
];
// Stats Data