Files
novalon-website/src/app/(marketing)/contact/contact-content-v3.tsx
T
zhangxiang 702c732d27 fix(contact): 去掉 useSearchParams 让 /contact 可完整预渲染;补发布后 ISR 预热脚本
冷首访白屏的第二个真因:/contact 用 useSearchParams() 读 ?success,客户端组件里
这会让整页在预渲染时退化成 Suspense fallback(首访只看到「加载中…」,限速下 ~6s 才出内容)。
该参数只用于一次性成功提示 ⇒ 改为挂载后从 window.location 读并 replaceState 清理。

- /contact 冷首访 h1 可见:6.0s → 1.5s;HTML 73KB 含正文(此前只有外壳)。
- 新增 scripts/ops/warm-routes.mjs:按 sitemap 预热并断言全 200、第二遍 <1500ms 或 HIT;
  本轮线上第二遍:非 200 = 0、>1500ms = 0。
- 全站冷首访复测:/ 827ms、/about 1652ms、/contact 1511ms、/products 917ms、
  /services/software 922ms、/insights 1532ms。
- runbook:加发布前磁盘检查(≥2G)与「构建失败必须中止」;加 §4.0 预热步骤。
- 事故记录:第三次重建时服务器磁盘 99%,COPY 报 ENOSPC 而 up -d 仍执行(旧镜像被当已发布);
  清理旧备份 1.8G + docker image prune 1.075G 后回到 81%,重建 015b6d75 成功。
2026-10-20 08:23:34 +08:00

623 lines
26 KiB
TypeScript
Raw Blame History

