diff --git a/scripts/dead-modules.mjs b/scripts/dead-modules.mjs new file mode 100644 index 0000000..de9ab80 --- /dev/null +++ b/scripts/dead-modules.mjs @@ -0,0 +1,172 @@ +#!/usr/bin/env node +/** + * 站内模块可达性判定:从真实入口(app/**\/page.tsx、layout、api route)做 import 闭包, + * 报出「没有任何入口能到达」的模块。 + * + * 为什么要这么判,而不是 grep 文件名: + * 1. 相对导入 `from './micro-interactions'` 用全路径正则扫不出来 —— 第一版就因此把 + * detail-hero.tsx 正在用的组件误判成死码。**判死码判错 = 误删活代码。** + * 2. 桶文件(detail/index.ts 再导出)会让"谁引用了它"的答案变成"引用了桶", + * 必须顺着一个真实 specifier 解析到落点文件再判。 + * 3. 只看"有没有 import 方"也不够:A 引 B、B 引 C,但 A 自己没人引 —— 整条链都是死的。 + * 可达性闭包才回答"这文件有没有可能进产物"。 + * + * 输出退出码:0 有死码 / 2 判定不可信(入口为 0、解析报错)。**不判 1**: + * 死码存在不是构建失败,而是台账 DEC-P-2 的存量,判红会让这道检查永远进不了 CI。 + */ +import { readFileSync, readdirSync, existsSync, statSync } from 'node:fs'; +import path from 'node:path'; + +// 扫描根可以有多个:只扫 src 会漏掉**门禁脚本与 e2e 对 src 的引用** +// (scripts/utils/check-color-contrast.ts 就 import 了 src/lib/color-contrast.ts, +// 只扫 src 时它被误判成死码)。入口仍只取 app/ 约定文件,其余根只贡献"谁在引"。 +const ROOTS = process.argv.length > 2 ? process.argv.slice(2) : ['src', 'scripts', 'e2e', 'config']; +const ROOT = 'src'; +const missing = ROOTS.filter((r) => !existsSync(r)); +if (missing.length) { console.error(`未能度量:根目录不存在 ${missing.join(', ')}`); process.exit(2); } + +function walk(dir, acc = []) { + for (const e of readdirSync(dir, { withFileTypes: true })) { + if (['node_modules', '.git', 'dist', '_archive', '.next'].includes(e.name)) continue; + const p = path.join(dir, e.name); + if (e.isDirectory()) walk(p, acc); + else if (/\.(tsx?|mjs)$/.test(e.name)) acc.push(p); + } + return acc; +} + +const files = ROOTS.flatMap((r) => walk(r)); +const texts = new Map(files.map((f) => [path.normalize(f), readFileSync(f, 'utf8')])); +const EXT = ['', '.ts', '.tsx', '.js', '.mjs', '/index.ts', '/index.tsx']; + +/** specifier → 站内落点文件(解析不到=第三方包或资源文件,返回 null) */ +function resolve(spec, fromFile) { + let base; + if (spec.startsWith('@/')) base = path.join(ROOT, spec.slice(2)); + // ⚠ 必须用 path.join 而不是 path.resolve:resolve 会拼上 cwd 变成**绝对路径**, + // 而模块表 texts 的 key 是 walk 出来的相对路径 ⇒ 所有 `./x` 相对导入都匹配不上、 + // 边被静默丢弃(`@/` 开头的反而正常,于是可达数看着像个数、其实是半瞎的)。 + // 本仓页面组件多用相对导入,第一版因此把 home-content-v16 报成死码。 + else if (spec.startsWith('./') || spec.startsWith('../')) base = path.normalize(path.join(path.dirname(fromFile), spec)); + else return null; + for (const e of EXT) { + const cand = path.normalize(base + e); + if (existsSync(cand) && statSync(cand).isFile()) return cand; + } + return null; +} + +/** + * 静态 from、再导出 from、**动态 import()**、require() 都要算边。 + * 第一版只匹配 `from '...'`,于是 GoogleAnalyticsWrapper 里的 + * const GoogleAnalytics = dynamic(() => import('./GoogleAnalytics')) + * 这条边不存在 ⇒ GA 组件被报成"零引用死码"。按那结果删掉它, + * GA4 会在没有单测、没有 e2e 断言渲染的情况下从页面上消失。 + * 动态导入的 specifier 是字符串字面量,这里一并抓(模式串无法静态解析,按字面量解析)。 + */ +const IMPORT_RE = /(?:from|import|require)\s*\(?\s*['"]([^'"]+)['"]/g; +const edgesFrom = (file) => { + const txt = texts.get(file); + if (txt === undefined) return []; + const out = []; + for (const m of txt.matchAll(IMPORT_RE)) { + const t = resolve(m[1], file); + if (t && texts.has(t)) out.push(t); + } + return out; +}; + +/** + * App Router 的入口 = 位于 app/ 之下、文件名属于 Next 约定的那些模块。 + * ⚠ 第一版写成 /(^|\/)app\/.*(^|\/)layout\.tsx$/ —— 中间的 (^|\/) 强制要求 + * `layout.tsx` 前面有一个 `/`,于是 src/app/layout.tsx 这种**根级约定文件根本没被认成入口**, + * 连带它 import 的整棵树全部误判成死码(实测把 home-content-v16、layout 自己都报成"零引用")。 + * 带着那版结果去删码就是删活码。判据改成按目录段 + 基名精确匹配。 + */ +const NEXT_CONVENTION_BASENAMES = new Set([ + 'page.tsx', 'page.ts', 'layout.tsx', 'layout.ts', 'template.tsx', 'loading.tsx', + 'error.tsx', 'global-error.tsx', 'not-found.tsx', 'route.ts', 'route.tsx', + 'sitemap.ts', 'robots.ts', 'manifest.ts', 'opengraph-image.tsx', 'icon.tsx', +]); +const isEntry = (f) => { + const segments = f.split(path.sep); + if (!segments.includes('app')) return false; + const base = segments[segments.length - 1]; + if (NEXT_CONVENTION_BASENAMES.has(base)) return true; + // 应用级非 import 入口:根 layout 之外的约定文件与 instrumentation/proxy 同理靠文件名而非路径深度 + return segments.length === 2 && segments[0] === 'src' + && /^(instrumentation|proxy)\.ts$/.test(base); +}; + +const norm = files.map((f) => path.normalize(f)); +const entries = norm.filter(isEntry); +// 非 src 根(scripts/e2e/config)里的每个文件都当成一个使用者种子: +// 它们引用的 src 模块不是死码,哪怕页面 import 图到不了。 +const consumerSeeds = norm.filter((f) => !f.startsWith(ROOT + path.sep)); +if (entries.length === 0) { console.error('未能度量:找不到任何入口文件'); process.exit(2); } + +const reachable = new Set(); +const stack = [...entries, ...consumerSeeds]; +while (stack.length) { + const cur = stack.pop(); + if (reachable.has(cur)) continue; + reachable.add(cur); + for (const t of edgesFrom(cur)) if (!reachable.has(t)) stack.push(t); +} + +// 反向引用表(含测试与桶文件,供报告用) +const importers = new Map(); +for (const f of texts.keys()) for (const t of edgesFrom(f)) { + if (!importers.has(t)) importers.set(t, new Set()); + importers.get(t).add(f); +} + +const testFile = (f) => /\.test\.|__tests__/.test(f); +const barrel = (f) => /(^|\/)index\.ts$/.test(f); + +const all = [...texts.keys()].filter((f) => !reachable.has(f)).sort(); + +/** + * 关键一步:不可达 ≠ 死码。第一版直接把 48 个不可达文件全列成"死码", + * 里面混着三类**必须**排除的东西 —— 照单删就会删掉在跑的生产代码: + * · 框架约定文件:由 Next/运行时按文件名加载,永远不会出现在 import 图里 + * (proxy.ts = Next 16 的中间件约定、instrumentation*.ts、*.d.ts 是环境声明) + * · 生成物:src/generated/** 由 prisma generate 产出,不在入口闭包内 + * · 组件库库存:src/components/ui/** 的 shadcn/Radix 原语是**故意**给后台与未来页面用的 + * (avatar/switch/slider/progress/scroll-area 等还承载 check:grammar R2/R9 的"功能性的圆"), + * 删它们是个产品决定,不是清理。 + */ +const CATEGORY_RULES = [ + ['convention', (f) => /(^|\/)(proxy|instrumentation|instrumentation-client)\.ts$/.test(f) + || /\.d\.ts$/.test(f) + || /(^|\/)(not-found|global-error|error|loading|template)\.tsx?$/.test(f)], + ['generated', (f) => /(^|\/)generated\//.test(f)], + ['library', (f) => /(^|\/)components\/ui\//.test(f)], + ['test', (f) => testFile(f)], +]; +const buckets = new Map(); +for (const f of all) { + const cat = CATEGORY_RULES.find(([, pred]) => pred(f))?.[0] ?? 'dead'; + if (!buckets.has(cat)) buckets.set(cat, []); + buckets.get(cat).push(f); +} + +console.log(`入口 ${entries.length} 个 · 站内模块 ${texts.size} 个 · 可达 ${reachable.size} 个 · 不可达 ${all.length} 个`); +for (const cat of ['convention', 'generated', 'library', 'test', 'dead']) { + const list = buckets.get(cat) || []; + const label = { + convention: '框架约定/环境声明(不可达属正常,勿删)', + generated: '生成物(不在 import 图内,勿删)', + library: '组件库库存(未被引用但是库存,删除是产品决定)', + test: '测试文件本身', + dead: '*** 可判为死码 ***', + }[cat]; + console.log(`\n[${cat}] ${list.length} 个 — ${label}`); + if (cat === 'dead' || cat === 'library') { + for (const f of list) { + const refBy = [...(importers.get(f) || [])]; + const onlyDeadOrTests = refBy.length === 0 || refBy.every((r) => testFile(r) || barrel(r) || !reachable.has(r)); + console.log(` ${f} ← ${refBy.length === 0 ? '零引用' : onlyDeadOrTests ? '仅测试/死链引用' : '被可达文件引用?!'}`); + } + } +} diff --git a/src/app/(marketing)/news/[slug]/NewsDetailClient.test.tsx b/src/app/(marketing)/news/[slug]/NewsDetailClient.test.tsx deleted file mode 100644 index 0cedbe8..0000000 --- a/src/app/(marketing)/news/[slug]/NewsDetailClient.test.tsx +++ /dev/null @@ -1,95 +0,0 @@ -import { render, screen } from '@testing-library/react'; -import '@testing-library/jest-dom'; -import { NewsDetailClient } from './NewsDetailClient'; - -jest.mock('next/navigation', () => ({ - useRouter: () => ({ - push: jest.fn(), - back: jest.fn(), - }), -})); - -jest.mock('next/link', () => { - const MockLink = ({ children, href }: { children: React.ReactNode; href: string }) => { - return {children}; - }; - MockLink.displayName = 'MockLink'; - return MockLink; -}); - -jest.mock('framer-motion', () => ({ - motion: { - div: ({ children }: { children: React.ReactNode }) =>
{children}
, - }, - useInView: () => true, -})); - -const mockNews = { - id: 'test-news', - title: '测试新闻标题', - category: '公司新闻', - date: '2024-01-01', - excerpt: '这是测试新闻摘要', - content: '这是测试新闻内容', -}; - -describe('NewsDetailClient', () => { - beforeEach(() => { - jest.clearAllMocks(); - }); - - describe('Rendering', () => { - it('should render news detail page', () => { - render(); - const titles = screen.getAllByText('测试新闻标题'); - expect(titles.length).toBeGreaterThan(0); - }); - - it('should render news title', () => { - render(); - const title = screen.getByRole('heading', { level: 1 }); - expect(title).toBeInTheDocument(); - expect(title).toHaveTextContent('测试新闻标题'); - }); - - it('should render news category', () => { - render(); - const categories = screen.getAllByText('公司新闻'); - expect(categories.length).toBeGreaterThan(0); - }); - - it('should render news date', () => { - render(); - const date = screen.getByText('2024-01-01'); - expect(date).toBeInTheDocument(); - }); - - it('should render news excerpt', () => { - render(); - const excerpt = screen.getByText('这是测试新闻摘要'); - expect(excerpt).toBeInTheDocument(); - }); - - it('should render news content', () => { - render(); - const content = screen.getByText('这是测试新闻内容'); - expect(content).toBeInTheDocument(); - }); - }); - - describe('Navigation', () => { - it('should have back button', () => { - render(); - const backButtons = screen.getAllByRole('button', { name: /返回/i }); - expect(backButtons.length).toBeGreaterThan(0); - }); - }); - - describe('Accessibility', () => { - it('should have proper heading hierarchy', () => { - render(); - const h1 = screen.getByRole('heading', { level: 1 }); - expect(h1).toBeInTheDocument(); - }); - }); -}); diff --git a/src/app/(marketing)/news/[slug]/NewsDetailClient.tsx b/src/app/(marketing)/news/[slug]/NewsDetailClient.tsx deleted file mode 100644 index 1c7d556..0000000 --- a/src/app/(marketing)/news/[slug]/NewsDetailClient.tsx +++ /dev/null @@ -1,155 +0,0 @@ -'use client'; - -import { StaticLink } from '@/components/ui/static-link'; -import { CTAButton } from '@/components/ui/cta-button'; -import { CTA_LABELS } from '@/lib/constants/cta-labels'; -import { Button } from '@/components/ui/button'; -import { Badge } from '@/components/ui/badge'; -import { Card } from '@/components/ui/card'; -import { Calendar, ArrowLeft, Newspaper } from 'lucide-react'; -import { motion } from 'framer-motion'; -import { useReducedMotion } from '@/hooks/use-reduced-motion'; -import { NEWS } from '@/lib/constants'; - -const EASE = [0.25, 1, 0.5, 1] as const; - -interface NewsDetailClientProps { - news: typeof NEWS[0]; -} - -export function NewsDetailClient({ news }: NewsDetailClientProps) { - const shouldReduceMotion = useReducedMotion(); - - const relatedNews = NEWS - .filter((n) => n.id !== news.id && n.category === news.category) - .slice(0, 3); - - return ( -
- {/* Article Header */} -
-
- {/* Breadcrumb */} - - - - {/* hover 底色用 12% 软红令牌而非 /20:半透明底叠加页面底色后, - 浅色主题下 text-brand-ink 实测 4.18:1(< AA 4.5:1),12% 为 4.80:1;深色分别 6.22 / 6.60。 */} - - {news.category} - -

- {news.title} -

-
-
- - {news.date} -
-
-
- -
-
- - {/* Article Body */} -
-
- - {/* Featured Image */} - {news.image ? ( -
- {news.title} -
- ) : ( -
- -
- )} - - {/* Excerpt */} - -

- {news.excerpt} -

-
- - {/* Article Content */} -
- {news.content} -
- - {/* Related News */} - {relatedNews.length > 0 && ( -
-

相关新闻

-
- {relatedNews.map((related) => ( - - -
- {related.image ? ( - {related.title} - ) : ( -
- -
- )} -
-
- {related.category} -

- {related.title} -

-

{related.excerpt}

-
-
-
- ))} -
-
- )} - - {/* Navigation */} -
- - - - - {CTA_LABELS.consult} - -
-
-
-
-
- ); -} diff --git a/src/components/detail/detail.test.tsx b/src/components/detail/detail.test.tsx index f1a0bd0..ad91092 100644 --- a/src/components/detail/detail.test.tsx +++ b/src/components/detail/detail.test.tsx @@ -168,49 +168,6 @@ jest.mock('lucide-react', () => { return icons; }); -jest.mock('@/lib/constants/design-system', () => ({ - DESIGN_SYSTEM: { - animation: { - duration: { fast: '0.2s', normal: '0.4s', slow: '0.6s', slower: '0.8s', countUp: '2s' }, - easing: { smooth: 'cubic-bezier(0.4, 0, 0.2, 1)', bounce: 'cubic-bezier(0.34, 1.56, 0.64, 1)', easeOut: 'cubic-bezier(0, 0, 0.2, 1)', easeInOut: 'cubic-bezier(0.4, 0, 0.6, 1)' }, - delay: { stagger: 0.08, section: 0.15 }, - }, - spacing: { - section: { py: 'py-20 lg:py-28', pyCompact: 'py-16 lg:py-20' }, - container: { default: 'max-w-7xl mx-auto px-4 sm:px-6 lg:px-8', narrow: 'max-w-5xl mx-auto px-4 sm:px-6 lg:px-8', wide: 'max-w-[1400px] mx-auto px-4 sm:px-6 lg:px-8' }, - grid: { gap: 'gap-6 lg:gap-8', gapSmall: 'gap-4 lg:gap-6' }, - }, - typography: { - hero: { title: 'text-4xl', subtitle: 'text-lg', description: 'text-base' }, - section: { title: 'text-3xl', subtitle: 'text-lg', body: 'text-base' }, - card: { title: 'text-lg', description: 'text-sm' }, - }, - effects: { - inkGlow: { border: 'conic-gradient(...)', glow: 'radial-gradient(...)', speed: '3s' }, - hover: { translateY: '-4px', shadow: 'shadow-xl', transition: 'all 0.3s' }, - scroll: { - fadeInUp: { - initial: { opacity: 0, y: 24 }, - animate: { opacity: 1, y: 0 }, - viewport: { once: true, margin: '-80px' }, - transition: { duration: 0.6, ease: [0.16, 1, 0.3, 1] }, - }, - staggerChildren: { delay: 0.08 }, - }, - }, - colors: { - brand: { primary: 'var(--color-brand)', light: 'var(--color-brand-bg)', lighter: 'rgba(var(--color-brand-rgb), 0.04)', gradient: 'linear-gradient(135deg, var(--color-brand) 0%, #99182d 100%)' }, - neutral: { '50': 'var(--color-bg-primary)', '100': 'var(--color-bg-section)', '200': 'var(--color-border-primary)' }, - ink: { light: 'rgba(0, 0, 0, 0.03)', medium: 'rgba(0, 0, 0, 0.06)' }, - }, - components: { - card: { base: 'rounded-2xl', hover: 'hover:-translate-y-1', padding: 'p-6' }, - badge: { base: 'inline-flex', variants: { primary: 'bg-brand-soft', secondary: 'bg-bg-tertiary' } }, - button: { primary: 'bg-brand', secondary: 'bg-white', ghost: 'bg-transparent' }, - metric: { container: 'text-center', value: 'text-3xl', label: 'text-sm', description: 'text-xs' }, - }, - }, -})); // ─── Mock Data ─────────────────────────────────────────────────────────── diff --git a/src/components/layout/breadcrumb.test.tsx b/src/components/layout/breadcrumb.test.tsx deleted file mode 100644 index ae9e97d..0000000 --- a/src/components/layout/breadcrumb.test.tsx +++ /dev/null @@ -1,52 +0,0 @@ -import { render, screen } from '@testing-library/react'; -import '@testing-library/jest-dom'; -import { Breadcrumb } from './breadcrumb'; - -jest.mock('next/link', () => { - return ({ children, href }: { children: React.ReactNode; href: string }) => { - return {children}; - }; -}); - -describe('Breadcrumb', () => { - beforeEach(() => { - jest.clearAllMocks(); - }); - - describe('Rendering', () => { - it('should render breadcrumb component', () => { - render(); - const nav = screen.getByRole('navigation', { name: /breadcrumb/i }); - expect(nav).toBeInTheDocument(); - }); - - it('should render home link', () => { - render(); - const homeLinks = screen.getAllByRole('link'); - expect(homeLinks.length).toBeGreaterThan(0); - }); - - it('should render breadcrumb items', () => { - const items = [ - { label: 'Products', href: '/products' }, - { label: 'Details', href: '/products/1' }, - ]; - - render(); - - const productLink = screen.getByRole('link', { name: /Products/i }); - const detailsLink = screen.getByRole('link', { name: /Details/i }); - - expect(productLink).toBeInTheDocument(); - expect(detailsLink).toBeInTheDocument(); - }); - }); - - describe('Accessibility', () => { - it('should have nav element with aria-label', () => { - render(); - const nav = screen.getByRole('navigation', { name: /breadcrumb/i }); - expect(nav).toBeInTheDocument(); - }); - }); -}); diff --git a/src/components/layout/breadcrumb.tsx b/src/components/layout/breadcrumb.tsx deleted file mode 100644 index 2191c24..0000000 --- a/src/components/layout/breadcrumb.tsx +++ /dev/null @@ -1,38 +0,0 @@ -'use client'; - -import { StaticLink } from '@/components/ui/static-link'; -import { ChevronRight, Home } from 'lucide-react'; - -interface BreadcrumbItem { - label: string; - href: string; -} - -interface BreadcrumbProps { - items: BreadcrumbItem[]; -} - -export function Breadcrumb({ items }: BreadcrumbProps) { - return ( - - ); -} diff --git a/src/components/sections/case-card.test.tsx b/src/components/sections/case-card.test.tsx deleted file mode 100644 index 9d8e923..0000000 --- a/src/components/sections/case-card.test.tsx +++ /dev/null @@ -1,123 +0,0 @@ -// @ts-nocheck -import { describe, it, expect, jest } from '@jest/globals'; -import { render, screen } from '@testing-library/react'; -import '@testing-library/jest-dom'; - -// ─── Mocks ─────────────────────────────────────────────────────────────── - -jest.mock('framer-motion', () => ({ - motion: { - div: ({ children, initial, animate, variants, whileInView, whileHover, whileTap, viewport, transition, className, ...props }: any) => ( -
- {children} -
- ), - }, - useInView: jest.fn(() => true), - AnimatePresence: ({ children }: any) => <>{children}, -})); - -// ─── Mock Data ──────────────────────────────────────────────────────────── - -const mockCase = { - industry: '制造业', - title: '某制造企业数字化转型', - challenge: '库存管理混乱,信息孤岛严重,生产流程不透明', - solution: '实施ERP系统,打通全业务流程,实现数据驱动决策', - impact: [ - { value: '200%', label: '库存周转率提升' }, - { value: '50%', label: '运营成本降低' }, - ], - quote: '数字化转型让我们的生产效率大幅提升', - author: '张总 / 某制造企业CEO', - image: '/images/cases/manufacturing.jpg', -}; - -// ─── Tests ─────────────────────────────────────────────────────────────── - -describe('CaseCard', () => { - it('should render industry tag and title', async () => { - const { CaseCard } = await import('./case-card'); - render(); - expect(screen.getByText('制造业')).toBeInTheDocument(); - expect(screen.getByText('某制造企业数字化转型')).toBeInTheDocument(); - }); - - it('should render challenge and solution', async () => { - const { CaseCard } = await import('./case-card'); - render(); - expect(screen.getByText('挑战')).toBeInTheDocument(); - expect(screen.getByText('方案')).toBeInTheDocument(); - expect(screen.getByText('库存管理混乱,信息孤岛严重,生产流程不透明')).toBeInTheDocument(); - expect(screen.getByText('实施ERP系统,打通全业务流程,实现数据驱动决策')).toBeInTheDocument(); - }); - - it('should render impact metrics', async () => { - const { CaseCard } = await import('./case-card'); - render(); - expect(screen.getByText('200%')).toBeInTheDocument(); - expect(screen.getByText('库存周转率提升')).toBeInTheDocument(); - expect(screen.getByText('50%')).toBeInTheDocument(); - expect(screen.getByText('运营成本降低')).toBeInTheDocument(); - }); - - it('should render quote and author', async () => { - const { CaseCard } = await import('./case-card'); - render(); - expect(screen.getByText(/数字化转型让我们的生产效率大幅提升/)).toBeInTheDocument(); - expect(screen.getByText('张总 / 某制造企业CEO')).toBeInTheDocument(); - }); - - it('should render background image when provided', async () => { - const { CaseCard } = await import('./case-card'); - const { container } = render(); - // 组件用 CSS 背景图而非 ,使 404 图片静默降级为纯色底 - const bg = container.querySelector('[style*="background-image"]'); - expect(bg).toBeInTheDocument(); - expect(bg).toHaveAttribute('aria-hidden', 'true'); - expect(bg).toHaveStyle({ backgroundImage: 'url(/images/cases/manufacturing.jpg)' }); - }); - - it('should not render background image when not provided', async () => { - const { CaseCard } = await import('./case-card'); - const { container } = render(); - const bg = container.querySelector('[style*="background-image"]'); - expect(bg).not.toBeInTheDocument(); - }); - - it('should use context as fallback when challenge is empty', async () => { - const { CaseCard } = await import('./case-card'); - render( - - ); - expect(screen.getByText('后备上下文')).toBeInTheDocument(); - }); - - it('should apply custom className', async () => { - const { CaseCard } = await import('./case-card'); - const { container } = render(); - const outer = container.querySelector('.custom-class'); - expect(outer).toBeInTheDocument(); - }); -}); \ No newline at end of file diff --git a/src/components/sections/case-card.tsx b/src/components/sections/case-card.tsx deleted file mode 100644 index d813950..0000000 --- a/src/components/sections/case-card.tsx +++ /dev/null @@ -1,127 +0,0 @@ -'use client'; - -interface CaseImpact { - value: string; - label: string; -} - -interface CaseCardProps { - /** Industry label (e.g. "制造业") */ - industry: string; - /** Case title */ - title: string; - /** Challenge the client faced (Bain-style) */ - challenge: string; - /** Solution we provided (Bain-style) */ - solution: string; - /** @deprecated Use challenge + solution instead */ - context?: string; - /** Quantified impact metrics (2 items) */ - impact: CaseImpact[]; - /** Client quote */ - quote: string; - /** Client name/title */ - author: string; - /** Optional background image URL */ - image?: string; - className?: string; -} - -export function CaseCard({ - industry, - title, - challenge, - solution, - context, - impact, - quote, - author, - image, - className = '', -}: CaseCardProps) { - const displayChallenge = challenge || context || ''; - const displaySolution = solution || ''; - - return ( -
- {/* Background image */} - {image && ( - - ); -} diff --git a/src/components/sections/challenge-section.tsx b/src/components/sections/challenge-section.tsx deleted file mode 100644 index 0f15b06..0000000 --- a/src/components/sections/challenge-section.tsx +++ /dev/null @@ -1,74 +0,0 @@ -'use client'; - -import { motion } from 'framer-motion'; -import { ChallengeCard } from '@/components/ui/challenge-card'; -import { GeometricDecoration } from '@/components/ui/brand-visuals'; -import { useReducedMotion } from '@/hooks/use-reduced-motion'; - -const CHALLENGES = [ - { - id: 'data-isolation', - title: '数据孤岛', - description: '各部门系统独立运行,数据无法互通共享,导致决策信息碎片化,影响整体运营效率。', - scenario: 'isolation' as const, - href: '/solutions#consulting', - }, - { - id: 'growth-bottleneck', - title: '增长瓶颈', - description: '业务规模扩大但管理手段滞后,流程效率低下,难以支撑持续增长的业务需求。', - scenario: 'growth' as const, - href: '/solutions#tech', - }, - { - id: 'compliance-risk', - title: '合规风险', - description: '行业监管日趋严格,传统手工操作难以满足合规要求,数据安全和审计面临挑战。', - scenario: 'compliance' as const, - href: '/solutions#accompany', - }, -]; - -export function ChallengeSection() { - const shouldReduceMotion = useReducedMotion(); - - return ( -
- -
- -
-
- CHALLENGES -
-
-

- 您的挑战,我们的使命 -

-

- 深入理解企业数字化进程中的核心痛点,提供针对性解决方案 -

- - -
- {CHALLENGES.map((challenge, index) => ( - - ))} -
-
-
- ); -} diff --git a/src/components/sections/cta-section.tsx b/src/components/sections/cta-section.tsx deleted file mode 100644 index ba6c804..0000000 --- a/src/components/sections/cta-section.tsx +++ /dev/null @@ -1,105 +0,0 @@ -'use client'; - -import { useRef } from 'react'; -import { motion } from 'framer-motion'; -import { StaticLink } from '@/components/ui/static-link'; -import { CTA_LABELS } from '@/lib/constants/cta-labels'; -import { Button } from '@/components/ui/button'; -import { BrandStamp } from '@/components/ui/brand-visuals'; -import { ArrowRight, Sparkles, MessageCircle, Clock, ShieldCheck } from 'lucide-react'; -import { useReducedMotion } from '@/hooks/use-reduced-motion'; - -interface CTASectionProps { - title?: string; - description?: string; - primaryLabel?: string; - primaryHref?: string; - secondaryLabel?: string; - secondaryHref?: string; -} - -export function CTASection({ - title = '一起聊聊您的数字化需求', - description = `无论您处于数字化转型的哪个阶段,我们都愿意坐下来一起想办法。首次咨询免费,无任何销售压力。`, - primaryLabel = CTA_LABELS.consult, - primaryHref = '/contact', - secondaryLabel = '了解我们的方法', - secondaryHref = '/team', -}: CTASectionProps) { - const shouldReduceMotion = useReducedMotion(); - const containerRef = useRef(null); - - return ( -
-
- -
- 值得信赖 -
- - - 开始对话 - - -

- {title} -

-

- {description} -

- -
-
- - 免费咨询 -
-
- - 30 分钟内响应 -
-
- - 无销售压力 -
-
- -
- - -
-
-
-
- ); -} diff --git a/src/components/sections/hero-particle-field-engine.test.tsx b/src/components/sections/hero-particle-field-engine.test.tsx deleted file mode 100644 index 18f3e84..0000000 --- a/src/components/sections/hero-particle-field-engine.test.tsx +++ /dev/null @@ -1,507 +0,0 @@ -import { describe, it, expect, jest, beforeEach, afterEach } from '@jest/globals'; -import { render, screen } from '@testing-library/react'; -import '@testing-library/jest-dom'; -import HeroParticleField, { type HeroVariant } from './hero-particle-field'; - -// ─── Mocks ─────────────────────────────────────────────────────────────── -// 本文件负责粒子引擎(绘制分支 / 出界回绕 / 启停),不做快照比对, -// 因此把 canvas 2d 上下文换成可回放的记录器:jsdom 无 canvas 实现, -// 不打桩的话 useEffect 会在 getContext('2d') 处提前 return(见 hero-particle-field.tsx:107)。 -jest.mock('@/hooks/use-reduced-motion', () => ({ - useReducedMotion: jest.fn(() => false), -})); - -type Call = { op: string; args: unknown[] }; -type StyleWrite = { prop: string; value: string }; -interface CtxStub { - calls: Call[]; - styles: StyleWrite[]; - gradients: { addColorStop: jest.Mock }[]; -} - -function createCtxStub() { - const calls: Call[] = []; - const styles: StyleWrite[] = []; - const gradients: { addColorStop: jest.Mock }[] = []; - const record = (op: string) => - jest.fn((...args: unknown[]) => { - calls.push({ op, args }); - }); - const stub: Record = { - calls, - styles, - gradients, - setTransform: record('setTransform'), - clearRect: record('clearRect'), - beginPath: record('beginPath'), - moveTo: record('moveTo'), - lineTo: record('lineTo'), - stroke: record('stroke'), - arc: record('arc'), - fill: record('fill'), - createLinearGradient: jest.fn(() => { - const g = { addColorStop: jest.fn() }; - gradients.push(g); - return g; - }), - }; - for (const prop of ['lineWidth', 'globalAlpha', 'shadowColor', 'shadowBlur', 'strokeStyle', 'fillStyle']) { - let value: unknown = ''; - Object.defineProperty(stub, prop, { - configurable: true, - get: () => value, - set: (next: unknown) => { - value = next; - styles.push({ prop, value: String(next) }); - }, - }); - } - return stub as unknown as CanvasRenderingContext2D & CtxStub; -} - -// ─── 环境夹具 ──────────────────────────────────────────────────────────── - -const VIEWPORT = { width: 1200, height: 700 }; -const originalWebdriver = navigator.webdriver; -let ctxStub: CanvasRenderingContext2D & CtxStub; -let getCtxSpy: jest.SpiedFunction; -let rectSpy: jest.SpiedFunction; -let frameQueue: Array<(t: number) => void>; -let rafSpy: jest.SpiedFunction; -let cafSpy: jest.SpiedFunction; - -/** jsdom 里 navigator.webdriver 默认为 true → 引擎走静态降级;本夹具默认要的是可动画环境 */ -function setWebdriver(value: boolean) { - Object.defineProperty(navigator, 'webdriver', { configurable: true, get: () => value }); -} - -function setReduceMotion(value: boolean) { - const { useReducedMotion } = require('@/hooks/use-reduced-motion'); - (useReducedMotion as jest.Mock).mockReturnValue(value); -} - -function setViewport(size: { width: number; height: number }) { - rectSpy.mockReturnValue({ - ...size, - top: 0, - left: 0, - right: size.width, - bottom: size.height, - x: 0, - y: 0, - toJSON: () => ({}), - } as DOMRect); -} - -/** 画布「可见尺寸」决定回绕边界,与 build() 用的父容器矩形分离,便于构造出界场景 */ -function setCanvasClientBox(width: number, height: number) { - Object.defineProperty(HTMLCanvasElement.prototype, 'clientWidth', { configurable: true, get: () => width }); - Object.defineProperty(HTMLCanvasElement.prototype, 'clientHeight', { configurable: true, get: () => height }); -} - -function arcPositions(since = 0): { x: number; y: number }[] { - return ctxStub.calls - .slice(since) - .filter((c) => c.op === 'arc') - .map((c) => ({ x: Number(c.args[0]), y: Number(c.args[1]) })); -} - -function written(prop: string): string[] { - return ctxStub.styles.filter((s) => s.prop === prop).map((s) => s.value); -} - -/** 手动推进 rAF 队列,返回推进的帧数 */ -function runFrames(stamps: number[]): number { - let done = 0; - for (const t of stamps) { - const pending = frameQueue.splice(0, frameQueue.length); - if (pending.length === 0) break; - pending.forEach((cb) => cb(t)); - done += 1; - } - return done; -} - -/** 动画路径下 build() 不直接落笔(paint 只发生在 step 内),推进一帧即可检查绘制结果 */ -function paintOnce() { - expect(runFrames([16])).toBe(1); -} - -beforeEach(() => { - ctxStub = createCtxStub(); - frameQueue = []; - getCtxSpy = jest - .spyOn(HTMLCanvasElement.prototype, 'getContext') - .mockImplementation((() => ctxStub) as never); - rectSpy = jest.spyOn(Element.prototype, 'getBoundingClientRect').mockReturnValue({ - ...VIEWPORT, - top: 0, - left: 0, - right: VIEWPORT.width, - bottom: VIEWPORT.height, - x: 0, - y: 0, - toJSON: () => ({}), - } as DOMRect); - rafSpy = jest - .spyOn(window, 'requestAnimationFrame') - .mockImplementation(((cb: (t: number) => void) => { - frameQueue.push(cb); - return frameQueue.length; - }) as never); - cafSpy = jest.spyOn(window, 'cancelAnimationFrame').mockImplementation((() => undefined) as never); - setWebdriver(false); - setReduceMotion(false); - setCanvasClientBox(VIEWPORT.width, VIEWPORT.height); - document.documentElement.style.removeProperty('--color-brand-rgb'); -}); - -afterEach(() => { - getCtxSpy.mockRestore(); - rectSpy.mockRestore(); - rafSpy.mockRestore(); - cafSpy.mockRestore(); - setWebdriver(originalWebdriver); - Object.defineProperty(HTMLCanvasElement.prototype, 'clientWidth', { configurable: true, get: () => 0 }); - Object.defineProperty(HTMLCanvasElement.prototype, 'clientHeight', { configurable: true, get: () => 0 }); - document.documentElement.style.removeProperty('--color-brand-rgb'); - delete (globalThis as Record).ResizeObserver; -}); - -// ─── 尺寸与密度 ────────────────────────────────────────────────────────── - -describe('HeroParticleField · 画布尺寸与粒子密度', () => { - it('sizes the backing store by devicePixelRatio and caps DPR at 2', () => { - Object.defineProperty(window, 'devicePixelRatio', { configurable: true, get: () => 4 }); - const { unmount } = render(); - const canvas = screen.getByTestId('hero-particle-field') as HTMLCanvasElement; - expect(canvas.width).toBe(VIEWPORT.width * 2); - expect(canvas.height).toBe(VIEWPORT.height * 2); - expect(canvas.style.width).toBe('1200px'); - expect(ctxStub.calls[0]).toEqual({ op: 'setTransform', args: [2, 0, 0, 2, 0, 0] }); - unmount(); - Object.defineProperty(window, 'devicePixelRatio', { configurable: true, get: () => 1 }); - }); - - it('keeps a 1x devicePixelRatio untouched', () => { - Object.defineProperty(window, 'devicePixelRatio', { configurable: true, get: () => 1 }); - render(); - const canvas = screen.getByTestId('hero-particle-field') as HTMLCanvasElement; - expect(canvas.width).toBe(VIEWPORT.width); - expect(ctxStub.calls[0]).toEqual({ op: 'setTransform', args: [1, 0, 0, 1, 0, 0] }); - }); - - it('treats a zero devicePixelRatio as 1 instead of collapsing the canvas', () => { - // 部分宿主在缩放计算前上报 dpr=0:Math.min(0, 2)=0 会把位图缩成 0x0,必须回落到 1 - Object.defineProperty(window, 'devicePixelRatio', { configurable: true, get: () => 0 }); - try { - render(); - const canvas = screen.getByTestId('hero-particle-field') as HTMLCanvasElement; - expect(canvas.width).toBe(VIEWPORT.width); - expect(canvas.style.width).toBe('1200px'); - expect(ctxStub.calls[0]).toEqual({ op: 'setTransform', args: [1, 0, 0, 1, 0, 0] }); - } finally { - Object.defineProperty(window, 'devicePixelRatio', { configurable: true, get: () => 1 }); - } - }); - - it('scales particle count with area', () => { - render(); - paintOnce(); - // 1200x700 / 26000 ≈ 32 - expect(arcPositions()).toHaveLength(32); - }); - - it('caps particle count at 56 on a very large viewport', () => { - setViewport({ width: 4000, height: 4000 }); - render(); - paintOnce(); - expect(arcPositions()).toHaveLength(56); - }); - - it('draws nothing extra when the container has zero area', () => { - setViewport({ width: 0, height: 0 }); - render(); - paintOnce(); - const canvas = screen.getByTestId('hero-particle-field') as HTMLCanvasElement; - // 面积为 0 时不产生粒子,但画布仍保留 1px 下限(避免 canvas 尺寸非法) - expect(canvas.width).toBe(1); - expect(arcPositions()).toHaveLength(0); - expect(written('fillStyle')).toHaveLength(0); - }); -}); - -// ─── 变体绘制 ──────────────────────────────────────────────────────────── - -describe('HeroParticleField · 变体绘制', () => { - const renderVariant = (variant: HeroVariant, dark = false) => { - const view = render(); - paintOnce(); - return view; - }; - - it('drift paints nodes only — no links, no streams, no glow', () => { - renderVariant('drift'); - expect(ctxStub.gradients).toHaveLength(0); - expect(ctxStub.calls.filter((c) => c.op === 'stroke')).toHaveLength(0); - expect(written('shadowColor')).toHaveLength(0); - expect(written('fillStyle').length).toBeGreaterThan(0); - }); - - it('grid draws thin ink links on a light background', () => { - renderVariant('grid'); - expect(written('strokeStyle')).toContain('rgba(10,14,20,1)'); - expect(written('shadowColor')).toHaveLength(0); - }); - - it('network draws white links and brand-red glow only for the bright nodes on dark', () => { - renderVariant('network', true); - expect(written('strokeStyle')).toContain('rgba(255,255,255,1)'); - expect(written('shadowColor')).toContain('rgba(196,30,58,0.9)'); - expect(written('shadowBlur')).toContain('8'); - }); - - it('spotlight combines links with glow', () => { - renderVariant('spotlight', true); - expect(ctxStub.calls.filter((c) => c.op === 'stroke').length).toBeGreaterThan(0); - expect(written('shadowColor')).toContain('rgba(196,30,58,0.9)'); - }); - - it('constellation adds vertical data streams and dim secondary nodes', () => { - renderVariant('constellation', true); - // 16 条竖向数据流,各用一条线性渐变 - expect(ctxStub.gradients).toHaveLength(16); - expect(ctxStub.gradients[0]!.addColorStop).toHaveBeenCalledTimes(3); - const fills = written('fillStyle'); - expect(fills.some((f) => f.startsWith('rgba(180,190,205'))).toBe(true); // 暗白次级节点 - expect(fills.some((f) => f.startsWith('rgba(196, 30, 58'))).toBe(true); // 品牌红主节点 - // 次级节点半径收缩到 0.7 倍,且不做 dim 的每 4 个一取的规则会被固定种子复现 - const dimCount = ctxStub.calls.filter((c) => c.op === 'arc').length; - expect(dimCount).toBe(32); - }); - - it('uses the cool-grey dim node on a light constellation too', () => { - renderVariant('constellation', false); - expect(written('fillStyle').some((f) => f.startsWith('rgba(100,116,139'))).toBe(true); - expect(written('shadowColor')).toHaveLength(0); // 浅底不辉光 - }); - - it('re-derives the variant when the prop changes', () => { - const { rerender } = render(); - paintOnce(); - expect(ctxStub.gradients).toHaveLength(0); - const before = ctxStub.calls.length; - rerender(); - paintOnce(); - expect(screen.getByTestId('hero-particle-field')).toHaveAttribute('data-variant', 'constellation'); - expect(ctxStub.calls.length).toBeGreaterThan(before); - expect(ctxStub.gradients).toHaveLength(16); - }); -}); - -// ─── 品牌色读取 ────────────────────────────────────────────────────────── - -describe('HeroParticleField · 品牌红取值', () => { - it('reads --color-brand-rgb from the document root', () => { - document.documentElement.style.setProperty('--color-brand-rgb', '12 200 40'); - render(); - paintOnce(); - expect(written('fillStyle')[0]).toContain('rgba(12, 200, 40,'); - }); - - it.each([ - ['malformed tokens', 'a b c'], - ['a partial triple', '12 34'], - ])('falls back to the literal brand red for %s', (_label, raw) => { - document.documentElement.style.setProperty('--color-brand-rgb', raw); - render(); - paintOnce(); - expect(written('fillStyle')[0]).toContain('rgba(196, 30, 58,'); - }); - - it('falls back when the token is not declared at all', () => { - render(); - paintOnce(); - expect(written('fillStyle')[0]).toContain('rgba(196, 30, 58,'); - }); -}); - -// ─── 动画循环 ──────────────────────────────────────────────────────────── - -describe('HeroParticleField · 循环与降级', () => { - it('drives a continuous rAF loop that keeps every node inside the wrap box', () => { - setCanvasClientBox(8, 8); // 视口远小于初始分布 → 第一帧即触发回绕 - render(); - expect(rafSpy).toHaveBeenCalledTimes(1); - const frames = runFrames([16, 32, 48, 64, 96, 120, 160, 200]); - expect(frames).toBeGreaterThan(1); - - const positions = arcPositions(); - const xs = positions.map((p) => p.x); - const ys = positions.map((p) => p.y); - expect(positions.length).toBe(32 * frames); - expect(Math.min(...xs)).toBeGreaterThanOrEqual(-3); - expect(Math.max(...xs)).toBeLessThanOrEqual(11); - expect(Math.min(...ys)).toBeGreaterThanOrEqual(-3); - expect(Math.max(...ys)).toBeLessThanOrEqual(11); - // 两个方向都真的发生了回绕:右出界 → 左侧 -3 入场,左出界 → 右侧 w+3 入场 - expect(xs).toContain(-3); - expect(xs).toContain(11); - expect(ys).toContain(-3); - expect(ys).toContain(11); - }); - - it('falls back to the backing-store box while the canvas has no layout size', () => { - // 首帧尚未排版时 clientWidth/Height 会是 0:回绕与淡出必须改用位图尺寸,而不是被 0x0 挤到边界 - setCanvasClientBox(0, 0); - render(); - paintOnce(); - const positions = arcPositions(); - const xs = positions.map((p) => p.x); - const ys = positions.map((p) => p.y); - expect(positions).toHaveLength(32); - expect(Math.max(...xs) - Math.min(...xs)).toBeGreaterThan(600); - expect(Math.max(...ys) - Math.min(...ys)).toBeGreaterThan(300); - expect(Math.max(...xs)).toBeLessThanOrEqual(VIEWPORT.width + 3); - expect(Math.max(...ys)).toBeLessThanOrEqual(VIEWPORT.height + 3); - }); - - it('cancels the scheduled frame on unmount', () => { - const { unmount } = render(); - runFrames([16]); - unmount(); - expect(cafSpy).toHaveBeenCalled(); - }); - - it('paints a single static frame and never schedules rAF under reduced motion', () => { - setReduceMotion(true); - render(); - expect(rafSpy).not.toHaveBeenCalled(); - expect(ctxStub.calls.filter((c) => c.op === 'fill')).toHaveLength(32); - setReduceMotion(false); - }); - - it('paints a single static frame in automated browsers (navigator.webdriver)', () => { - setWebdriver(true); - render(); - expect(rafSpy).not.toHaveBeenCalled(); - expect(arcPositions()).toHaveLength(32); - // 静态帧仍要落笔:边缘淡出后的透明度写入了 fillStyle - expect(written('fillStyle').length).toBeGreaterThan(0); - }); - - it('degrades to a static frame when requestAnimationFrame is unavailable', () => { - const savedRaf = window.requestAnimationFrame; - // @ts-expect-error 运行期删除,模拟无 rAF 的老宿主 - delete window.requestAnimationFrame; - try { - render(); - expect(arcPositions()).toHaveLength(32); - expect(rafSpy).not.toHaveBeenCalled(); - } finally { - // `writable` 必须显式给出:defineProperty 的默认值是 false,缺省会把它变成只读属性, - // 随后 afterEach 里 rafSpy.mockRestore() 的赋值就会抛 - // "Cannot assign to read only property 'requestAnimationFrame'",整套件判为 failed to run。 - Object.defineProperty(window, 'requestAnimationFrame', { - configurable: true, - writable: true, - value: savedRaf, - }); - } - }); - - it('stops when the tab is hidden and restarts when it becomes visible', () => { - render(); - const rafCallsBefore = rafSpy.mock.calls.length; - const visibility = Object.getOwnPropertyDescriptor(Document.prototype, 'visibilityState') - ?? Object.getOwnPropertyDescriptor(document, 'visibilityState'); - Object.defineProperty(document, 'visibilityState', { configurable: true, get: () => 'hidden' }); - document.dispatchEvent(new Event('visibilitychange')); - expect(cafSpy).toHaveBeenCalled(); - expect(rafSpy.mock.calls.length).toBe(rafCallsBefore); - - Object.defineProperty(document, 'visibilityState', { configurable: true, get: () => 'visible' }); - document.dispatchEvent(new Event('visibilitychange')); - expect(rafSpy.mock.calls.length).toBeGreaterThan(rafCallsBefore); - if (visibility) Object.defineProperty(document, 'visibilityState', visibility); - }); - - it('still runs the loop on hosts without IntersectionObserver and unmounts cleanly', () => { - // 老宿主缺 IO:引擎要直接按挂载即起跑,卸载时的 io?.disconnect() 也不能抛错 - const savedIO = (globalThis as Record).IntersectionObserver; - delete (globalThis as Record).IntersectionObserver; - try { - const { unmount } = render(); - expect(rafSpy).toHaveBeenCalledTimes(1); - paintOnce(); - expect(arcPositions()).toHaveLength(32); - expect(() => unmount()).not.toThrow(); - expect(cafSpy).toHaveBeenCalled(); - } finally { - (globalThis as Record).IntersectionObserver = savedIO; - } - }); - - it('rebuilds and repaints through ResizeObserver when the host provides one', () => { - const observers: Array<{ cb: () => void; targets: Element[]; disconnected: boolean }> = []; - class MockResizeObserver { - cb: () => void; - targets: Element[] = []; - disconnected = false; - constructor(cb: () => void) { - this.cb = cb; - observers.push(this); - } - observe(el: Element) { - this.targets.push(el); - } - unobserve() {} - disconnect() { - this.disconnected = true; - } - } - (globalThis as Record).ResizeObserver = MockResizeObserver; - - render(); - const canvas = screen.getByTestId('hero-particle-field') as HTMLCanvasElement; - expect(canvas.width).toBe(1200); - const observer = observers[0]; - expect(observer?.targets).toHaveLength(1); - - setViewport({ width: 800, height: 600 }); - observer!.cb(); - // 重建:位图尺寸与变换矩阵按新容器重排(800x600 / 26000 ≈ 18 个粒子) - expect(canvas.width).toBe(800); - expect(canvas.height).toBe(600); - expect(ctxStub.calls.filter((c) => c.op === 'setTransform')).toHaveLength(2); - runFrames([16]); - expect(arcPositions()).toHaveLength(18); - }); - - it('disconnects the observers on unmount', () => { - const observers: Array<{ disconnected: boolean }> = []; - class MockResizeObserver { - disconnected = false; - constructor(cb: () => void) { - void cb; - observers.push(this); - } - observe() {} - unobserve() {} - disconnect() { - this.disconnected = true; - } - } - (globalThis as Record).ResizeObserver = MockResizeObserver; - const { unmount } = render(); - unmount(); - expect(observers[0]?.disconnected).toBe(true); - }); - - it('appends a custom class to the canvas layer', () => { - render(); - const canvas = screen.getByTestId('hero-particle-field'); - expect(canvas.className).toContain('hero-overlay'); - expect(canvas.className).toContain('pointer-events-none'); - }); -}); diff --git a/src/components/sections/hero-particle-field.test.tsx b/src/components/sections/hero-particle-field.test.tsx deleted file mode 100644 index daf5f9c..0000000 --- a/src/components/sections/hero-particle-field.test.tsx +++ /dev/null @@ -1,79 +0,0 @@ -import { describe, it, expect, jest } from '@jest/globals'; -import { render, screen } from '@testing-library/react'; -import '@testing-library/jest-dom'; -import HeroParticleField from './hero-particle-field'; - -jest.mock('@/hooks/use-reduced-motion', () => ({ - useReducedMotion: jest.fn(() => false), -})); - -describe('HeroParticleField - 动态粒子层(循环漂移动画)', () => { - it('renders an aria-hidden, non-interactive canvas layer', () => { - render(); - const canvas = screen.getByTestId('hero-particle-field'); - expect(canvas.tagName).toBe('CANVAS'); - expect(canvas).toHaveAttribute('aria-hidden', 'true'); - expect(canvas.className).toContain('pointer-events-none'); - }); - - it('does not throw under reduced motion (degrades to a single static frame)', () => { - const { useReducedMotion } = require('@/hooks/use-reduced-motion'); - (useReducedMotion as jest.Mock).mockReturnValue(true); - expect(() => render()).not.toThrow(); - // 静态降级下仍渲染 canvas(无 rAF 循环,仅一次绘制) - expect(screen.getByTestId('hero-particle-field').tagName).toBe('CANVAS'); - }); - - it('bails safely when no 2d context is available (jsdom / SSR guard)', () => { - const ctxSpy = jest - .spyOn(HTMLCanvasElement.prototype, 'getContext') - .mockReturnValue(null as any); - expect(() => render()).not.toThrow(); - ctxSpy.mockRestore(); - }); - - it('starts a continuous rAF loop and stops it on unmount when animation is allowed', () => { - // 重置被前置用例 mockReturnValue(true) 污染的共享 mock,确保本用例走动画路径 - const { useReducedMotion: urm } = require('@/hooks/use-reduced-motion'); - (urm as jest.Mock).mockReturnValue(false); - - const ctxStub = { - setTransform: jest.fn(), - clearRect: jest.fn(), - beginPath: jest.fn(), - arc: jest.fn(), - fill: jest.fn(), - fillStyle: '', - }; - const getCtxSpy = jest - .spyOn(HTMLCanvasElement.prototype, 'getContext') - .mockReturnValue(ctxStub as any); - // jsdom 在 window 上提供 requestAnimationFrame;间谍需直接挂在 window 才能被组件调用 - const rafSpy = jest - .spyOn(window, 'requestAnimationFrame') - .mockImplementation(() => 1 as unknown as number); - const cafSpy = jest - .spyOn(window, 'cancelAnimationFrame') - .mockImplementation(() => undefined); - // 强制非自动化环境,确保走动画路径(而非 navigator.webdriver 静态降级) - try { - Object.defineProperty(navigator, 'webdriver', { - configurable: true, - get: () => false, - }); - } catch { - /* navigator.webdriver 不可重定义时忽略,依赖 rAF 间谍仍应触发循环 */ - } - - const { unmount } = render(); - // 动画路径:应已调度 rAF(持续循环起点),且 navigator.webdriver 未触发静态降级 - expect(rafSpy).toHaveBeenCalled(); - - unmount(); - expect(cafSpy).toHaveBeenCalled(); - - getCtxSpy.mockRestore(); - rafSpy.mockRestore(); - cafSpy.mockRestore(); - }); -}); diff --git a/src/components/sections/hero-particle-field.tsx b/src/components/sections/hero-particle-field.tsx deleted file mode 100644 index 9dc52ba..0000000 --- a/src/components/sections/hero-particle-field.tsx +++ /dev/null @@ -1,325 +0,0 @@ -'use client'; - -/** - * Hero 动态粒子层(循环漂移动画 + 科技感变体) - * - * 设计约束对齐(CLAUDE.md / CONTEXT.md / Impeccable 审计): - * - 循环动画(用户特批豁免「无持续循环」铁律):rAF 持续漂移,离屏/隐藏标签页即停。 - * - 品牌红单电压:粒子用 --color-brand-rgb(#C41E3A),稀疏小点(封顶 56、半径 ≤2.6px), - * 品牌红面积占比 <0.1%,远低于单电压 10% 上限,不作为大背景。 - * - reduced-motion:直接绘制一次静态帧,不进入 rAF 循环。 - * - 自动化环境稳定:navigator.webdriver 为真(Playwright 默认)时同样降级为静态帧, - * 且位置由固定种子 mulberry32 复现——与改动前「入场后静止」的冻结帧像素一致, - * 因此视觉回归快照基线不发生漂移(连线/星图位置同样由固定种子复现)。 - * - 性能:DPR 限幅(≤2)、粒子数随面积封顶、离屏/隐藏即停、ResizeObserver 重排。 - * - 无特效库:纯自包含 canvas,不引入任何第三方动画/粒子依赖(effects/ 已删除)。 - * - * 变体(variant prop,默认 'drift' 兼容旧调用): - * - 'drift' 仅品牌红小点漂移(原行为,浅色 Hero 用) - * - 'grid' 浅色科技感:墨色细连线 + 品牌红节点(网格由 HeroSection 的 CSS 层承担) - * - 'network' 品牌红节点 + 邻近中性灰连线(深色 Hero 默认,科技感最强) - * - 'constellation' 品牌红脉冲节点 + 暗白次级点 + 极淡竖向数据流(NovaVis 看板语义) - * - 'spotlight' 同 network + 工程网格 + 品牌红光标聚光(纵深最强) - * 连线/辉光仅作用于深色底(dark=true);浅色变体用墨色细线。 - */ - -import { useEffect, useRef } from 'react'; -import { useReducedMotion } from '@/hooks/use-reduced-motion'; - -const MAX_DPR = 2; -const MAX_PARTICLES = 56; -const DENSITY_DIVISOR = 26000; // 每 ~26000px² 一个粒子,面积驱动密度封顶 -const SEED = 0x9e3779b9; // 固定种子 → 初始位置可复现(快照稳定) -const BASE_SPEED = 0.25; // px / 16ms,极缓漂移 -const LINK_DIST = 150; // 连线触发距离 - -export type HeroVariant = 'drift' | 'network' | 'grid' | 'constellation' | 'spotlight'; - -interface VariantConfig { - links: boolean; // 邻近粒子连线 - glow: boolean; // 品牌红节点辉光(仅深底生效) - dim: boolean; // 暗白次级节点(星图) - streams: boolean; // 竖向数据流 -} - -const VARIANT_CONFIG: Record = { - drift: { links: false, glow: false, dim: false, streams: false }, - // grid:浅色科技感变体 —— 墨色细连线 + 品牌红节点(工程网格由 HeroSection 的 CSS 层承担) - grid: { links: true, glow: false, dim: false, streams: false }, - network: { links: true, glow: true, dim: false, streams: false }, - constellation: { links: false, glow: true, dim: true, streams: true }, - spotlight: { links: true, glow: true, dim: false, streams: false }, -}; - -interface Particle { - x: number; - y: number; - vx: number; - vy: number; - r: number; - alpha: number; - dim: boolean; -} - -function readBrandRgb(): [number, number, number] { - if (typeof window === 'undefined') return [196, 30, 58]; - const raw = getComputedStyle(document.documentElement) - .getPropertyValue('--color-brand-rgb') - .trim(); - if (raw) { - const parts = raw.split(/\s+/).map(Number); - if (parts.length === 3 && parts.every((n) => !Number.isNaN(n))) { - const [r, g, b] = parts as [number, number, number]; - return [r, g, b]; - } - } - return [196, 30, 58]; -} - -/** 固定种子 PRNG(mulberry32):让粒子位置对给定视口可复现,避免视觉回归快照 flaky */ -function mulberry32(seed: number): () => number { - let s = seed; - return function () { - s |= 0; - s = (s + 0x6d2b79f5) | 0; - let t = Math.imul(s ^ (s >>> 15), 1 | s); - t = (t + Math.imul(t ^ (t >>> 7), 61 | t)) ^ t; - return ((t ^ (t >>> 14)) >>> 0) / 4294967296; - }; -} - -export function HeroParticleField({ - variant = 'drift', - dark = false, - className, -}: { - variant?: HeroVariant; - dark?: boolean; - className?: string; -}) { - const canvasRef = useRef(null); - const reduceMotion = useReducedMotion(); - - useEffect(() => { - const canvas = canvasRef.current; - if (!canvas) return; - const ctx = canvas.getContext('2d'); - if (!ctx) return; // jsdom / SSR / 无 2d 上下文:安全退出,不绘制 - const parent = canvas.parentElement; - if (!parent) return; - - // 变体配置在 effect 内派生:随 variant 重建(VARIANT_CONFIG 为模块级常量,无需入依赖数组) - const cfg = VARIANT_CONFIG[variant]; - - const brand = readBrandRgb(); - let particles: Particle[] = []; - let raf = 0; - let last = 0; - let running = false; - const hasRaf = typeof requestAnimationFrame === 'function'; - // Playwright 默认将 navigator.webdriver 置 true → 降级静态帧,保证快照稳定 - const isAutomation = - typeof navigator !== 'undefined' && - (navigator as unknown as { webdriver?: boolean }).webdriver === true; - - const paint = () => { - // 透明画布:仅绘制粒子层,背景由 section 承载(支持深色/浅色 Hero 切换) - ctx.clearRect(0, 0, canvas.width, canvas.height); - const w = canvas.clientWidth || canvas.width; - const h = canvas.clientHeight || canvas.height; - // 边缘径向淡出:中心可见、四角收敛(确定性 —— 仅依赖固定种子位置 + 视口尺寸,快照零漂移) - const maxR = Math.max(1, Math.hypot(w / 2, h / 2)); - const fade = (x: number, y: number) => { - const d = Math.hypot(x - w / 2, y - h / 2) / maxR; - return 0.2 + 0.8 * Math.max(0, 1 - d); - }; - - // 竖向数据流(constellation):固定种子复现 x 位置 → 静态降级像素稳定 - if (cfg.streams) { - const srng = mulberry32(SEED ^ 0x55); - ctx.lineWidth = 1; - for (let i = 0; i < 16; i++) { - const x = srng() * w; - const g = ctx.createLinearGradient(0, 0, 0, h); - g.addColorStop(0, 'rgba(196,30,58,0)'); - g.addColorStop(0.5, 'rgba(196,30,58,0.06)'); - g.addColorStop(1, 'rgba(196,30,58,0)'); - ctx.strokeStyle = g; - ctx.beginPath(); - ctx.moveTo(x, 0); - ctx.lineTo(x, h); - ctx.stroke(); - } - } - - // 邻近连线(network / spotlight):中性灰(深底)或墨色(浅底),不抢品牌红 - if (cfg.links && particles.length) { - ctx.lineWidth = 1; - for (let i = 0; i < particles.length; i++) { - const a = particles[i]; - if (!a) continue; // noUncheckedIndexedAccess 收窄(不用非空断言,避免 lint 告警) - for (let j = i + 1; j < particles.length; j++) { - const b = particles[j]; - if (!b) continue; - const dx = a.x - b.x; - const dy = a.y - b.y; - const d = Math.hypot(dx, dy); - if (d < LINK_DIST) { - ctx.strokeStyle = dark ? 'rgba(255,255,255,1)' : 'rgba(10,14,20,1)'; - // 浅底连线更克制:上限 0.42(原 0.7)+ 边缘径向淡出,避免「图纸过密」 - ctx.globalAlpha = (1 - d / LINK_DIST) * 0.42 * fade((a.x + b.x) / 2, (a.y + b.y) / 2); - ctx.beginPath(); - ctx.moveTo(a.x, a.y); - ctx.lineTo(b.x, b.y); - ctx.stroke(); - } - } - } - ctx.globalAlpha = 1; - } - - // 粒子节点 - for (const p of particles) { - if (dark && cfg.glow && !p.dim) { - ctx.shadowColor = 'rgba(196,30,58,0.9)'; - ctx.shadowBlur = 8; - } else { - ctx.shadowBlur = 0; - } - // 边缘径向淡出同样作用于节点,使视线聚焦版心 - const na = (p.dim ? (dark ? 0.4 : 0.5) : p.alpha) * fade(p.x, p.y); - ctx.fillStyle = p.dim - ? `rgba(${dark ? '180,190,205' : '100,116,139'}, ${na})` - : `rgba(${brand[0]}, ${brand[1]}, ${brand[2]}, ${na})`; - ctx.beginPath(); - ctx.arc(p.x, p.y, p.dim ? p.r * 0.7 : p.r, 0, Math.PI * 2); - ctx.fill(); - } - ctx.shadowBlur = 0; - }; - - const build = () => { - const rect = parent.getBoundingClientRect(); - const dpr = Math.min(window.devicePixelRatio || 1, MAX_DPR); - canvas.width = Math.max(1, Math.floor(rect.width * dpr)); - canvas.height = Math.max(1, Math.floor(rect.height * dpr)); - canvas.style.width = `${rect.width}px`; - canvas.style.height = `${rect.height}px`; - ctx.setTransform(dpr, 0, 0, dpr, 0, 0); - - const area = rect.width * rect.height; - const count = Math.min(MAX_PARTICLES, Math.round(area / DENSITY_DIVISOR)); - const rng = mulberry32(SEED); // 固定种子 → 位置可复现(含 dim 标记不消耗额外 rng) - particles = Array.from({ length: Math.max(0, count) }, (_, i) => { - const ang = rng() * Math.PI * 2; - const sp = BASE_SPEED * (0.5 + rng()); - return { - x: rng() * rect.width, - y: rng() * rect.height, - vx: Math.cos(ang) * sp, - vy: Math.sin(ang) * sp, - r: 0.8 + rng() * 1.8, - alpha: 0.35 + rng() * 0.5, - // dim 次级节点:确定性派生(不消耗 rng),保证各变体粒子位置一致 - dim: cfg.dim && i % 4 === 1, - }; - }); - }; - - // 单帧推进:dt 归一化到 ~60fps,出界回绕(toroidal wrap) - const step = (now: number) => { - const dt = last ? Math.min(48, now - last) : 16.67; - last = now; - const k = dt / 16.67; - const w = canvas.clientWidth || canvas.width; - const h = canvas.clientHeight || canvas.height; - for (const p of particles) { - p.x += p.vx * k; - p.y += p.vy * k; - if (p.x < -3) p.x = w + 3; - else if (p.x > w + 3) p.x = -3; - if (p.y < -3) p.y = h + 3; - else if (p.y > h + 3) p.y = -3; - } - paint(); - if (running && hasRaf) raf = requestAnimationFrame(step); - }; - - const start = () => { - if (running || !hasRaf) return; - running = true; - last = 0; - raf = requestAnimationFrame(step); - }; - const stop = () => { - running = false; - if (raf) { - cancelAnimationFrame(raf); - raf = 0; - } - }; - - build(); - - // 静态降级:reduced-motion / 自动化环境 / 无 rAF(如 jsdom) - if (reduceMotion || isAutomation || !hasRaf) { - paint(); - } else { - start(); - } - - // 离屏或标签页隐藏即停,回到视口且可见再启动 - let io: IntersectionObserver | undefined; - // 记录是否仍在视口内;onVisibility 须同时满足「可见 + 在视口」才启动, - // 否则滚出视口后切走标签页再切回,会在离屏 canvas 上把 rAF 空转起来(S-8,违背 :271 契约)。 - let intersecting = true; - if (typeof IntersectionObserver !== 'undefined') { - io = new IntersectionObserver( - (entries) => { - const visible = entries.some((e) => e.isIntersecting); - intersecting = visible; - if (visible && document.visibilityState === 'visible' && !reduceMotion && !isAutomation) { - start(); - } else { - stop(); - } - }, - { threshold: 0.01 }, - ); - io.observe(canvas); - } - const onVisibility = () => { - if (document.visibilityState !== 'visible') stop(); - else if (intersecting && !reduceMotion && !isAutomation) start(); - }; - document.addEventListener('visibilitychange', onVisibility); - - let ro: ResizeObserver | undefined; - if (typeof ResizeObserver !== 'undefined') { - ro = new ResizeObserver(() => { - build(); - if (reduceMotion || isAutomation || !hasRaf) paint(); - }); - ro.observe(parent); - } - - return () => { - stop(); - io?.disconnect(); - ro?.disconnect(); - document.removeEventListener('visibilitychange', onVisibility); - }; - }, [reduceMotion, variant, dark]); - - return ( -