This file contains ambiguous Unicode characters
This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.
'use client';
import { useState, useEffect, Suspense } from 'react';
import { z } from 'zod';
import { motion } from 'framer-motion';
import { Button } from '@/components/ui/button';
import { LabeledInput as Input } from '@/components/ui/labeled-input';
import { LabeledTextarea as Textarea } from '@/components/ui/labeled-textarea';
import { Toast } from '@/components/ui/toast';
import { CTAButton } from '@/components/ui/cta-button';
import { canonicalCtaLabel } from '@/lib/constants/cta-labels';
import { StaticLink } from '@/components/ui/static-link';
import { ContentUnavailableState } from '@/components/ui/content-unavailable';
import {
Mail,
MapPin,
Send,
Loader2,
Clock,
HeadphonesIcon,
CheckCircle2,
HelpCircle,
} from 'lucide-react';
import { trackContactForm } from '@/lib/analytics';
import { BreadcrumbSchema } from '@/components/seo/structured-data';
import { LegacyTooltip as Tooltip } from '@/components/ui/tooltip';
const EASE_OUT = [0.22, 1, 0.36, 1] as const;
// jitless 关掉 Zod 模块求值时的 `new Function` eval 探测:探测的 throw 被库吞掉,但浏览器仍就地点报一次 securitypolicyviolation(本站 CSP 无 'unsafe-eval'),会淹没真实违规的定位。
z.config({ jitless: true });
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;
}
interface ContactData {
heroSubtitle?: string;
heroTitle?: string;
heroDescription?: string;
contactTitle?: string;
emailLabel?: string;
addressLabel?: string;
email?: string;
address?: string;
workHoursTitle?: string;
dayLabel?: string;
hours?: string;
commitmentTitle?: string;
commitmentItems?: string[];
formTitle?: string;
successTitle?: string;
successMessage?: string;
submitLabel?: string;
submittingLabel?: string;
ctaSubtitle?: string;
ctaTitle?: string;
ctaDescription?: string;
ctaPrimaryLabel?: string;
ctaPrimaryHref?: string;
ctaSecondaryLabel?: string;
ctaSecondaryHref?: string;
}
function ContactFormContent({ data }: { data: ContactData }) {
// 2026-10-20(冷首访白屏):不再用 `useSearchParams()`。
// 它在客户端组件里会让本页在预渲染时**退化成 Suspense fallback**(首访只看到「加载中…」,
// 实测限速下 ~6s 才出现内容)。该参数只用于展示一次成功提示,
// 挂载后从 window.location 读即可,页面因此可以完整预渲染。
const [showToast, setShowToast] = useState(false);
const [toastMessage, setToastMessage] = useState('');
// 初值仅在 ?success=true 重定向时随 showToast/isSubmitted 一同生效,故恒为 success。
const [toastType, setToastType] = useState<'success' | 'error'>('success');
const [isSubmitting, setIsSubmitting] = useState(false);
const [isSubmitted, setIsSubmitted] = useState(false);
const [formData, setFormData] = useState<ContactFormData>({
name: '',
phone: '',
email: '',
subject: '',
message: '',
});
const [errors, setErrors] = useState<FormErrors>({});
// 成功重定向:挂载后读一次 ?success=true,应用成功态并立即从 URL 移除(刷新不应重放)
useEffect(() => {
if (typeof window === 'undefined') return;
if (new URLSearchParams(window.location.search).get('success') !== 'true') return;
setShowToast(true);
setToastMessage('表单提交成功!我们会尽快与您联系。');
setIsSubmitted(true);
const url = new URL(window.location.href);
url.searchParams.delete('success');
window.history.replaceState(null, '', url.pathname + url.search + url.hash);
}, []);
const emailAddress = data.email ?? '';
const addressText = data.address ?? '';
const validateField = (field: keyof ContactFormData, value: string) => {
try {
contactFormSchema.shape[field].parse(value);
// 通过时必须删除 key:留成 undefined 会让 Object.keys(errors) 把有效字段也计入
// 「请修正以下 N 项内容」,虚假错误面板在输入过程中插入并顶开表单布局。
setErrors((prev) => {
if (!(field in prev)) {return prev;}
const next = {...prev};
delete next[field];
return next;
});
} 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) => {
setFormData((prev) => ({ ...prev, [field]: value }));
if (errors[field]) {
validateField(field, value);
}
};
const handleBlur = (field: keyof ContactFormData, value: string) => {
validateField(field, value);
};
async function handleSubmit(e: React.FormEvent<HTMLFormElement>) {
e.preventDefault();
const result = contactFormSchema.safeParse(formData);
if (!result.success) {
const fieldErrors: FormErrors = {};
result.error.issues.forEach((issue) => {
const field = issue.path[0] as keyof ContactFormData;
if (!fieldErrors[field]) {
fieldErrors[field] = issue.message;
}
});
setErrors(fieldErrors);
setToastMessage(`请检查表单:${Object.keys(fieldErrors).length} 项内容需要修正`);
setToastType('error');
setShowToast(true);
// 滚动到表单区域,让用户看到错误提示
setTimeout(() => {
const formSection = document.getElementById('contact-form-section');
if (formSection) {
formSection.scrollIntoView({ behavior: 'smooth', block: 'start' });
}
}, 100);
return;
}
setIsSubmitting(true);
try {
const formBody = new URLSearchParams();
formBody.append('name', formData.name);
formBody.append('phone', formData.phone);
formBody.append('email', formData.email);
formBody.append('subject', formData.subject);
formBody.append('message', formData.message);
const response = await fetch('/api/contact', {
method: 'POST',
body: formBody,
});
const resultData = await response.json();
if (response.ok && (resultData.success === 'true' || resultData.success === true)) {
// trackContactForm 内部已发送 form_submit 事件并触发 conversion,
// 不再额外调用 trackConversion,避免同一个提交被重复计为两次转化。
trackContactForm(
{
name: formData.name,
email: formData.email,
company: formData.subject,
},
true,
);
setToastMessage(data.successMessage || '提交成功!我们会尽快与您联系。');
setToastType('success');
setShowToast(true);
setIsSubmitted(true);
setFormData({ name: '', phone: '', email: '', subject: '', message: '' });
setErrors({});
} else {
const errorMsg = resultData.message || '提交失败,请稍后重试或直接发送邮件联系我们。';
if (errorMsg.includes('HTML files') || errorMsg.includes('web server')) {
setToastMessage(`表单服务需要在生产环境激活。部署后首次提交会发送确认邮件到 ${emailAddress}`);
} else {
setToastMessage(errorMsg);
}
setToastType('error');
setShowToast(true);
}
} catch {
setToastMessage('网络错误,请稍后重试。');
setToastType('error');
setShowToast(true);
} finally {
setIsSubmitting(false);
}
}
const heroTitleLines = (data.heroTitle || '随时欢迎\n与您聊聊需求').split('\n');
const commitmentItems = data.commitmentItems ?? [];
return (
<div className="min-h-screen bg-bg-primary text-ink overflow-x-hidden">
<BreadcrumbSchema items={[{ name: '首页', href: '/' }, { name: '联系我们', href: '/contact' }]} />
{showToast && (
<Toast
message={toastMessage}
type={toastType}
duration={toastType === 'error' ? 6000 : undefined}
onClose={() => setShowToast(false)}
/>
)}
{/* Hero Section —— critique P2(2026-09-19):80vh 巨幅把转化表单推出首屏,
转化页按 DESIGN.md 紧凑档处理:无 min-h、py 收窄,表单回到首屏视野。 */}
<section className="relative flex items-center overflow-hidden bg-bg-primary">
<div className="max-w-container mx-auto px-4 sm:px-6 lg:px-10 relative z-10 w-full py-16 sm:py-20 lg:py-28">
<div className="max-w-4xl">
{data.heroSubtitle && (
<motion.div
initial={{ opacity: 0, y: 20 }}
animate={{ opacity: 1, y: 0 }}
transition={{ duration: 0.28, delay: 0.1, ease: EASE_OUT }}
className="text-sm font-mono tracking-[0.15em] text-text-muted mb-8"
>
{data.heroSubtitle}
</motion.div>
)}
<motion.h1
initial={{ opacity: 0, y: 40 }}
animate={{ opacity: 1, y: 0 }}
transition={{ duration: 0.28, delay: 0.2, ease: EASE_OUT }}
className="text-4xl sm:text-5xl md:text-6xl lg:text-7xl font-black text-ink leading-[0.88] tracking-tighter mb-10 sm:mb-12 md:mb-16"
>
{heroTitleLines.map((line, i) => (
<div key={i} className={`block ${i > 0 ? 'mt-4 sm:mt-6' : ''}`}>
{i === 1 ? (
<span className="relative inline-block">
<span className="relative text-brand-ink font-black">
{line}
<motion.span
className="absolute -bottom-2 left-0 w-full h-[3px] bg-brand"
style={{ transformOrigin: 'left' }}
initial={{ scaleX: 0 }}
animate={{ scaleX: 1 }}
// 装饰性标题下划线:delay 属调度不属时长,1.2s 为已批准保留值
// (见 .workbuddy/memory/2026-09-04.md「delay 一律判 P2,不得判 P0;
// 字面 delay >150ms 保留」),且全站另有 6 处同形同值,改一处即跨页不一致。
transition={{ duration: 0.28, delay: 1.2, ease: EASE_OUT }}
/>
</span>
</span>
) : (
line
)}
</div>
))}
</motion.h1>
{data.heroDescription && (
<motion.p
initial={{ opacity: 0, y: 30 }}
animate={{ opacity: 1, y: 0 }}
transition={{ duration: 0.28, delay: 0.5, ease: EASE_OUT }}
className="text-lg md:text-xl text-text-secondary max-w-2xl leading-relaxed mb-12 sm:mb-16"
>
{data.heroDescription}
</motion.p>
)}
</div>
</div>
</section>
{/* Form + Info Section */}
<section className="relative py-20 sm:py-28 md:py-36 lg:py-44 overflow-hidden bg-bg-secondary">
<div className="max-w-container mx-auto px-4 sm:px-6 lg:px-10 relative z-10">
<div className="grid lg:grid-cols-5 gap-10 lg:gap-14">
{/* Left: Contact Info */}
<motion.div
initial={{ opacity: 0, y: 30 }}
whileInView={{ opacity: 1, y: 0 }}
viewport={{ once: true, margin: '-60px' }}
transition={{ duration: 0.28, ease: EASE_OUT }}
className="lg:col-span-2 space-y-8"
>
<div>
{data.contactTitle && (
<h2 className="text-xl font-bold text-ink mb-8">{data.contactTitle}</h2>
)}
<div className="space-y-6" data-testid="contact-info">
<div className="flex items-start gap-4" data-testid="email-info">
<div className="w-12 h-12 border border-border-primary bg-bg-elevated flex items-center justify-center shrink-0" aria-hidden="true">
<Mail className="w-5 h-5 text-text-secondary" />
</div>
<div className="mt-3.5">
<p className="text-sm text-text-muted mb-1">{data.emailLabel || ''}</p>
<a
href={`mailto:${emailAddress}`}
className="inline-flex items-center min-h-6 text-ink hover:text-brand-ink transition-colors duration-normal"
data-testid="email-link"
>
{emailAddress}
</a>
</div>
</div>
<div className="flex items-start gap-4" data-testid="address-info">
<div className="w-12 h-12 border border-border-primary bg-bg-elevated flex items-center justify-center shrink-0" aria-hidden="true">
<MapPin className="w-5 h-5 text-text-secondary" />
</div>
<div className="mt-3.5">
<p className="text-sm text-text-muted mb-1">{data.addressLabel || ''}</p>
<p className="text-ink" data-testid="address-text">
{addressText}
</p>
</div>
</div>
</div>
</div>
<div className="relative border border-border-primary bg-bg-elevated p-8 overflow-hidden">
<div className="absolute top-0 left-0 bottom-0 w-0.5 bg-brand/60" />
<div className="flex items-center gap-3 mb-4">
<Clock className="w-5 h-5 text-brand-ink" aria-hidden="true" />
<h2 className="text-base font-bold text-ink">{data.workHoursTitle || ''}</h2>
</div>
<div className="flex justify-between" data-testid="work-hours-row">
<span className="text-text-secondary">{data.dayLabel || ''}</span>
<span className="text-brand-ink font-medium">{data.hours || ''}</span>
</div>
</div>
<div className="relative border border-border-primary bg-bg-elevated p-8 overflow-hidden">
<div className="absolute top-0 left-0 bottom-0 w-0.5 bg-brand/60" />
<div className="flex items-center gap-3 mb-4">
<HeadphonesIcon className="w-5 h-5 text-text-secondary" aria-hidden="true" />
<h2 className="text-base font-bold text-ink">{data.commitmentTitle || ''}</h2>
</div>
<div className="space-y-4">
{commitmentItems.map((item, idx) => (
<div key={idx} className="flex items-start gap-3">
<div className="w-1 h-1 bg-text-muted rounded-full mt-2.5 shrink-0" />
<p className="text-text-secondary">{item}</p>
</div>
))}
</div>
</div>
</motion.div>
{/* Right: Form */}
<motion.div
initial={{ opacity: 0, y: 30 }}
whileInView={{ opacity: 1, y: 0 }}
viewport={{ once: true, margin: '-60px' }}
transition={{ duration: 0.28, delay: 0.1, ease: EASE_OUT }}
className="lg:col-span-3"
>
<div className="relative border border-border-primary bg-bg-elevated p-6 sm:p-8 lg:p-10 h-full overflow-hidden" id="contact-form-section">
<div className="absolute top-0 left-0 right-0 h-0.5 bg-brand" />
<h2 className="text-xl font-bold text-ink mb-8">{data.formTitle || ''}</h2>
{Object.keys(errors).length > 0 && (
<div className="mb-6 p-4 border border-brand/30 bg-brand/5" role="alert">
<p className="text-sm font-bold text-brand-ink mb-2">
请修正以下 {Object.keys(errors).length} 项内容:
</p>
<ul className="space-y-1">
{Object.entries(errors).map(([field, message]) => (
<li key={field} className="text-sm text-text-secondary flex items-start gap-2">
<span className="text-brand-ink shrink-0 mt-0.5">&#8226;</span>
<span>{message}</span>
</li>
))}
</ul>
</div>
)}
{isSubmitted ? (
<div className="text-center py-16">
<div className="w-20 h-20 bg-brand rounded-full flex items-center justify-center mx-auto mb-6">
<CheckCircle2 className="w-10 h-10 text-white" />
</div>
<h4 className="text-2xl font-bold text-ink mb-3">{data.successTitle || '提交成功'}</h4>
<p className="text-text-secondary mb-10">{data.successMessage || '感谢您的留言,我们会尽快与您联系。'}</p>
<div className="flex flex-col items-center justify-center gap-5 mb-10">
<CTAButton href="/methodology">先看看我们如何工作</CTAButton>
<StaticLink
href="/products"
className="text-sm text-text-secondary underline-offset-4 transition-colors hover:text-brand-ink hover:underline"
>
或先浏览产品矩阵
</StaticLink>
</div>
<button
type="button"
onClick={() => setIsSubmitted(false)}
className="text-sm text-text-muted transition-colors hover:text-text-secondary"
>
继续提交其他问题
</button>
</div>
) : (
<form onSubmit={handleSubmit} className="space-y-6" noValidate>
<input
type="text"
name="website"
style={{ display: 'none' }}
tabIndex={-1}
autoComplete="off"
aria-hidden="true"
aria-label="honeypot"
/>
<div className="grid grid-cols-1 sm:grid-cols-2 gap-6">
<div className="relative">
<Input
name="name"
data-testid="name-input"
label={
<span className="flex items-center gap-1.5">
姓名
<Tooltip content="用于正式沟通和方案报价">
<HelpCircle className="w-3.5 h-3.5 text-text-muted hover:text-brand-ink cursor-help" />
</Tooltip>
</span>
}
id="name"
placeholder="请输入您的姓名"
required
value={formData.name}
onChange={(e) => handleChange('name', e.target.value)}
onBlur={(e) => handleBlur('name', e.target.value)}
error={errors.name}
className="bg-bg-elevated border-border-primary text-ink placeholder:text-text-muted focus:border-brand/50"
/>
</div>
<div className="relative">
<Input
name="phone"
data-testid="phone-input"
label={
<span className="flex items-center gap-1.5">
电话
<Tooltip content="接收项目进度通知和验证码,仅用于业务联系">
<HelpCircle className="w-3.5 h-3.5 text-text-muted hover:text-brand-ink cursor-help" />
</Tooltip>
</span>
}
id="phone"
type="tel"
placeholder="请输入11位手机号"
required
value={formData.phone}
onChange={(e) => handleChange('phone', e.target.value)}
onBlur={(e) => handleBlur('phone', e.target.value)}
error={errors.phone}
className="bg-bg-elevated border-border-primary text-ink placeholder:text-text-muted focus:border-brand/50"
/>
</div>
</div>
<Input
name="email"
data-testid="email-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}
className="bg-bg-elevated border-border-primary text-ink placeholder:text-text-muted focus:border-brand/50"
/>
<Input
name="subject"
data-testid="subject-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}
className="bg-bg-elevated border-border-primary text-ink placeholder:text-text-muted focus:border-brand/50"
/>
<Textarea
name="message"
data-testid="message-input"
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}
className="bg-bg-elevated border-border-primary text-ink placeholder:text-text-muted focus:border-brand/50"
/>
<Button
type="submit"
data-testid="submit-button"
size="xl"
className="w-full h-14 disabled:opacity-70"
disabled={isSubmitting}
>
{isSubmitting ? (
<span className="flex items-center justify-center gap-2">
<Loader2 className="h-5 w-5 animate-spin" />
<span>{data.submittingLabel || '...'}</span>
</span>
) : (
<>
<span>{data.submitLabel || '发送'}</span>
<Send className="h-4 w-4" />
</>
)}
</Button>
</form>
)}
</div>
</motion.div>
</div>
</div>
</section>
{/* CTA Section */}
<section className="relative py-20 sm:py-28 md:py-36 lg:py-44 overflow-hidden bg-bg-primary">
<div className="max-w-container mx-auto px-4 sm:px-6 lg:px-10 relative z-10">
<motion.div
initial={{ opacity: 0, y: 30 }}
whileInView={{ opacity: 1, y: 0 }}
viewport={{ once: true, margin: '-60px' }}
transition={{ duration: 0.28, ease: EASE_OUT }}
className="max-w-3xl mx-auto text-center"
>
<div className="text-sm font-mono tracking-[0.2em] text-text-muted uppercase mb-8">
{data.ctaSubtitle || ''}
</div>
<h2 className="text-3xl sm:text-4xl md:text-5xl lg:text-6xl font-black text-ink tracking-tight leading-tight mb-8">
{data.ctaTitle || ''}
</h2>
<p className="text-lg md:text-xl text-text-secondary leading-relaxed mb-12">
{data.ctaDescription || ''}
</p>
<div className="flex flex-col sm:flex-row gap-4 sm:gap-6 justify-center">
{data.ctaPrimaryLabel && data.ctaPrimaryHref && (
<CTAButton href={data.ctaPrimaryHref} className="px-12 py-6 font-bold">
{canonicalCtaLabel(data.ctaPrimaryLabel)}
</CTAButton>
)}
{data.ctaSecondaryLabel && data.ctaSecondaryHref && (
<CTAButton href={data.ctaSecondaryHref} variant="secondary" className="px-12 py-6 font-bold">
{data.ctaSecondaryLabel}
</CTAButton>
)}
</div>
</motion.div>
</div>
</section>
</div>
);
}
function EmptyState() {
return <ContentUnavailableState pageName="联系我们" />;
}
export default function ContactContentV3({ data }: { data: Record<string, unknown> }) {
const contactData = data as ContactData;
// Empty state when no CMS data is available
if (!data || Object.keys(data).length === 0) {
return <EmptyState />;
}
return (
<Suspense
fallback={
<div className="min-h-screen bg-bg-primary flex items-center justify-center">
<div className="animate-pulse text-text-muted">加载中...</div>
</div>
}
>
<ContactFormContent data={contactData} />
</Suspense>
);
}