fix(qa): 第五轮系统性质量保障缺陷修复 + 单元/集成测试

安全/鉴权:登出清服务端 httpOnly 令牌、登录 IP 限流前置 bcrypt、停用账号
令牌在 6 个内联 role handler 失效、admin/items 存在性 oracle 认证前置、
同意偏好 sanitize fail-closed、api-crypto 按 HTTP 方法判体。

CMS:workflow 状态更新+审计收进交互式 $transaction(失败即回滚)、编辑器
richtext 走 textarea 防换行损毁、array/object 子字段按作用域读写防污染、
about/contact/erp-upgrade 补 ISR revalidate 与路由映射。

UI/a11y:AnimatedCounter 入视口前显起点、CLS 累计上报、MetricCard 动画入
effect 并卸载取消 rAF、后台状态四态映射/搜索防抖+序号守卫/媒体单 input/
吞错改横幅/表单 label-aria 关联。

新增对应判别性单测与 pagination/rate-limit/client-ip/sanitize/validate-content-data
等模块及 tests-integration 真库集成层。
This commit is contained in:
zhangxiang committed 2026-09-28 10:48:07 +08:00
1 parent 040951c0a3
commit a366bd1400
224 files changed
+8938 -5579

No files matched your search

+13 -1
View File
@@ -26,6 +26,18 @@ import {
} from 'lucide-react';
import { ThemeToggle } from '@/components/theme/theme-toggle';
// 令牌的 role claim 有两个来源:login 签发 User.role 标量(取值见 prisma/seed.ts:199,313,324 与
// schema 默认值 'admin'),refresh 则按 UserRole.roleCode 重签(B-7 修复,refresh/route.ts:31)。
// 侧栏必须同时认这两套取值,否则刷新后的 super_admin 会掉进 else 分支显示成「编辑」。
const ROLE_LABELS: Record<string, string> = {
admin: '管理员',
super_admin: '超级管理员',
content_admin: '内容管理员',
content_editor: '内容编辑',
reviewer: '审核员',
readonly: '只读用户',
};
const menuItems = [
{
label: '内容管理',
@@ -238,7 +250,7 @@ export function AdminLayout({ children }: { children: React.ReactNode }) {
<p className="text-sm font-medium text-text-primary truncate">
{user?.nickname || user?.username}
</p>
<p className="text-xs text-text-muted">{user?.role === 'admin' ? '管理员' : '编辑'}</p>
<p className="text-xs text-text-muted">{ROLE_LABELS[user?.role ?? ''] ?? '编辑'}</p>
</div>
<button
onClick={handleLogout}
@@ -0,0 +1,61 @@
import { renderHook, act, waitFor } from '@testing-library/react';
import type { ReactNode } from 'react';
import { AuthProvider, useAuth } from '@/components/admin/auth-context';
const push = jest.fn();
jest.mock('next/navigation', () => ({ useRouter: () => ({ push }) }));
describe('AuthContext.logout', () => {
let fetchMock: jest.Mock;
const wrapper = ({ children }: { children: ReactNode }) => (
<AuthProvider>{children}</AuthProvider>
);
beforeEach(() => {
push.mockClear();
fetchMock = jest.fn().mockResolvedValue({ ok: true, json: async () => ({}) });
global.fetch = fetchMock;
localStorage.setItem('novalon_admin_token', 'tok');
localStorage.setItem(
'novalon_admin_user',
JSON.stringify({ id: '1', username: 'a', nickname: 'A', role: 'x', avatar: '' }),
);
});
afterEach(() => {
localStorage.clear();
});
it('清除服务端 httpOnly cookie(调用 /api/auth/logout)并本地状态与跳转', async () => {
const { result } = renderHook(() => useAuth(), { wrapper });
await waitFor(() => expect(result.current.loading).toBe(false));
act(() => {
result.current.logout();
});
// 关键判据:若不调用 logout 端点,clearTokenCookie 永不触发,
// authenticateRequest 会凭 cookie 在登出后继续放行全站受守卫 API 至多 24h。
expect(fetchMock).toHaveBeenCalledWith(
'/api/auth/logout',
expect.objectContaining({ method: 'POST' }),
);
expect(localStorage.getItem('novalon_admin_token')).toBeNull();
expect(localStorage.getItem('novalon_admin_user')).toBeNull();
expect(push).toHaveBeenCalledWith('/admin/login');
});
it('即使网络失败也清理本地状态并跳转', async () => {
fetchMock.mockRejectedValueOnce(new Error('network down'));
const { result } = renderHook(() => useAuth(), { wrapper });
await waitFor(() => expect(result.current.loading).toBe(false));
await act(async () => {
result.current.logout();
});
expect(localStorage.getItem('novalon_admin_token')).toBeNull();
expect(push).toHaveBeenCalledWith('/admin/login');
});
});
+9
View File
@@ -72,6 +72,15 @@ export function AuthProvider({ children }: { children: ReactNode }) {
}, []);
const logout = useCallback(() => {
// 必须请求 /api/auth/logout 让服务端 clearTokenCookie 下发 Max-Age=0 的 Set-Cookie。
// 登录时 httpOnly 的 novalon_token(24h)/novalon_refresh(7d) 由 login 路由写入,
// 而 authenticateRequest 会回退读取 cookie —— 仅清 localStorage 无法真正登出,
// 受守卫 API 会在登出后仍凭 cookie 放行至多 24h。
try {
fetch('/api/auth/logout', { method: 'POST' }).catch(() => {});
} catch {
// 网络不可用也要继续清理本地并跳转
}
setToken(null);
setUser(null);
localStorage.removeItem('novalon_admin_token');
+10 -9
View File
@@ -1,6 +1,6 @@
'use client';
import { useState, useEffect, useCallback, useRef } from 'react';
import { useState, useEffect, useCallback } from 'react';
import {
updateConsentDetailed,
trackButtonClick,
@@ -36,12 +36,12 @@ export function CookieConsent() {
const [showSettings, setShowSettings] = useState(false);
const [isAnimating, setIsAnimating] = useState(false);
const [preferences, setPreferences] = useState<CookiePreferences>(getDefaultPreferences());
const consentCheckedRef = useRef(false);
// 刻意不加「只跑一次」的 ref 守卫:dev 下 React StrictMode 会 effect → cleanup → effect 连跑两次,
// 第一次的 cleanup 已 clearTimeout;若第二次被守卫拦掉,就没有人再挂 2s 定时器,
// 同意条在 E2E 默认的 dev 目标下永远不渲染 —— 这是 A-12 逃过全部自动化门禁的根因。
// 各分支本身可重入:迁移过的第二次走 stored 分支,只重复一次幂等的 updateConsentDetailed。
useEffect(() => {
if (consentCheckedRef.current) {return;}
consentCheckedRef.current = true;
if (isAdminRoute()) {
hasConsentBeenHandled = true;
return;
@@ -139,6 +139,7 @@ export function CookieConsent() {
exit={{ y: 100, opacity: 0 }}
transition={{ type: 'spring', damping: 25, stiffness: 300 }}
className="fixed bottom-16 md:bottom-0 left-0 right-0 z-[9998] bg-[var(--color-bg-primary)] border-t border-[var(--color-border-secondary)] shadow-lg"
data-testid="cookie-consent-banner"
>
<div className="max-w-7xl mx-auto px-4 py-4 sm:px-6 lg:px-8">
{!showSettings ? (
@@ -149,7 +150,7 @@ export function CookieConsent() {
继续使用即表示您同意我们的{' '}
<a
href="/privacy"
className="text-[var(--color-brand)] hover:text-[var(--color-brand-hover)] underline font-medium"
className="text-brand-ink hover:text-brand-ink-hover underline font-medium"
>
隐私政策
</a>
@@ -201,7 +202,7 @@ export function CookieConsent() {
type="checkbox"
checked
disabled
className="mt-1 h-4 w-4 rounded border-[var(--color-border-secondary)] text-[var(--color-brand)] focus:ring-[var(--color-brand)] cursor-not-allowed"
className="mt-1 h-4 w-4 rounded border-[var(--color-border-secondary)] text-brand-ink focus:ring-[var(--color-brand)] cursor-not-allowed"
aria-label="必要 Cookie"
/>
<div className="flex-1">
@@ -220,7 +221,7 @@ export function CookieConsent() {
type="checkbox"
checked={preferences.analytics}
onChange={() => handleTogglePreference('analytics')}
className="mt-1 h-4 w-4 rounded border-[var(--color-border-secondary)] text-[var(--color-brand)] focus:ring-[var(--color-brand)] cursor-pointer"
className="mt-1 h-4 w-4 rounded border-[var(--color-border-secondary)] text-brand-ink focus:ring-[var(--color-brand)] cursor-pointer"
aria-label="分析 Cookie"
/>
<div className="flex-1">
@@ -236,7 +237,7 @@ export function CookieConsent() {
type="checkbox"
checked={preferences.marketing}
onChange={() => handleTogglePreference('marketing')}
className="mt-1 h-4 w-4 rounded border-[var(--color-border-secondary)] text-[var(--color-brand)] focus:ring-[var(--color-brand)] cursor-pointer"
className="mt-1 h-4 w-4 rounded border-[var(--color-border-secondary)] text-brand-ink focus:ring-[var(--color-brand)] cursor-pointer"
aria-label="营销 Cookie"
/>
<div className="flex-1">
@@ -1,6 +1,6 @@
// @ts-nocheck
import { describe, it, expect, jest, beforeEach } from '@jest/globals';
import { render, act } from '@testing-library/react';
import { render, act, waitFor } from '@testing-library/react';
import '@testing-library/jest-dom';
// Mock useSyncExternalStore to always return true (mounted in browser environment)
@@ -53,6 +53,7 @@ describe('GoogleAnalytics', () => {
delete (window as any).gtag;
mockPathname.mockReturnValue('/');
mockSearchParams.mockReturnValue(new URLSearchParams());
document.title = '';
process.env.NEXT_PUBLIC_GA_MEASUREMENT_ID = 'G-TEST123';
});
@@ -111,7 +112,7 @@ describe('GoogleAnalytics', () => {
expect(gtagMock).not.toHaveBeenCalled();
});
it('should call config only when navigating to a different URL', () => {
it('should call config only when navigating to a different URL', async () => {
setupGtag();
const { GoogleAnalytics } = require('./GoogleAnalytics');
@@ -123,7 +124,7 @@ describe('GoogleAnalytics', () => {
rerender(<GoogleAnalytics />);
});
expect(gtagMock).toHaveBeenCalledTimes(1);
await waitFor(() => expect(gtagMock).toHaveBeenCalledTimes(1));
expect(gtagMock).toHaveBeenCalledWith('config', 'G-TEST123', {
page_path: '/contact',
page_title: document.title,
@@ -131,7 +132,7 @@ describe('GoogleAnalytics', () => {
});
});
it('should include searchParams in navigation page_path', () => {
it('should include searchParams in navigation page_path', async () => {
setupGtag();
const { GoogleAnalytics } = require('./GoogleAnalytics');
@@ -143,12 +144,14 @@ describe('GoogleAnalytics', () => {
rerender(<GoogleAnalytics />);
});
expect(gtagMock).toHaveBeenCalledWith('config', 'G-TEST123', expect.objectContaining({
page_path: '/news?page=2',
}));
await waitFor(() =>
expect(gtagMock).toHaveBeenCalledWith('config', 'G-TEST123', expect.objectContaining({
page_path: '/news?page=2',
}))
);
});
it('should skip duplicate config when URL is unchanged across re-renders', () => {
it('should skip duplicate config when URL is unchanged across re-renders', async () => {
setupGtag();
const { GoogleAnalytics } = require('./GoogleAnalytics');
@@ -158,13 +161,93 @@ describe('GoogleAnalytics', () => {
act(() => {
rerender(<GoogleAnalytics />);
});
expect(gtagMock).toHaveBeenCalledTimes(1);
await waitFor(() => expect(gtagMock).toHaveBeenCalledTimes(1));
act(() => {
rerender(<GoogleAnalytics />);
});
expect(gtagMock).toHaveBeenCalledTimes(1);
});
// 验收 A-17(探针实证):Next.js 在路由 commit 之后才写入 <title>,
// 同步读取 document.title 会把 SPA pageview 的标题发成空串。
it('should read document.title after metadata paints, not during the navigation commit', async () => {
setupGtag();
document.title = '首页 - 睿新致远';
const { GoogleAnalytics } = require('./GoogleAnalytics');
const { rerender } = render(<GoogleAnalytics />);
mockPathname.mockReturnValue('/privacy');
act(() => {
rerender(<GoogleAnalytics />);
});
expect(gtagMock).not.toHaveBeenCalled();
act(() => {
document.title = '隐私政策 - 睿新致远';
});
await waitFor(() =>
expect(gtagMock).toHaveBeenCalledWith('config', 'G-TEST123', expect.objectContaining({
page_path: '/privacy',
page_title: '隐私政策 - 睿新致远',
}))
);
});
// 验收 A-17 复测:真实浏览器里 metadata 不在同一帧落地(chromium-mobile 第 2 帧、
// 桌面第 3–5 帧),只等一帧会把 page_title 发成上一页标题 —— GA4 页面维度被错归属。
it('should keep waiting while the title still belongs to the previous page', async () => {
setupGtag();
document.title = '首页 - 睿新致远';
const { GoogleAnalytics } = require('./GoogleAnalytics');
const { rerender } = render(<GoogleAnalytics />);
mockPathname.mockReturnValue('/privacy');
act(() => {
rerender(<GoogleAnalytics />);
});
const nextFrame = () => new Promise<void>((resolve) => requestAnimationFrame(() => resolve()));
for (let frame = 0; frame < 4; frame += 1) {
await nextFrame();
}
expect(gtagMock).not.toHaveBeenCalled();
act(() => {
document.title = '隐私政策 - 睿新致远';
});
await waitFor(() =>
expect(gtagMock).toHaveBeenCalledWith('config', 'G-TEST123', expect.objectContaining({
page_title: '隐私政策 - 睿新致远',
}))
);
});
// 帧预算只用来「等」,不能吞掉 pageview:两条路由同名时必须在预算耗尽后兜底发出。
it('should still send the pageview when the title never changes', async () => {
setupGtag();
document.title = '固定标题';
const { GoogleAnalytics } = require('./GoogleAnalytics');
const { rerender } = render(<GoogleAnalytics />);
mockPathname.mockReturnValue('/terms');
act(() => {
rerender(<GoogleAnalytics />);
});
await waitFor(() =>
expect(gtagMock).toHaveBeenCalledWith('config', 'G-TEST123', expect.objectContaining({
page_path: '/terms',
page_title: '固定标题',
}))
);
});
});
describe('rendering guards', () => {
+37 -5
View File
@@ -6,6 +6,14 @@ import { useEffect, useRef, Suspense, useSyncExternalStore } from 'react';
const GA_MEASUREMENT_ID = process.env.NEXT_PUBLIC_GA_MEASUREMENT_ID || '';
/**
* SPA pageview 等待 <title> 落地的帧预算。
* 生产实测(e2e TC-GA4-004):Next.js 的 metadata 提交晚于路由 commit,
* chromium-mobile 在第 2 帧、桌面 chromium 在第 3–5 帧才写入新标题,
* 单帧读取会把 page_title 发成上一页标题或空串(污染 GA4 报表的页面维度)。
*/
const MAX_TITLE_SETTLE_FRAMES = 10;
function useIsMounted() {
return useSyncExternalStore(
(callback) => {
@@ -24,6 +32,8 @@ function GoogleAnalyticsContent() {
// null = 尚未导航过:首屏 pageview 由 snippet 内唯一一次 config 发送(GA 用真实 URL)。
// effect 只在「路由变化且 URL 与上次不同」时再发 config,消除复评指出的双 config。
const lastNavigationUrlRef = useRef<string | null>(null);
/** 仍在等标题、尚未发出的上一次 pageview;新导航开始前先补发,避免丢计数 */
const pendingPageViewRef = useRef<(() => void) | null>(null);
useEffect(() => {
if (!GA_MEASUREMENT_ID || !mounted || typeof window === 'undefined') {return;}
@@ -38,11 +48,33 @@ function GoogleAnalyticsContent() {
lastNavigationUrlRef.current = url;
if (window.gtag) {
window.gtag('config', GA_MEASUREMENT_ID, {
page_path: url,
page_title: document.title,
page_location: window.location.origin + url,
});
pendingPageViewRef.current?.();
const titleBeforeNavigation = document.title;
let settled = false;
const send = () => {
if (settled) {return;}
settled = true;
pendingPageViewRef.current = null;
window.gtag?.('config', GA_MEASUREMENT_ID, {
page_path: url,
page_title: document.title,
page_location: window.location.origin + url,
});
};
pendingPageViewRef.current = send;
let framesWaited = 0;
const waitForTitle = () => {
if (settled) {return;}
if (document.title !== titleBeforeNavigation || framesWaited >= MAX_TITLE_SETTLE_FRAMES) {
send();
return;
}
framesWaited += 1;
requestAnimationFrame(waitForTitle);
};
requestAnimationFrame(waitForTitle);
}
}, [pathname, searchParams, mounted]);
@@ -167,6 +167,22 @@ describe('PerformanceTracker', () => {
expect(mockTrackPerformance).toHaveBeenCalledWith('CLS', 150);
});
// S-24:CLS 是会话累计指标。旧实现把累加器放在 observer 回调内,
// 分批到达的 layout-shift 各自只报本批增量,GA 收到的永不是总 CLS。
it('reports cumulative CLS across observer batches, not per-batch deltas', () => {
const { PerformanceTracker } = require('./PerformanceTracker');
render(<PerformanceTracker />);
simulateCLSEntry(0.1);
simulateCLSEntry(0.05);
const clsCalls = mockTrackPerformance.mock.calls.filter((c: unknown[]) => c[0] === 'CLS');
expect(clsCalls).toHaveLength(2);
expect(clsCalls[0][1]).toBeCloseTo(100, 5);
// 第二批上报的是累计值(≈150),而不是本批增量 50
expect(clsCalls[1][1]).toBeCloseTo(150, 5);
});
it('should not track CLS when entry has recent input', () => {
const { PerformanceTracker } = require('./PerformanceTracker');
render(<PerformanceTracker />);
@@ -26,8 +26,10 @@ export function PerformanceTracker() {
}
});
// CLS 是页面会话的累计值:累加器必须在回调外,分批上报每次的总值。
// 旧实现每批从 0 起算,只报本批增量(S-24)。
let clsValue = 0;
const clsObserver = new PerformanceObserver((list) => {
let clsValue = 0;
for (const entry of list.getEntries()) {
if ('value' in entry && !(entry as LayoutShift).hadRecentInput) {
clsValue += (entry as LayoutShift).value;
-314
View File
@@ -1,314 +0,0 @@
import { describe, it, expect, jest, beforeEach } from '@jest/globals';
import { render, screen, fireEvent } from '@testing-library/react';
import { RichTextEditor } from './RichTextEditor';
// ─── Mocks ───────────────────────────────────────────────────────────────
// Mock @tiptap/react
const mockEditor = {
getHTML: jest.fn(() => '<p>test content</p>'),
commands: {
setContent: jest.fn(),
},
chain: jest.fn(() => ({
focus: jest.fn(() => ({
toggleBold: jest.fn(() => ({ run: jest.fn() })),
toggleItalic: jest.fn(() => ({ run: jest.fn() })),
toggleHeading: jest.fn(() => ({ run: jest.fn() })),
toggleBulletList: jest.fn(() => ({ run: jest.fn() })),
toggleOrderedList: jest.fn(() => ({ run: jest.fn() })),
toggleBlockquote: jest.fn(() => ({ run: jest.fn() })),
undo: jest.fn(() => ({ run: jest.fn() })),
redo: jest.fn(() => ({ run: jest.fn() })),
extendMarkRange: jest.fn(() => ({
unsetLink: jest.fn(() => ({ run: jest.fn() })),
setLink: jest.fn(() => ({ run: jest.fn() })),
})),
setLink: jest.fn(() => ({ run: jest.fn() })),
run: jest.fn(),
})),
})),
isActive: jest.fn(() => false),
can: jest.fn(() => ({
undo: jest.fn(() => true),
redo: jest.fn(() => true),
})),
getAttributes: jest.fn(() => ({ href: '' })),
};
jest.mock('@tiptap/react', () => ({
useEditor: jest.fn(() => mockEditor),
EditorContent: (_props: {
editor: typeof mockEditor;
}) => <div data-testid="editor-content" />,
}));
// Mock lucide-react icons
jest.mock('lucide-react', () => {
const mockIcon = (name: string) => {
const Icon = (_props: Record<string, unknown>) => (
<svg data-testid={`icon-${name.toLowerCase()}`} />
);
Icon.displayName = name;
return Icon;
};
return {
Bold: mockIcon('bold'),
Italic: mockIcon('italic'),
Heading2: mockIcon('heading2'),
Heading3: mockIcon('heading3'),
List: mockIcon('list'),
ListOrdered: mockIcon('list-ordered'),
Link: mockIcon('link'),
Quote: mockIcon('quote'),
Undo2: mockIcon('undo2'),
Redo2: mockIcon('redo2'),
};
});
// Mock window.prompt
const mockPrompt = jest.spyOn(window, 'prompt') as jest.Mock;
beforeEach(() => {
jest.clearAllMocks();
mockPrompt.mockReturnValue(null);
});
// ─── Tests ───────────────────────────────────────────────────────────────
describe('RichTextEditor', () => {
describe('Initial State', () => {
it('should render editor content when editor is ready', () => {
render(<RichTextEditor value="" onChange={jest.fn()} />);
expect(screen.getByTestId('editor-content')).toBeInTheDocument();
});
it('should render loading state when editor is null', () => {
// Temporarily make useEditor return null
const useEditorMock = (jest.requireMock('@tiptap/react') as { useEditor: jest.Mock }).useEditor;
useEditorMock.mockReturnValueOnce(null);
render(<RichTextEditor value="" onChange={jest.fn()} />);
expect(screen.getByText('加载编辑器...')).toBeInTheDocument();
});
it('should render toolbar with buttons', () => {
render(<RichTextEditor value="" onChange={jest.fn()} />);
expect(screen.getByTitle('加粗')).toBeInTheDocument();
expect(screen.getByTitle('斜体')).toBeInTheDocument();
expect(screen.getByTitle('标题 2')).toBeInTheDocument();
expect(screen.getByTitle('标题 3')).toBeInTheDocument();
expect(screen.getByTitle('无序列表')).toBeInTheDocument();
expect(screen.getByTitle('有序列表')).toBeInTheDocument();
expect(screen.getByTitle('引用')).toBeInTheDocument();
expect(screen.getByTitle('链接')).toBeInTheDocument();
expect(screen.getByTitle('撤销')).toBeInTheDocument();
expect(screen.getByTitle('重做')).toBeInTheDocument();
});
});
describe('Editor Options', () => {
it('should call useEditor with correct options', () => {
const useEditorMock = (jest.requireMock('@tiptap/react') as { useEditor: jest.Mock }).useEditor;
render(<RichTextEditor value="initial content" onChange={jest.fn()} placeholder="custom placeholder" />);
expect(useEditorMock).toHaveBeenCalledWith(
expect.objectContaining({
content: 'initial content',
extensions: expect.any(Array),
immediatelyRender: false,
})
);
});
it('should use default placeholder when not provided', () => {
const useEditorMock = (jest.requireMock('@tiptap/react') as { useEditor: jest.Mock }).useEditor;
render(<RichTextEditor value="" onChange={jest.fn()} />);
expect(useEditorMock).toHaveBeenCalledWith(
expect.objectContaining({
extensions: expect.any(Array),
})
);
});
});
describe('Toolbar Interactions', () => {
it('should toggle bold on click', () => {
render(<RichTextEditor value="" onChange={jest.fn()} />);
const boldButton = screen.getByTitle('加粗');
fireEvent.click(boldButton);
expect(mockEditor.chain).toHaveBeenCalled();
});
it('should toggle italic on click', () => {
render(<RichTextEditor value="" onChange={jest.fn()} />);
fireEvent.click(screen.getByTitle('斜体'));
expect(mockEditor.chain).toHaveBeenCalled();
});
it('should toggle heading 2 on click', () => {
render(<RichTextEditor value="" onChange={jest.fn()} />);
fireEvent.click(screen.getByTitle('标题 2'));
expect(mockEditor.chain).toHaveBeenCalled();
});
it('should toggle heading 3 on click', () => {
render(<RichTextEditor value="" onChange={jest.fn()} />);
fireEvent.click(screen.getByTitle('标题 3'));
expect(mockEditor.chain).toHaveBeenCalled();
});
it('should toggle bullet list on click', () => {
render(<RichTextEditor value="" onChange={jest.fn()} />);
fireEvent.click(screen.getByTitle('无序列表'));
expect(mockEditor.chain).toHaveBeenCalled();
});
it('should toggle ordered list on click', () => {
render(<RichTextEditor value="" onChange={jest.fn()} />);
fireEvent.click(screen.getByTitle('有序列表'));
expect(mockEditor.chain).toHaveBeenCalled();
});
it('should toggle blockquote on click', () => {
render(<RichTextEditor value="" onChange={jest.fn()} />);
fireEvent.click(screen.getByTitle('引用'));
expect(mockEditor.chain).toHaveBeenCalled();
});
it('should undo on click', () => {
render(<RichTextEditor value="" onChange={jest.fn()} />);
fireEvent.click(screen.getByTitle('撤销'));
expect(mockEditor.chain).toHaveBeenCalled();
});
it('should redo on click', () => {
render(<RichTextEditor value="" onChange={jest.fn()} />);
fireEvent.click(screen.getByTitle('重做'));
expect(mockEditor.chain).toHaveBeenCalled();
});
});
describe('Link Button', () => {
it('should prompt for URL when link button is clicked', () => {
mockPrompt.mockReturnValue('https://example.com');
render(<RichTextEditor value="" onChange={jest.fn()} />);
fireEvent.click(screen.getByTitle('链接'));
expect(mockPrompt).toHaveBeenCalledWith('链接 URL', '');
});
it('should unset link when empty URL is provided', () => {
mockPrompt.mockReturnValue('');
render(<RichTextEditor value="" onChange={jest.fn()} />);
fireEvent.click(screen.getByTitle('链接'));
expect(mockPrompt).toHaveBeenCalledWith('链接 URL', '');
});
it('should not modify link when prompt is cancelled', () => {
mockPrompt.mockReturnValue(null);
render(<RichTextEditor value="" onChange={jest.fn()} />);
fireEvent.click(screen.getByTitle('链接'));
expect(mockPrompt).toHaveBeenCalledWith('链接 URL', '');
});
it('should show existing URL when editing a link', () => {
mockEditor.getAttributes.mockReturnValue({ href: 'https://existing.com' });
render(<RichTextEditor value="" onChange={jest.fn()} />);
fireEvent.click(screen.getByTitle('链接'));
expect(mockPrompt).toHaveBeenCalledWith('链接 URL', 'https://existing.com');
});
});
describe('Content Synchronization', () => {
it('should sync content when value changes externally', () => {
const { rerender } = render(
<RichTextEditor value="initial" onChange={jest.fn()} />
);
rerender(<RichTextEditor value="updated" onChange={jest.fn()} />);
expect(mockEditor.commands.setContent).toHaveBeenCalledWith('updated');
});
it('should not sync content when HTML matches the value', () => {
// The component compares value === editor.getHTML()
// So we need to pass the same HTML string as the mock returns
mockEditor.getHTML.mockReturnValue('<p>same content</p>');
const { rerender } = render(
<RichTextEditor value="<p>same content</p>" onChange={jest.fn()} />
);
rerender(<RichTextEditor value="<p>same content</p>" onChange={jest.fn()} />);
// setContent should not be called when HTML matches the value
expect(mockEditor.commands.setContent).not.toHaveBeenCalled();
});
it('should call onUpdate when editor content changes', () => {
// Simulate the onUpdate callback
const useEditorMock = (jest.requireMock('@tiptap/react') as { useEditor: jest.Mock }).useEditor;
const onChange = jest.fn();
render(<RichTextEditor value="" onChange={onChange} />);
// Get the onUpdate callback from useEditor options
const editorOptions = useEditorMock.mock.calls[0]?.[0] as { onUpdate: (args: { editor: typeof mockEditor }) => void };
const onUpdate = editorOptions.onUpdate;
// Call onUpdate with mock editor
onUpdate({ editor: mockEditor });
expect(mockEditor.getHTML).toHaveBeenCalled();
});
});
describe('Editor State Management', () => {
it('should apply active state to toolbar buttons', () => {
mockEditor.isActive.mockReturnValue(true);
render(<RichTextEditor value="" onChange={jest.fn()} />);
// When active, the button should have brand styling
const boldButton = screen.getByTitle('加粗');
expect(boldButton).toBeInTheDocument();
});
it('should disable undo button when cannot undo', () => {
mockEditor.can.mockReturnValue({
undo: jest.fn(() => false),
redo: jest.fn(() => true),
});
render(<RichTextEditor value="" onChange={jest.fn()} />);
const undoButton = screen.getByTitle('撤销');
expect(undoButton).toBeDisabled();
});
it('should disable redo button when cannot redo', () => {
mockEditor.can.mockReturnValue({
undo: jest.fn(() => true),
redo: jest.fn(() => false),
});
render(<RichTextEditor value="" onChange={jest.fn()} />);
const redoButton = screen.getByTitle('重做');
expect(redoButton).toBeDisabled();
});
});
describe('Edge Cases', () => {
it('should handle null editor in useEffect', () => {
// Force editor to be null after first render
const useEditorMock = (jest.requireMock('@tiptap/react') as { useEditor: jest.Mock }).useEditor;
useEditorMock.mockReturnValueOnce(null);
const { rerender } = render(
<RichTextEditor value="test" onChange={jest.fn()} />
);
// Rerender with null editor - should not crash
expect(() => {
rerender(<RichTextEditor value="updated" onChange={jest.fn()} />);
}).not.toThrow();
});
it('should handle empty value', () => {
const useEditorMock = (jest.requireMock('@tiptap/react') as { useEditor: jest.Mock }).useEditor;
render(<RichTextEditor value="" onChange={jest.fn()} />);
const editorOptions = useEditorMock.mock.calls[0]?.[0] as { content: string };
expect(editorOptions.content).toBe('');
});
});
});
-204
View File
@@ -1,204 +0,0 @@
'use client';
import { useEditor, EditorContent, type Editor } from '@tiptap/react';
import StarterKit from '@tiptap/starter-kit';
import Link from '@tiptap/extension-link';
import Placeholder from '@tiptap/extension-placeholder';
import { useEffect } from 'react';
import {
Bold,
Italic,
Heading2,
Heading3,
List,
ListOrdered,
Link as LinkIcon,
Quote,
Undo2,
Redo2,
} from 'lucide-react';
interface RichTextEditorProps {
value: string;
onChange: (html: string) => void;
placeholder?: string;
}
/**
* TipTap 富文本编辑器
* 用于 CMS ContentEditor 的 richtext 字段
* 支持:加粗、斜体、标题、列表、引用、链接
* 暗色主题适配(CMS Studio 暗色背景)
*/
export function RichTextEditor({ value, onChange, placeholder = '请输入内容...' }: RichTextEditorProps) {
const editor = useEditor({
extensions: [
StarterKit.configure({
heading: {
levels: [2, 3],
},
}),
Link.configure({
openOnClick: false,
HTMLAttributes: {
class: 'text-brand-ink underline',
},
}),
Placeholder.configure({
placeholder,
}),
],
content: value,
immediatelyRender: false,
onUpdate: ({ editor: e }) => {
onChange(e.getHTML());
},
editorProps: {
attributes: {
class: 'rich-text-editor-content',
},
},
});
// 同步外部 value 变化(如切换内容条目时)
useEffect(() => {
if (editor && value !== editor.getHTML()) {
editor.commands.setContent(value || '');
}
}, [editor, value]);
if (!editor) {
return (
<div className="min-h-[120px] bg-white/[0.05] border border-white/[0.1] rounded-lg p-3 text-white/40 text-sm">
加载编辑器...
</div>
);
}
return (
<div className="rich-text-editor bg-white/[0.05] border border-white/[0.1] rounded-lg overflow-hidden focus-within:border-brand/50 focus-within:ring-1 focus-within:ring-brand/30 transition-colors">
<Toolbar editor={editor} />
<EditorContent editor={editor} />
</div>
);
}
function Toolbar({ editor }: { editor: Editor }) {
const btnClass = (isActive: boolean) =>
`p-1.5 rounded transition-colors ${
isActive
? 'bg-brand/20 text-brand-ink'
: 'text-white/60 hover:bg-white/[0.05] hover:text-white'
}`;
const setLink = () => {
const previousUrl = editor.getAttributes('link').href;
const url = window.prompt('链接 URL', previousUrl);
if (url === null) return;
if (url === '') {
editor.chain().focus().extendMarkRange('link').unsetLink().run();
return;
}
editor.chain().focus().extendMarkRange('link').setLink({ href: url }).run();
};
return (
<div className="flex items-center gap-0.5 px-2 py-1.5 border-b border-white/[0.08] bg-white/[0.02]">
<button
type="button"
onClick={() => editor.chain().focus().toggleBold().run()}
className={btnClass(editor.isActive('bold'))}
title="加粗"
>
<Bold className="w-4 h-4" />
</button>
<button
type="button"
onClick={() => editor.chain().focus().toggleItalic().run()}
className={btnClass(editor.isActive('italic'))}
title="斜体"
>
<Italic className="w-4 h-4" />
</button>
<div className="w-px h-5 bg-white/[0.08] mx-1" />
<button
type="button"
onClick={() => editor.chain().focus().toggleHeading({ level: 2 }).run()}
className={btnClass(editor.isActive('heading', { level: 2 }))}
title="标题 2"
>
<Heading2 className="w-4 h-4" />
</button>
<button
type="button"
onClick={() => editor.chain().focus().toggleHeading({ level: 3 }).run()}
className={btnClass(editor.isActive('heading', { level: 3 }))}
title="标题 3"
>
<Heading3 className="w-4 h-4" />
</button>
<div className="w-px h-5 bg-white/[0.08] mx-1" />
<button
type="button"
onClick={() => editor.chain().focus().toggleBulletList().run()}
className={btnClass(editor.isActive('bulletList'))}
title="无序列表"
>
<List className="w-4 h-4" />
</button>
<button
type="button"
onClick={() => editor.chain().focus().toggleOrderedList().run()}
className={btnClass(editor.isActive('orderedList'))}
title="有序列表"
>
<ListOrdered className="w-4 h-4" />
</button>
<button
type="button"
onClick={() => editor.chain().focus().toggleBlockquote().run()}
className={btnClass(editor.isActive('blockquote'))}
title="引用"
>
<Quote className="w-4 h-4" />
</button>
<div className="w-px h-5 bg-white/[0.08] mx-1" />
<button
type="button"
onClick={setLink}
className={btnClass(editor.isActive('link'))}
title="链接"
>
<LinkIcon className="w-4 h-4" />
</button>
<div className="flex-1" />
<button
type="button"
onClick={() => editor.chain().focus().undo().run()}
disabled={!editor.can().undo()}
className="p-1.5 rounded text-white/60 hover:bg-white/[0.05] hover:text-white transition-colors disabled:opacity-30 disabled:cursor-not-allowed"
title="撤销"
>
<Undo2 className="w-4 h-4" />
</button>
<button
type="button"
onClick={() => editor.chain().focus().redo().run()}
disabled={!editor.can().redo()}
className="p-1.5 rounded text-white/60 hover:bg-white/[0.05] hover:text-white transition-colors disabled:opacity-30 disabled:cursor-not-allowed"
title="重做"
>
<Redo2 className="w-4 h-4" />
</button>
</div>
);
}
+366 -15
View File
@@ -1,21 +1,66 @@
import { describe, it, expect } from '@jest/globals';
import { describe, it, expect, jest } from '@jest/globals';
import { render, screen } from '@testing-library/react';
import { MethodologyFramework } from './sections';
import userEvent from '@testing-library/user-event';
import '@testing-library/jest-dom';
import {
MethodologyFramework,
TechStackShowcase,
DeliveryTimeline,
FAQSection,
DataProofSection,
type DataMetric,
type MethodologyLayer,
type TechStackCategory,
type TimelineStep,
} from './sections';
// ─── Mocks ───────────────────────────────────────────────────────────────
// framer-motion 换成哑组件:本文件的动画不可见,animate/initial 是唯一能断言的状态输出,
// 因此 FAQ 折叠态等「状态机」只能通过 data-animate 校验(见 sections.test.tsx 同族范式)。
jest.mock('framer-motion', () => ({
motion: {
div: ({ children, initial, animate, variants, whileInView, viewport, transition, className, style, ...props }: any) => (
<div
data-testid="motion-div"
data-initial={JSON.stringify(initial)}
data-animate={JSON.stringify(animate)}
data-variants={JSON.stringify(variants)}
data-while-inview={JSON.stringify(whileInView)}
data-viewport={JSON.stringify(viewport)}
data-transition={JSON.stringify(transition)}
className={className}
style={style}
{...props}
>
{children}
</div>
),
},
useInView: jest.fn(() => true),
AnimatePresence: ({ children }: any) => <>{children}</>,
}));
// ─── Test Data ───────────────────────────────────────────────────────────
const layers: MethodologyLayer[] = [
{ title: '诊断', description: '业务现状诊断', items: ['访谈', '数据分析'] },
{ title: '设计', description: '解决方案设计', items: ['架构设计'] },
];
/** 取答案文本所在的高度动画容器 */
function panelOf(answer: string): HTMLElement {
const el = screen.getByText(answer).closest('[data-testid="motion-div"]');
if (!el) throw new Error(`找不到答案「${answer}」所属的动画容器`);
return el as HTMLElement;
}
function panelAnimate(answer: string): { height?: number | string; opacity?: number } {
return JSON.parse(panelOf(answer).dataset.animate ?? '{}');
}
// ─── MethodologyFramework ────────────────────────────────────────────────
describe('MethodologyFramework', () => {
const layers = [
{
title: '诊断',
description: '业务现状诊断',
items: ['访谈', '数据分析'],
},
{
title: '设计',
description: '解决方案设计',
items: ['架构设计'],
},
];
it('renders title and subtitle', () => {
render(<MethodologyFramework title="方法论" subtitle="分层推进" layers={layers} />);
expect(screen.getByText('方法论')).toBeInTheDocument();
@@ -33,7 +78,313 @@ describe('MethodologyFramework', () => {
it('renders without subtitle', () => {
const { container } = render(<MethodologyFramework title="方法论" layers={layers} />);
expect(container.querySelector('h2')).toHaveTextContent('方法论');
// 无 subtitle 时只剩每层描述各一个 <p>,不额外多出引言段
expect(container.querySelectorAll('p')).toHaveLength(layers.length);
});
it('draws a connector only between adjacent layers, never after the last one', () => {
const { container } = render(<MethodologyFramework title="方法论" layers={layers} />);
expect(container.querySelectorAll('[class*="bg-gradient-to-b"]')).toHaveLength(1);
const single = render(<MethodologyFramework title="单步方法论" layers={[layers[0]!]} />);
expect(single.container.querySelectorAll('[class*="bg-gradient-to-b"]')).toHaveLength(0);
});
it('defaults the accent to brand red and honours a custom accentColor', () => {
const { container, unmount } = render(<MethodologyFramework title="M" layers={layers} />);
const dot = container.querySelector('div[class*="rounded-full"]');
expect(dot).toHaveStyle({ backgroundColor: 'rgb(196, 30, 58)' });
unmount();
const custom = render(
<MethodologyFramework title="M" layers={layers} accentColor="#0891B2" />,
);
expect(custom.container.querySelector('div[class*="rounded-full"]')).toHaveStyle({
backgroundColor: 'rgb(8, 145, 178)',
});
});
it('renders only the heading block when layers is empty', () => {
const { container } = render(<MethodologyFramework title="空方法论" layers={[]} />);
expect(screen.getByText('空方法论')).toBeInTheDocument();
expect(container.querySelectorAll('h3')).toHaveLength(0);
});
});
// ─── TechStackShowcase ───────────────────────────────────────────────────
describe('TechStackShowcase', () => {
const categories: TechStackCategory[] = [
{ name: '后端', items: ['Java', 'Node.js'] },
{ name: '数据', items: ['ClickHouse'] },
];
it('renders every category card with its technology chips', () => {
render(
<TechStackShowcase
title="技术栈"
subtitle="按能力域分组"
categories={categories}
/>,
);
expect(screen.getByText('技术栈')).toBeInTheDocument();
expect(screen.getByText('按能力域分组')).toBeInTheDocument();
expect(screen.getAllByText('Java')).toHaveLength(1);
expect(screen.getAllByText('Node.js')).toHaveLength(1);
expect(screen.getAllByText('ClickHouse')).toHaveLength(1);
});
it('omits the subtitle paragraph when subtitle is not given', () => {
const { container } = render(<TechStackShowcase title="技术栈" categories={categories} />);
expect(container.querySelectorAll('p')).toHaveLength(0);
expect(container.querySelectorAll('h3')).toHaveLength(2);
});
it('renders a card without chips when a category has no items', () => {
const { container } = render(
<TechStackShowcase title="技术栈" categories={[{ name: '待定', items: [] }]} />,
);
expect(screen.getByText('待定')).toBeInTheDocument();
expect(container.querySelectorAll('h3')).toHaveLength(1);
// 空 items 下不产生任何 chip(chip 是 span,标题是 h3)
expect(container.querySelectorAll('.flex.flex-wrap.gap-2 span')).toHaveLength(0);
});
});
// ─── Q-5 响应式网格回归 ────────────────────────────────────────────────────
// StaggerReveal 会为每个子项各包一层 motion.div。若把 grid/space 类放在「只含 StaggerReveal
// 这一个子元素」的外层容器上,包装层成为唯一网格项 ⇒ 卡片在桌面端塌成单列、gap/space 全部失效。
// 正确做法是把网格类挂到 StaggerReveal 自身(其 className 落在 motion.div 上,直接子项即各卡片)。
describe('Q-5 网格类必须挂在 StaggerReveal 上(卡片为网格直接子项)', () => {
it('TechStackShowcase: grid-cols-3 元素直接父有每类一张卡', () => {
const { container } = render(
<TechStackShowcase
title="技术栈"
categories={[
{ name: '后端', items: ['Java'] },
{ name: '数据', items: ['ClickHouse'] },
{ name: '前端', items: ['React'] },
]}
/>,
);
const grid = container.querySelector('[class*="grid-cols-3"]');
expect(grid).not.toBeNull();
expect(grid!.className).toContain('grid');
// 旧结构下 grid 元素只有 1 个子项(StaggerReveal 包裹层)⇒ 单列;修复后应为 3
expect(grid!.children.length).toBe(3);
});
it('DataProofSection: grid-cols-4 元素直接父有每个指标一格', () => {
const metrics = [
{ value: '99.9%', label: '可用率' },
{ value: '20+', label: '对接源' },
{ value: '40%', label: '提效' },
];
const { container } = render(<DataProofSection title="成果" metrics={metrics} />);
const grid = container.querySelector('[class*="grid-cols-4"]');
expect(grid).not.toBeNull();
expect(grid!.className).toContain('grid');
expect(grid!.children.length).toBe(3);
});
it('FAQSection: space-y 挂在 StaggerReveal 上,问答条目为其直接子项', () => {
const items = [
{ question: 'Q1', answer: 'A1' },
{ question: 'Q2', answer: 'A2' },
];
const { container } = render(<FAQSection title="常见问题" items={items} />);
const stack = container.querySelector('[class*="space-y-3"]');
expect(stack).not.toBeNull();
// 旧结构下 space-y-3 在外层 div(仅 1 个子 = StaggerReveal 根)⇒ 间距失效
expect(stack!.children.length).toBe(2);
});
});
// ─── DeliveryTimeline ────────────────────────────────────────────────────
describe('DeliveryTimeline', () => {
const steps: TimelineStep[] = [
{
phase: '诊断',
title: '现状梳理',
description: '访谈与数据盘点',
duration: '2 周',
deliverables: ['诊断报告', '路线图'],
},
{
phase: '交付',
title: '系统上线',
description: '迭代开发与部署',
duration: '8 周',
deliverables: ['生产环境'],
},
{
phase: '陪跑',
title: '运营支持',
description: '指标看板与培训',
duration: '长期',
deliverables: [],
},
];
it('numbers phases from 1 and shows duration, title, description and deliverables', () => {
render(<DeliveryTimeline title="交付路径" subtitle="四步走" steps={steps} />);
expect(screen.getByText('第 1 阶段:诊断')).toBeInTheDocument();
expect(screen.getByText('第 2 阶段:交付')).toBeInTheDocument();
expect(screen.getByText('第 3 阶段:陪跑')).toBeInTheDocument();
expect(screen.getByText('2 周')).toBeInTheDocument();
expect(screen.getByText('现状梳理')).toBeInTheDocument();
expect(screen.getByText('访谈与数据盘点')).toBeInTheDocument();
expect(screen.getByText('诊断报告')).toBeInTheDocument();
expect(screen.getAllByText('阶段产出')).toHaveLength(3);
});
it('alternates the card side per index', () => {
const { container } = render(<DeliveryTimeline title="交付路径" steps={steps} />);
const leftShifted = container.querySelectorAll('[class*="lg:ml-12"]');
const rightShifted = container.querySelectorAll('[class*="lg:mr-12"]');
expect(leftShifted).toHaveLength(2); // index 0 与 2
expect(rightShifted).toHaveLength(1); // index 1
expect(container.querySelectorAll('[class*="lg:flex-row-reverse"]')).toHaveLength(1);
});
it('paints the timeline node border with accentColor', () => {
const { container } = render(
<DeliveryTimeline title="交付路径" steps={steps} accentColor="#1D4ED8" />,
);
const node = container.querySelector('div[class*="rounded-full"]');
expect(node).toHaveStyle({ borderColor: 'rgb(29, 78, 216)' });
});
it('renders the heading only when there are no steps', () => {
const { container } = render(<DeliveryTimeline title="交付路径" steps={[]} />);
expect(screen.getByText('交付路径')).toBeInTheDocument();
expect(container.querySelectorAll('h3')).toHaveLength(0);
expect(container.querySelectorAll('[class*="rounded-full"]')).toHaveLength(0);
});
});
// ─── FAQSection ──────────────────────────────────────────────────────────
describe('FAQSection', () => {
const items = [
{ question: '交付周期多久?', answer: '通常 8-12 周。' },
{ question: '是否私有化部署?', answer: '支持全栈私有化。' },
];
it('keeps the first question open and the rest collapsed on mount', () => {
render(<FAQSection title="常见问题" subtitle="选型答疑" items={items} />);
expect(panelAnimate('通常 8-12 周。')).toEqual({ height: 'auto', opacity: 1 });
expect(panelAnimate('支持全栈私有化。')).toEqual({ height: 0, opacity: 0 });
// 展开项的箭头旋转 180°,折叠项归零
const openChevron = screen.getByText('交付周期多久?').closest('button');
expect(
JSON.parse(openChevron?.querySelector('[data-testid="motion-div"]')?.getAttribute('data-animate') ?? '{}'),
).toEqual({ rotate: 180 });
});
it('opens the clicked question and closes the previously open one', async () => {
render(<FAQSection title="常见问题" items={items} />);
await userEvent.click(screen.getByText('是否私有化部署?'));
expect(panelAnimate('支持全栈私有化。')).toEqual({ height: 'auto', opacity: 1 });
expect(panelAnimate('通常 8-12 周。')).toEqual({ height: 0, opacity: 0 });
});
it('collapses the open question when its own trigger is clicked again', async () => {
render(<FAQSection title="常见问题" items={items} />);
await userEvent.click(screen.getByText('交付周期多久?'));
expect(panelAnimate('通常 8-12 周。')).toEqual({ height: 0, opacity: 0 });
// 全部折叠后箭头不再旋转
const chevron = screen
.getByText('交付周期多久?')
.closest('button')
?.querySelector('[data-testid="motion-div"]');
expect(JSON.parse(chevron?.getAttribute('data-animate') ?? '{}')).toEqual({ rotate: 0 });
});
it('renders no accordion when items is empty', () => {
render(<FAQSection title="常见问题" items={[]} />);
expect(screen.getByText('常见问题')).toBeInTheDocument();
expect(screen.queryAllByRole('button')).toHaveLength(0);
});
});
// ─── DataProofSection ────────────────────────────────────────────────────
describe('DataProofSection', () => {
const metrics: DataMetric[] = [
{
value: '40%',
label: '库存周转提升',
description: '以季度为口径',
trend: '+12% 环比',
trendUp: true,
basis: 'target',
},
{ value: '99.9%', label: '系统可用率', trend: '-0.1% 波动', trendUp: false, basis: 'verified' },
];
it('renders each metric with optional description and trend', () => {
render(<DataProofSection title="可验证的成果" subtitle="口径透明" metrics={metrics} />);
expect(screen.getByText('40%')).toBeInTheDocument();
expect(screen.getByText('库存周转提升')).toBeInTheDocument();
expect(screen.getByText('以季度为口径')).toBeInTheDocument();
expect(screen.getByText('99.9%')).toBeInTheDocument();
expect(screen.getByText('+12% 环比')).toBeInTheDocument();
expect(screen.getByText('-0.1% 波动')).toBeInTheDocument();
});
it('colors up-trends as success and down-trends as brand ink', () => {
const { container } = render(<DataProofSection title="成果" metrics={metrics} />);
const up = screen.getByText('+12% 环比').closest('[class*="inline-flex"]');
const down = screen.getByText('-0.1% 波动').closest('[class*="inline-flex"]');
expect(up?.className).toContain('text-success');
expect(up?.className).not.toContain('text-brand-ink');
expect(down?.className).toContain('text-brand-ink');
expect(container.querySelectorAll('[class*="inline-flex"]')).toHaveLength(2);
});
it('omits description and trend blocks when those fields are absent', () => {
const { container } = render(
<DataProofSection title="成果" metrics={[{ value: '3 座', label: '交付城市' }]} />,
);
expect(screen.getByText('交付城市')).toBeInTheDocument();
expect(container.querySelectorAll('[class*="inline-flex"]')).toHaveLength(0);
// 无 description 时不渲染 <p>,但口径角注本身是一个 <p>
expect(container.querySelectorAll('p')).toHaveLength(1);
});
it('annotates the aggregate basis as the weakest one across metrics', () => {
render(<DataProofSection title="成果" metrics={metrics} />);
// target(0) 弱于 verified(2) → 取 target 文案
expect(screen.getByTestId('metrics-basis-note')).toHaveTextContent('目标口径,非既成结果');
});
it('annotates a stronger note when every metric is verified', () => {
render(
<DataProofSection title="成果" metrics={[{ value: '40%', label: 'X', basis: 'verified' }]} />,
);
expect(screen.getByTestId('metrics-basis-note')).toHaveTextContent('已有可核验的实测出处');
});
it('annotates team-history wording when that is the only declared basis', () => {
render(
<DataProofSection title="成果" metrics={[{ value: '40%', label: 'X', basis: 'team-history' }]} />,
);
expect(screen.getByTestId('metrics-basis-note')).toHaveTextContent('团队历史项目成果');
});
it('renders nothing when metrics is empty', () => {
const { container } = render(<DataProofSection title="成果" metrics={[]} />);
expect(container).toBeEmptyDOMElement();
expect(screen.queryByText('成果')).not.toBeInTheDocument();
});
it('guards a missing metrics prop instead of throwing', () => {
const { container } = render(
<DataProofSection title="成果" metrics={undefined as unknown as DataMetric[]} />,
);
expect(container).toBeEmptyDOMElement();
});
});
+17 -13
View File
@@ -51,7 +51,7 @@ export function MethodologyFramework({
initial={{ opacity: 0, x: -30 }}
whileInView={{ opacity: 1, x: 0 }}
viewport={{ once: true, margin: '-50px' }}
transition={{ duration: 0.3, delay: index * 0.06, ease: EASE_OUT }}
transition={{ duration: 0.28, delay: index * 0.06, ease: EASE_OUT }}
>
<div className="flex gap-6 lg:gap-10">
<div className="flex flex-col items-center pt-2">
@@ -118,8 +118,11 @@ export function TechStackShowcase({ title, subtitle, categories }: TechStackShow
)}
</ScrollReveal>
<div className="grid md:grid-cols-2 lg:grid-cols-3 gap-6">
<StaggerReveal staggerDelay={0.05} delayChildren={0.05}>
<StaggerReveal
staggerDelay={0.05}
delayChildren={0.05}
className="grid md:grid-cols-2 lg:grid-cols-3 gap-6"
>
{categories.map((category, index) => (
<div
key={index}
@@ -130,7 +133,7 @@ export function TechStackShowcase({ title, subtitle, categories }: TechStackShow
{category.items.map((item, i) => (
<span
key={i}
className="px-3 py-1.5 text-xs font-medium bg-bg-secondary text-text-secondary border border-border-primary hover:border-brand/30 hover:text-brand-ink transition-colors duration-300"
className="px-3 py-1.5 text-xs font-medium bg-bg-secondary text-text-secondary border border-border-primary hover:border-brand/30 hover:text-brand-ink transition-colors duration-normal"
>
{item}
</span>
@@ -139,7 +142,6 @@ export function TechStackShowcase({ title, subtitle, categories }: TechStackShow
</div>
))}
</StaggerReveal>
</div>
</div>
</section>
);
@@ -269,12 +271,12 @@ export function FAQSection({ title, subtitle, items }: FAQSectionProps) {
)}
</ScrollReveal>
<div className="lg:col-span-8 space-y-3">
<StaggerReveal staggerDelay={0.06} delayChildren={0.05}>
<div className="lg:col-span-8">
<StaggerReveal staggerDelay={0.06} delayChildren={0.05} className="space-y-3">
{items.map((item, index) => (
<div
key={index}
className="border border-border-primary bg-bg-primary hover:border-border-secondary transition-colors duration-300"
className="border border-border-primary bg-bg-primary hover:border-border-secondary transition-colors duration-normal"
>
<button
onClick={() => setOpenIndex(openIndex === index ? null : index)}
@@ -285,7 +287,7 @@ export function FAQSection({ title, subtitle, items }: FAQSectionProps) {
</span>
<motion.div
animate={{ rotate: openIndex === index ? 180 : 0 }}
transition={{ duration: 0.3, ease: EASE_OUT }}
transition={{ duration: 0.28, ease: EASE_OUT }}
className="shrink-0"
>
<ChevronDown className="w-5 h-5 text-text-muted" />
@@ -297,7 +299,7 @@ export function FAQSection({ title, subtitle, items }: FAQSectionProps) {
height: openIndex === index ? 'auto' : 0,
opacity: openIndex === index ? 1 : 0,
}}
transition={{ duration: 0.3, ease: EASE_OUT }}
transition={{ duration: 0.28, ease: EASE_OUT }}
className="overflow-hidden"
>
<div className="px-6 lg:px-7 pb-7 pt-1 text-text-secondary leading-relaxed">
@@ -347,8 +349,11 @@ export function DataProofSection({ title, subtitle, metrics }: DataProofSectionP
)}
</ScrollReveal>
<div className="grid md:grid-cols-2 lg:grid-cols-4 gap-px bg-border-primary">
<StaggerReveal staggerDelay={0.05} delayChildren={0.05}>
<StaggerReveal
staggerDelay={0.05}
delayChildren={0.05}
className="grid md:grid-cols-2 lg:grid-cols-4 gap-px bg-border-primary"
>
{metrics.map((metric, index) => (
<div
key={index}
@@ -378,7 +383,6 @@ export function DataProofSection({ title, subtitle, metrics }: DataProofSectionP
</div>
))}
</StaggerReveal>
</div>
<MetricsBasisNote basis={basis} className="mt-6" />
</div>
</section>
@@ -1,55 +0,0 @@
import { describe, it, expect } from '@jest/globals';
import { render, screen, fireEvent } from '@testing-library/react';
import { TestimonialSection, LogoWall } from './testimonials';
describe('TestimonialSection', () => {
const testimonials = [
{
quote: '服务非常专业',
author: '张三',
title: 'CEO',
company: 'A 公司',
industry: '科技',
},
{
quote: '交付准时',
author: '李四',
title: 'CTO',
company: 'B 公司',
industry: '制造',
},
];
it('renders title and subtitle', () => {
render(<TestimonialSection title="客户评价" subtitle="来自客户的真实反馈" testimonials={testimonials} />);
expect(screen.getByText('客户评价')).toBeInTheDocument();
expect(screen.getByText('来自客户的真实反馈')).toBeInTheDocument();
});
it('renders first testimonial by default', () => {
render(<TestimonialSection title="客户评价" testimonials={testimonials} />);
expect(screen.getByText('张三')).toBeInTheDocument();
expect(screen.getByText('科技')).toBeInTheDocument();
});
it('switches testimonial on dot click', () => {
render(<TestimonialSection title="客户评价" testimonials={testimonials} />);
const dots = screen.getAllByRole('button');
fireEvent.click(dots[1]!);
expect(screen.getByText('李四')).toBeInTheDocument();
expect(screen.getByText('制造')).toBeInTheDocument();
});
it('renders without subtitle', () => {
const { container } = render(<TestimonialSection title="客户评价" testimonials={testimonials} />);
expect(container.querySelector('h2')).toHaveTextContent('客户评价');
});
});
describe('LogoWall (testimonials)', () => {
it('renders logo wall', () => {
render(<LogoWall title="合作企业" logos={[{ name: 'A 公司' }, { name: 'B 公司', industry: '制造' }]} />);
expect(screen.getByText('合作企业')).toBeInTheDocument();
expect(screen.getByText('A 公司')).toBeInTheDocument();
});
});
-155
View File
@@ -1,155 +0,0 @@
'use client';
import { motion } from 'framer-motion';
import { ScrollReveal } from '@/components/ui/scroll-reveal';
import { SectionLabel, EASE_OUT } from '@/components/ui/page-decoration';
import { Quote } from 'lucide-react';
import { useState } from 'react';
import { cn } from '@/lib/utils';
export interface Testimonial {
quote: string;
author: string;
title: string;
company: string;
industry: string;
}
export interface TestimonialSectionProps {
title: string;
subtitle?: string;
testimonials: Testimonial[];
accentColor?: string;
}
export function TestimonialSection({
title,
subtitle,
testimonials,
accentColor = '#C41E3A',
}: TestimonialSectionProps) {
const [activeIndex, setActiveIndex] = useState(0);
return (
<section className="relative py-20 sm:py-28 md:py-32 lg:py-40 overflow-hidden bg-bg-secondary">
<div className="max-w-container mx-auto px-4 sm:px-6 lg:px-10">
<ScrollReveal className="mb-16 sm:mb-20 max-w-3xl">
<SectionLabel>Client Stories</SectionLabel>
<h2 className="text-3xl md:text-4xl lg:text-5xl font-bold text-ink tracking-tight leading-tight mb-6">
{title}
</h2>
{subtitle && (
<p className="text-text-secondary leading-relaxed text-lg">
{subtitle}
</p>
)}
</ScrollReveal>
<div className="relative">
<div className="relative overflow-hidden">
<motion.div
className="flex"
animate={{ x: `-${activeIndex * 100}%` }}
transition={{ duration: 0.3, ease: EASE_OUT }}
>
{testimonials.map((testimonial, index) => (
<div key={index} className="w-full shrink-0">
<div className="max-w-4xl mx-auto">
<div className="relative p-10 lg:p-16 border border-border-primary bg-bg-primary">
<Quote className="absolute top-8 left-8 w-12 h-12 opacity-10 text-brand-ink" />
<div className="relative z-10">
<p className="text-xl lg:text-2xl text-text-primary leading-relaxed font-light mb-10 lg:mb-14">
「{testimonial.quote}」
</p>
<div className="flex items-center gap-5">
<div
className="w-14 h-14 rounded-full flex items-center justify-center text-white font-bold text-lg"
style={{ backgroundColor: accentColor }}
>
{testimonial.author.charAt(0)}
</div>
<div>
<div className="text-text-primary font-semibold text-lg">
{testimonial.author}
</div>
<div className="text-text-secondary text-sm">
{testimonial.title} · {testimonial.company}
</div>
<div className="text-text-muted text-xs mt-0.5">
{testimonial.industry}
</div>
</div>
</div>
</div>
</div>
</div>
</div>
))}
</motion.div>
</div>
<div className="flex justify-center gap-3 mt-10">
{testimonials.map((_, index) => (
<button
key={index}
onClick={() => setActiveIndex(index)}
className={cn(
'h-2 rounded-full transition-all duration-300',
activeIndex === index
? 'w-8'
: 'w-2 bg-border-primary hover:bg-border-secondary'
)}
style={activeIndex === index ? { backgroundColor: accentColor } : {}}
/>
))}
</div>
</div>
</div>
</section>
);
}
export interface LogoWallProps {
title: string;
logos: { name: string; industry?: string }[];
}
export function LogoWall({ title, logos }: LogoWallProps) {
return (
<section className="relative py-16 sm:py-20 overflow-hidden bg-bg-primary">
<div className="max-w-container mx-auto px-4 sm:px-6 lg:px-10">
<ScrollReveal>
<div className="text-center mb-12">
<p className="text-sm text-text-muted tracking-[0.2em] uppercase font-medium">
{title}
</p>
</div>
</ScrollReveal>
<div className="grid grid-cols-2 sm:grid-cols-3 md:grid-cols-4 lg:grid-cols-6 gap-px bg-border-primary">
{logos.map((logo, index) => (
<motion.div
key={index}
initial={{ opacity: 0, y: 20 }}
whileInView={{ opacity: 1, y: 0 }}
viewport={{ once: true }}
transition={{ duration: 0.3, delay: index * 0.05, ease: EASE_OUT }}
className="flex items-center justify-center p-8 bg-bg-primary hover:bg-bg-secondary transition-colors duration-300"
>
<div className="text-center">
<div className="text-text-secondary font-semibold text-base hover:text-text-primary transition-colors duration-300">
{logo.name}
</div>
{logo.industry && (
<div className="text-text-muted text-xs mt-1">
{logo.industry}
</div>
)}
</div>
</motion.div>
))}
</div>
</div>
</section>
);
}
@@ -75,12 +75,12 @@ export function CaseStudiesSection({
{caseStudies.map((study) => (
<div
key={study.client}
className="group relative block h-full overflow-hidden bg-bg-primary transition-all duration-300 hover:bg-bg-secondary"
className="group relative block h-full overflow-hidden bg-bg-primary transition-all duration-normal hover:bg-bg-secondary"
>
<div className="aspect-[4/3] bg-gradient-to-br from-bg-secondary to-bg-tertiary relative overflow-hidden">
<div className="absolute inset-0 flex items-center justify-center">
{/* 客户名首字作占位图形(无真实配图时),纯装饰 → aria-hidden 豁免对比度 */}
<span aria-hidden="true" className="text-6xl font-bold text-text-muted/10">
{/* 客户名首字占位图形(无真实配图时):aria-hidden 不豁免 1.4.3,用大字档令牌 text-text-hint */}
<span aria-hidden="true" className="text-6xl font-bold text-text-hint">
{study.client.charAt(0)}
</span>
</div>
@@ -92,7 +92,7 @@ export function CaseStudiesSection({
</div>
<div className="p-8">
<h3 className="text-xl font-bold text-ink mb-3 group-hover:translate-x-2 transition-transform duration-300">
<h3 className="text-xl font-bold text-ink mb-3 group-hover:translate-x-2 transition-transform duration-normal">
{study.client}
</h3>
<p className="text-text-secondary text-sm leading-relaxed mb-6">
+1 -1
View File
@@ -14,7 +14,7 @@ export function CaseStudyCard({ study, index }: CaseStudyCardProps) {
initial={{ opacity: 0, y: 20 }}
whileInView={{ opacity: 1, y: 0 }}
viewport={{ once: true, margin: '-50px' }}
transition={{ duration: 0.3, delay: index * 0.06 }}
transition={{ duration: 0.28, delay: index * 0.06 }}
className="rounded-xl border border-border-primary bg-bg-elevated p-6 shadow-sm transition-shadow hover:shadow-md"
>
<div className="mb-3 flex items-center gap-2">
@@ -21,7 +21,7 @@ export function CertificationList({ certifications }: CertificationListProps) {
initial: { opacity: 0, scale: 0.95 },
whileInView: { opacity: 1, scale: 1 },
viewport: { once: true, margin: '-50px' },
transition: { duration: 0.3, delay: index * 0.05 },
transition: { duration: 0.28, delay: index * 0.05 },
className,
};
const inner = (
@@ -57,7 +57,7 @@ export function CertificationsSection({ certifications }: CertificationsSectionP
{certifications.map((cert, idx) => (
<div
key={idx}
className="group flex items-center gap-4 px-8 py-5 bg-bg-primary hover:bg-bg-secondary transition-all duration-300"
className="group flex items-center gap-4 px-8 py-5 bg-bg-primary hover:bg-bg-secondary transition-all duration-normal"
>
<div className="w-12 h-12 rounded-xl bg-brand-soft flex items-center justify-center text-brand-ink">
<Shield className="w-6 h-6" />
+3 -3
View File
@@ -38,7 +38,7 @@ export function DetailCTASection({
initial={{ opacity: 0, y: 32 }}
whileInView={{ opacity: 1, y: 0 }}
viewport={{ once: true, margin: '-100px' }}
transition={{ duration: 0.3, ease: [0.22, 1, 0.36, 1] }}
transition={{ duration: 0.28, ease: [0.22, 1, 0.36, 1] }}
className="max-w-3xl"
>
{/* 标签 */}
@@ -61,7 +61,7 @@ export function DetailCTASection({
className="group inline-flex items-center gap-3 px-10 py-4 bg-white text-brand font-bold text-base hover:bg-white/90 transition-all duration-200"
>
<span>{primaryAction.label}</span>
<ArrowRight className="w-5 h-5 transition-transform duration-300 group-hover:translate-x-1" />
<ArrowRight className="w-5 h-5 transition-transform duration-normal group-hover:translate-x-1" />
</a>
{secondaryAction && (
@@ -78,7 +78,7 @@ export function DetailCTASection({
initial={{ opacity: 0 }}
whileInView={{ opacity: 1 }}
viewport={{ once: true }}
transition={{ delay: 0.5, duration: 0.3 }}
transition={{ delay: 0.5, duration: 0.28 }}
className="mt-10 text-sm text-white/70"
>
平均响应时间 &lt; 2小时 · 7×24小时技术支持 · 无需预付费用
+21 -17
View File
@@ -69,7 +69,7 @@ export function DetailHero({
scale: 1,
filter: 'blur(0px)',
transition: {
duration: 0.3,
duration: 0.28,
ease: [0.22, 1, 0.36, 1] as const,
},
},
@@ -101,7 +101,7 @@ export function DetailHero({
y: 0,
filter: 'blur(0px)',
transition: {
duration: 0.3,
duration: 0.28,
ease: [0.22, 1, 0.36, 1] as const,
},
},
@@ -120,7 +120,7 @@ export function DetailHero({
opacity: 1,
y: 0,
transition: {
duration: 0.3,
duration: 0.28,
delay: 0.25,
ease: [0.22, 1, 0.36, 1] as const,
},
@@ -139,7 +139,7 @@ export function DetailHero({
opacity: 1,
y: 0,
transition: {
duration: 0.3,
duration: 0.28,
delay: 0.4,
ease: [0.22, 1, 0.36, 1] as const,
},
@@ -159,7 +159,7 @@ export function DetailHero({
opacity: 1,
y: 0,
transition: {
duration: 0.3,
duration: 0.28,
delay: 0.55,
ease: [0.22, 1, 0.36, 1] as const,
},
@@ -168,19 +168,23 @@ export function DetailHero({
className={`mt-12 flex flex-wrap gap-5 ${isCenterLayout ? 'justify-center' : ''}`}
>
{primaryAction && (
<a href={primaryAction.href}>
<PressableButton variant="primary" className="px-10 py-4 text-base shadow-lg group">
<span>{primaryAction.label}</span>
<ArrowRight className="w-5 h-5 group-hover:translate-x-1 group-hover:-translate-y-0.5 transition-transform duration-300" />
</PressableButton>
</a>
<PressableButton
href={primaryAction.href}
variant="primary"
className="px-10 py-4 text-base shadow-lg group"
>
<span>{primaryAction.label}</span>
<ArrowRight className="w-5 h-5 group-hover:translate-x-1 group-hover:-translate-y-0.5 transition-transform duration-normal" />
</PressableButton>
)}
{secondaryAction && (
<a href={secondaryAction.href}>
<PressableButton variant="secondary" className="px-8 py-4 text-base">
{secondaryAction.label}
</PressableButton>
</a>
<PressableButton
href={secondaryAction.href}
variant="secondary"
className="px-8 py-4 text-base"
>
{secondaryAction.label}
</PressableButton>
)}
</motion.div>
)}
@@ -189,7 +193,7 @@ export function DetailHero({
<motion.div
initial={{ opacity: 0 }}
animate={{ opacity: 1 }}
transition={{ delay: 1.5, duration: 0.3 }}
transition={{ delay: 1.5, duration: 0.28 }}
className="absolute bottom-8 left-1/2 -translate-x-1/2"
>
<div
+28 -22
View File
@@ -1,7 +1,7 @@
'use client';
import { motion, useInView } from 'framer-motion';
import { useRef, useState } from 'react';
import { useEffect, useRef, useState } from 'react';
import {
CheckCircle2,
ArrowRight,
@@ -70,25 +70,31 @@ function MetricCard({
const suffix = value.replace(/[0-9.]/g, '');
const [displayValue, setDisplayValue] = useState('0');
if (isInView && displayValue === '0') {
// 动画必须在 effect 中驱动并在卸载/重跑时取消。历史写法在 render 体内 setState +
// requestAnimationFrame:每一帧的 setState 又触发重渲染并再 spawn 一条从 0 开始的动画链,
// 相互竞争且从不取消(Q-6)。
useEffect(() => {
if (!isInView) return;
if (isNaN(numericValue)) {
setDisplayValue(value);
} else {
let startTime: number;
const animate = (currentTime: number) => {
if (!startTime) startTime = currentTime;
const progress = Math.min((currentTime - startTime) / 2000, 1);
const easeOutQuart = 1 - Math.pow(1 - progress, 4);
setDisplayValue(
Number.isInteger(numericValue)
? Math.floor(numericValue * easeOutQuart).toString() + suffix
: (numericValue * easeOutQuart).toFixed(1) + suffix
);
if (progress < 1) requestAnimationFrame(animate);
};
requestAnimationFrame(animate);
return;
}
}
let frame = 0;
let startTime: number | undefined;
const animate = (currentTime: number) => {
if (startTime === undefined) startTime = currentTime;
const progress = Math.min((currentTime - startTime) / 2000, 1);
const easeOutQuart = 1 - Math.pow(1 - progress, 4);
setDisplayValue(
Number.isInteger(numericValue)
? Math.floor(numericValue * easeOutQuart).toString() + suffix
: (numericValue * easeOutQuart).toFixed(1) + suffix,
);
if (progress < 1) frame = requestAnimationFrame(animate);
};
frame = requestAnimationFrame(animate);
return () => cancelAnimationFrame(frame);
}, [isInView, numericValue, suffix, value]);
return (
<div className="bain-card p-8">
@@ -120,7 +126,7 @@ export function ProductValueSection({ product }: ProductValueSectionProps) {
initial={{ opacity: 0, y: 32 }}
whileInView={{ opacity: 1, y: 0 }}
viewport={{ once: true, margin: '-120px' }}
transition={{ duration: 0.3, ease: [0.22, 1, 0.36, 1] }}
transition={{ duration: 0.28, ease: [0.22, 1, 0.36, 1] }}
className="mb-16 sm:mb-20"
>
<div className="flex items-center gap-3 mb-6">
@@ -149,7 +155,7 @@ export function ProductValueSection({ product }: ProductValueSectionProps) {
whileInView={{ opacity: 1, y: 0 }}
viewport={{ once: true }}
transition={{
duration: 0.3,
duration: 0.28,
delay: index * 0.06,
ease: [0.22, 1, 0.36, 1],
}}
@@ -190,7 +196,7 @@ export function ProductValueSection({ product }: ProductValueSectionProps) {
whileInView={{ opacity: 1, x: 0 }}
viewport={{ once: true }}
transition={{
duration: 0.3,
duration: 0.28,
delay: index * 0.06,
ease: [0.22, 1, 0.36, 1],
}}
@@ -225,7 +231,7 @@ export function ProductValueSection({ product }: ProductValueSectionProps) {
viewport={{ once: true }}
transition={{
delay: 0.3 + index * 0.05,
duration: 0.3,
duration: 0.28,
ease: [0.22, 1, 0.36, 1],
}}
className="flex items-start gap-3 text-sm text-text-secondary"
@@ -245,7 +251,7 @@ export function ProductValueSection({ product }: ProductValueSectionProps) {
initial={{ opacity: 0, y: 32 }}
whileInView={{ opacity: 1, y: 0 }}
viewport={{ once: true, margin: '-80px' }}
transition={{ duration: 0.3, delay: 0.2 }}
transition={{ duration: 0.28, delay: 0.2 }}
className="mt-24"
>
<div className="mb-12">
+26 -10
View File
@@ -2,6 +2,7 @@
import { motion, useInView } from 'framer-motion';
import { useRef, useEffect, useState } from 'react';
import { useReducedMotion } from '@/hooks/use-reduced-motion';
import { CaseStudyCard } from './detail-case-study';
import { CertificationList } from './detail-certification';
import type { CaseStudy, DataProof, Certification } from '@/lib/constants/products';
@@ -19,6 +20,7 @@ function AnimatedCounter({ value, duration = 2000 }: { value: string; duration?:
const [displayValue, setDisplayValue] = useState('0');
const ref = useRef<HTMLDivElement>(null);
const isInView = useInView(ref, { once: true });
const shouldReduceMotion = useReducedMotion();
useEffect(() => {
if (!isInView) return;
@@ -29,7 +31,19 @@ function AnimatedCounter({ value, duration = 2000 }: { value: string; duration?:
return;
}
const suffix = value.replace(/[0-9.]/g, '');
const [, prefix = '', suffix = ''] = value.match(/^([^\d.]*)[\d.]+([^\d.]*)$/) ?? [];
const finalText =
prefix +
(Number.isInteger(numericValue) ? numericValue.toString() : numericValue.toFixed(1)) +
suffix;
// 尊重 prefers-reduced-motion:降级动效用户直接看到终值,不跑 2000ms rAF 计数。
// MotionConfig reducedMotion="user" 只管 framer-motion 的动画属性,管不到裸 rAF(S-9)。
if (shouldReduceMotion) {
setDisplayValue(finalText);
return;
}
let startTime: number;
let animationFrame: number;
@@ -40,9 +54,11 @@ function AnimatedCounter({ value, duration = 2000 }: { value: string; duration?:
const currentValue = numericValue * easeOutQuart;
setDisplayValue(
Number.isInteger(numericValue)
? Math.floor(currentValue).toString() + suffix
: currentValue.toFixed(1) + suffix
prefix +
(Number.isInteger(numericValue)
? Math.floor(currentValue).toString()
: currentValue.toFixed(1)) +
suffix
);
if (progress < 1) {
@@ -53,7 +69,7 @@ function AnimatedCounter({ value, duration = 2000 }: { value: string; duration?:
animationFrame = requestAnimationFrame(animate);
return () => cancelAnimationFrame(animationFrame);
}, [isInView, value, duration]);
}, [isInView, value, duration, shouldReduceMotion]);
return (
<div ref={ref} className="text-3xl sm:text-4xl font-black text-brand-ink tabular-nums leading-none">
@@ -80,7 +96,7 @@ export function DetailTrustSection({
initial={{ opacity: 0, y: 24 }}
whileInView={{ opacity: 1, y: 0 }}
viewport={{ once: true, margin: '-80px' }}
transition={{ duration: 0.3, ease: [0.22, 1, 0.36, 1] }}
transition={{ duration: 0.28, ease: [0.22, 1, 0.36, 1] }}
className="mb-12"
>
<div className="flex items-center gap-3 mb-6">
@@ -104,7 +120,7 @@ export function DetailTrustSection({
whileInView={{ opacity: 1, y: 0 }}
viewport={{ once: true, margin: '-60px' }}
transition={{
duration: 0.3,
duration: 0.28,
delay: index * 0.06,
ease: [0.22, 1, 0.36, 1],
}}
@@ -129,7 +145,7 @@ export function DetailTrustSection({
initial={{ opacity: 0, y: 24 }}
whileInView={{ opacity: 1, y: 0 }}
viewport={{ once: true, margin: '-80px' }}
transition={{ duration: 0.3, ease: [0.22, 1, 0.36, 1] }}
transition={{ duration: 0.28, ease: [0.22, 1, 0.36, 1] }}
className="mb-12"
>
<h2 className="text-2xl sm:text-3xl md:text-4xl lg:text-5xl font-black text-ink tracking-tight leading-[0.95]">
@@ -145,7 +161,7 @@ export function DetailTrustSection({
whileInView={{ opacity: 1, y: 0 }}
viewport={{ once: true, margin: '-60px' }}
transition={{
duration: 0.3,
duration: 0.28,
delay: index * 0.06,
ease: [0.22, 1, 0.36, 1],
}}
@@ -162,7 +178,7 @@ export function DetailTrustSection({
initial={{ opacity: 0, y: 24 }}
whileInView={{ opacity: 1, y: 0 }}
viewport={{ once: true, margin: '-80px' }}
transition={{ duration: 0.3, ease: [0.22, 1, 0.36, 1] }}
transition={{ duration: 0.28, ease: [0.22, 1, 0.36, 1] }}
className="text-center"
>
<h3 className="text-lg font-semibold text-text-secondary mb-6">资质认证</h3>
+56 -1
View File
@@ -1,5 +1,5 @@
import { describe, it, expect, jest } from '@jest/globals';
import { render, screen } from '@testing-library/react';
import { render, screen, act } from '@testing-library/react';
import '@testing-library/jest-dom';
// ─── Mocks ───────────────────────────────────────────────────────────────
@@ -445,6 +445,61 @@ describe('ProductValueSection', () => {
expect(screen.queryByText('以可量化的目标约束交付')).not.toBeInTheDocument();
});
it('指标计数动画由 effect 驱动并在卸载时取消排队帧(Q-6 回归)', async () => {
// Q-6:动画曾在 render 体内 setState + requestAnimationFrame——每帧 setState 又触发
// 重渲染并重启一条新动画链,且从不 cancelAnimationFrame;卸载后帧回调继续排队。
// 判别面:已排队的帧必须被逐一取消(sched === cancel),旧实现 sched>0 且 cancel=0 必红。
jest.useFakeTimers();
// faithful rAF 桩:cancel 必须真的撤销已排队的回调,否则「卸载后不再排队」无从判别
const pending = new Map<number, ReturnType<typeof setTimeout>>();
let handle = 0;
const sched = jest.fn((cb: FrameRequestCallback) => {
const id = ++handle;
pending.set(
id,
setTimeout(() => {
pending.delete(id);
cb(Date.now());
}, 16),
);
return id;
});
const cancel = jest.fn((id: number) => {
const t = pending.get(id);
if (t) clearTimeout(t);
pending.delete(id);
});
const prevRaf = global.requestAnimationFrame;
const prevCancel = global.cancelAnimationFrame;
global.requestAnimationFrame = sched as unknown as typeof requestAnimationFrame;
global.cancelAnimationFrame = cancel as unknown as typeof cancelAnimationFrame;
try {
const { ProductValueSection } = await import('./detail-product-value');
const { container, unmount } = render(<ProductValueSection product={mockProduct} />);
const card = container.querySelector('.tabular-nums') as HTMLElement;
expect(card.textContent).toBe('0');
await act(async () => {
jest.advanceTimersByTime(200);
});
// 动画真的在推进(中途值),而不是停在 0 或瞬间跳终值
expect(card.textContent).not.toBe('0');
expect(card.textContent).not.toBe('300%');
const scheduledBeforeUnmount = sched.mock.calls.length;
expect(scheduledBeforeUnmount).toBeGreaterThan(0);
unmount();
await act(async () => {
jest.advanceTimersByTime(3000);
});
// 泄漏判别:卸载后动画链必须死透——旧实现(render 期 rAF、从不 cancel)
// 在这里会继续排队每一帧;effect 版在 cleanup 里 cancel 掉最后一帧。
expect(sched.mock.calls.length).toBe(scheduledBeforeUnmount);
} finally {
global.requestAnimationFrame = prevRaf;
global.cancelAnimationFrame = prevCancel;
jest.useRealTimers();
}
});
});
describe('DetailTrustSection', () => {
-1
View File
@@ -20,7 +20,6 @@ export { CertificationsSection } from './detail-certifications-section';
export { SolutionValueSection } from './solution-value';
export { ServiceValueSection } from './service-value';
export { ListPageHero } from './list-page-hero';
export { ProductCard } from './product-card';
export { SolutionCard } from './solution-service-card';
+2 -2
View File
@@ -129,7 +129,7 @@ function SignalCard({ signal }: { signal: L3Signal }) {
<div
className={cn(
'group relative h-full p-6 sm:p-8 rounded-lg border border-border-primary bg-bg-primary',
'transition-all duration-300 ease-out',
'transition-all duration-normal ease-out',
disabled
? 'opacity-70 cursor-not-allowed'
: 'hover:border-brand/40 hover:shadow-md hover:-translate-y-1'
@@ -150,7 +150,7 @@ function SignalCard({ signal }: { signal: L3Signal }) {
{title}
{!disabled && (
<ArrowUpRight
className="w-4 h-4 transition-transform duration-300 group-hover:translate-x-0.5 group-hover:-translate-y-0.5"
className="w-4 h-4 transition-transform duration-normal group-hover:translate-x-0.5 group-hover:-translate-y-0.5"
aria-hidden="true"
/>
)}
@@ -1,152 +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, viewport, transition, className, ...props }: any) => (
<div
data-testid="motion-div"
data-initial={JSON.stringify(initial)}
data-animate={JSON.stringify(animate)}
data-variants={JSON.stringify(variants)}
data-while-inview={JSON.stringify(whileInView)}
data-viewport={JSON.stringify(viewport)}
data-transition={JSON.stringify(transition)}
className={className}
{...props}
>
{children}
</div>
),
h1: ({ children, className, ...props }: any) => (
<h1 data-testid="motion-h1" className={className} {...props}>{children}</h1>
),
p: ({ children, className, ...props }: any) => (
<p data-testid="motion-p" className={className} {...props}>{children}</p>
),
},
useInView: jest.fn(() => true),
AnimatePresence: ({ children }: any) => <>{children}</>,
}));
jest.mock('@/hooks/use-reduced-motion', () => ({
useReducedMotion: jest.fn(() => false),
}));
// ─── Tests ───────────────────────────────────────────────────────────────
describe('ListPageHero', () => {
it('should render title', async () => {
const { ListPageHero } = await import('./list-page-hero');
render(<ListPageHero title="产品服务" subtitle="企业数字化转型全方位解决方案" />);
expect(screen.getByText('产品服务')).toBeInTheDocument();
});
it('should render subtitle', async () => {
const { ListPageHero } = await import('./list-page-hero');
render(<ListPageHero title="产品服务" subtitle="企业数字化转型全方位解决方案" />);
expect(screen.getByText('企业数字化转型全方位解决方案')).toBeInTheDocument();
});
it('should render description when provided', async () => {
const { ListPageHero } = await import('./list-page-hero');
render(
<ListPageHero
title="产品服务"
subtitle="企业数字化转型全方位解决方案"
description="覆盖企业全业务场景的产品矩阵"
/>
);
expect(screen.getByText('覆盖企业全业务场景的产品矩阵')).toBeInTheDocument();
});
it('should not render description when not provided', async () => {
const { ListPageHero } = await import('./list-page-hero');
render(<ListPageHero title="产品服务" subtitle="企业数字化转型全方位解决方案" />);
expect(screen.queryByText('覆盖企业全业务场景的产品矩阵')).not.toBeInTheDocument();
});
it('should render badge when provided', async () => {
const { ListPageHero } = await import('./list-page-hero');
render(
<ListPageHero
title="产品服务"
subtitle="企业数字化转型全方位解决方案"
badge={{ text: '新品发布', variant: 'brand' }}
/>
);
expect(screen.getByText('新品发布')).toBeInTheDocument();
});
it('should not render badge when not provided', async () => {
const { ListPageHero } = await import('./list-page-hero');
render(<ListPageHero title="产品服务" subtitle="企业数字化转型全方位解决方案" />);
expect(screen.queryByText('新品发布')).not.toBeInTheDocument();
});
it('should render stats when provided', async () => {
const { ListPageHero } = await import('./list-page-hero');
const stats = [
{ value: '6', label: '企业套装' },
{ value: '3', label: '专业产品' },
];
render(
<ListPageHero
title="产品服务"
subtitle="企业数字化转型全方位解决方案"
stats={stats}
/>
);
expect(screen.getByText('6')).toBeInTheDocument();
expect(screen.getByText('企业套装')).toBeInTheDocument();
expect(screen.getByText('3')).toBeInTheDocument();
expect(screen.getByText('专业产品')).toBeInTheDocument();
});
it('should not render stats when not provided', async () => {
const { ListPageHero } = await import('./list-page-hero');
render(<ListPageHero title="产品服务" subtitle="企业数字化转型全方位解决方案" />);
expect(screen.queryByText('6')).not.toBeInTheDocument();
});
it('should render with badge variant "blue"', async () => {
const { ListPageHero } = await import('./list-page-hero');
render(
<ListPageHero
title="解决方案"
subtitle="行业解决方案"
badge={{ text: '推荐', variant: 'blue' }}
/>
);
expect(screen.getByText('推荐')).toBeInTheDocument();
});
it('should render with badge variant "green"', async () => {
const { ListPageHero } = await import('./list-page-hero');
render(
<ListPageHero
title="服务"
subtitle="专业服务"
badge={{ text: '热门', variant: 'green' }}
/>
);
expect(screen.getByText('热门')).toBeInTheDocument();
});
it('should render with badge variant "neutral"', async () => {
const { ListPageHero } = await import('./list-page-hero');
render(
<ListPageHero
title="案例"
subtitle="客户案例"
badge={{ text: '案例', variant: 'neutral' }}
/>
);
const neutralBadges = screen.getAllByText('案例');
expect(neutralBadges.length).toBeGreaterThanOrEqual(1);
});
});
-166
View File
@@ -1,166 +0,0 @@
'use client';
import { motion } from 'framer-motion';
import { useReducedMotion } from '@/hooks/use-reduced-motion';
interface ListPageHeroProps {
title: string;
subtitle: string;
description?: string;
stats?: Array<{ value: string; label: string }>;
badge?: {
text: string;
variant?: 'brand' | 'blue' | 'green' | 'neutral';
};
}
const BADGE_VARIANTS = {
brand: {
bg: 'var(--color-brand-bg)',
text: 'var(--color-brand)',
border: 'rgba(var(--color-brand-rgb), 0.15)',
dot: 'var(--color-brand)',
},
blue: {
bg: 'rgba(var(--color-accent-blue-rgb), 0.08)',
text: 'var(--color-accent-blue)',
border: 'rgba(var(--color-accent-blue-rgb), 0.15)',
dot: 'var(--color-accent-blue)',
},
green: {
bg: 'rgba(34, 197, 94, 0.08)',
text: '#16a34a',
border: 'rgba(34, 197, 94, 0.15)',
dot: '#22c55e',
},
neutral: {
bg: 'var(--color-bg-section)',
text: 'var(--color-text-secondary)',
border: 'var(--color-border-primary)',
dot: 'var(--color-text-subtle)',
},
};
export function ListPageHero({
title,
subtitle,
description,
stats,
badge,
}: ListPageHeroProps) {
const shouldReduceMotion = useReducedMotion();
const badgeStyle = BADGE_VARIANTS[badge?.variant || 'brand'];
return (
<section className="relative overflow-hidden">
{/* Multi-layer background */}
<div className="absolute inset-0 bg-gradient-to-br from-[var(--color-bg-section)] via-[var(--color-bg-secondary)] to-[var(--color-bg-section)]" />
<div className="absolute inset-0 bg-[radial-gradient(ellipse_at_top_right,_rgba(var(--color-brand-rgb),_0.05)_0%,_transparent_50%)]" />
<div className="absolute inset-0 bg-[radial-gradient(ellipse_at_bottom_left,_rgba(var(--color-brand-rgb),_0.03)_0%,_transparent_50%)]" />
{/* Subtle grid texture */}
<div
className="absolute inset-0 opacity-[0.03]"
style={{
backgroundImage:
'linear-gradient(rgba(var(--color-border-primary-rgb), 0.5) 1px, transparent 1px), linear-gradient(90deg, rgba(var(--color-border-primary-rgb), 0.5) 1px, transparent 1px)',
backgroundSize: '60px 60px',
}}
aria-hidden="true"
/>
{/* Decorative accent line */}
<div className="absolute top-0 left-0 right-0 h-px" style={{ background: 'linear-gradient(90deg, transparent, var(--color-brand), transparent)' }} aria-hidden="true" />
<div className="container-wide relative z-10 py-20 lg:py-28">
<motion.div
initial={shouldReduceMotion ? {} : { opacity: 0, y: 20 }}
whileInView={{ opacity: 1, y: 0 }}
viewport={{ once: true }}
transition={{ duration: 0.3, ease: [0.16, 1, 0.3, 1] }}
className="max-w-4xl mx-auto text-center"
>
{/* Dynamic Badge */}
{badge && badge.text && (
<motion.div
initial={shouldReduceMotion ? {} : { opacity: 0, scale: 0.95, y: 8 }}
whileInView={{ opacity: 1, scale: 1, y: 0 }}
viewport={{ once: true }}
transition={{ delay: 0.1, duration: 0.3, ease: [0.16, 1, 0.3, 1] }}
className="inline-flex items-center gap-2 px-4 py-1.5 rounded-full text-sm font-medium mb-6 backdrop-blur-sm"
style={{ backgroundColor: badgeStyle.bg, color: badgeStyle.text, border: `1px solid ${badgeStyle.border}` }}
>
<span className="w-2 h-2 rounded-full animate-pulse" style={{ backgroundColor: badgeStyle.dot }} />
{badge?.text || ''}
</motion.div>
)}
{/* Title */}
<motion.h1
initial={shouldReduceMotion ? {} : { opacity: 0, y: 24 }}
whileInView={{ opacity: 1, y: 0 }}
viewport={{ once: true }}
transition={{ delay: 0.15, duration: 0.3, ease: [0.16, 1, 0.3, 1] }}
className="text-4xl md:text-5xl lg:text-6xl font-bold tracking-tight mb-6 text-[var(--color-text-primary)]"
>
{title}
</motion.h1>
{/* Subtitle */}
<motion.p
initial={shouldReduceMotion ? {} : { opacity: 0, y: 20 }}
whileInView={{ opacity: 1, y: 0 }}
viewport={{ once: true }}
transition={{ delay: 0.25, duration: 0.3, ease: [0.16, 1, 0.3, 1] }}
className="text-lg md:text-xl max-w-2xl mx-auto leading-relaxed mb-4 text-[var(--color-text-secondary)]"
>
{subtitle}
</motion.p>
{/* Description */}
{description && (
<motion.p
initial={shouldReduceMotion ? {} : { opacity: 0, y: 18 }}
whileInView={{ opacity: 1, y: 0 }}
viewport={{ once: true }}
transition={{ delay: 0.35, duration: 0.3, ease: [0.16, 1, 0.3, 1] }}
className="text-base max-w-xl mx-auto mb-10 text-[var(--color-text-muted)]"
>
{description}
</motion.p>
)}
{/* Stats Row */}
{stats && stats.length > 0 && (
<motion.div
initial={shouldReduceMotion ? {} : { opacity: 0, y: 24 }}
whileInView={{ opacity: 1, y: 0 }}
viewport={{ once: true }}
transition={{ delay: 0.4, duration: 0.3, ease: [0.16, 1, 0.3, 1] }}
className="flex flex-wrap justify-center gap-8 md:gap-12 mt-12 pt-12 border-t border-[var(--color-border-primary)]"
>
{stats.map((stat, index) => (
<motion.div
key={stat.label}
initial={shouldReduceMotion ? {} : { opacity: 0, scale: 0.95 }}
whileInView={{ opacity: 1, scale: 1 }}
viewport={{ once: true }}
transition={{ delay: 0.5 + index * 0.08, duration: 0.3, ease: [0.16, 1, 0.3, 1] }}
className="text-center min-w-[100px]"
>
<div className="text-3xl md:text-4xl font-bold tracking-tight text-[var(--color-text-primary)]">
{stat.value}
</div>
<div className="text-sm mt-1 text-[var(--color-text-subtle)]">{stat.label}</div>
</motion.div>
))}
</motion.div>
)}
</motion.div>
</div>
{/* Bottom fade */}
<div className="absolute bottom-0 left-0 right-0 h-20 bg-gradient-to-t from-[var(--color-bg-primary)] to-transparent pointer-events-none" aria-hidden="true" />
</section>
);
}
@@ -0,0 +1,30 @@
import { describe, it, expect } from '@jest/globals';
import { render } from '@testing-library/react';
import '@testing-library/jest-dom';
import { PressableButton } from './micro-interactions';
// S-5 回归:带 href 的 PressableButton 必须渲染单个 <a>(可导航),而不是把 <button> 嵌进 <a>
// —— 旧实现 `<a><motion.button/></a>` 是无效交互嵌套,SR 会同时播报「链接 + 按钮」。
// 旧码下 `container.querySelector('button')` 不为 null ⇒ 本用例判红(真判别)。
describe('PressableButton (S-5)', () => {
it('renders a single anchor (no nested button) when href is provided', () => {
const { container } = render(
<PressableButton href="/products/erp" variant="primary">
了解更多
</PressableButton>
);
const anchor = container.querySelector('a[href="/products/erp"]');
expect(anchor).not.toBeNull();
expect(container.querySelector('button')).toBeNull();
});
it('renders a button (not an anchor) when no href is provided', () => {
const { container } = render(
<PressableButton variant="secondary" onClick={() => {}}>
点击
</PressableButton>
);
expect(container.querySelector('button')).not.toBeNull();
expect(container.querySelector('a')).toBeNull();
});
});
+16 -19
View File
@@ -129,31 +129,28 @@ export function PressableButton({
'bg-transparent text-brand-ink hover:bg-brand/5',
};
const content = (
<motion.button
whileHover={{ y: -1 }}
whileTap={{ scale: 0.97, y: 0 }}
transition={{
type: 'spring',
stiffness: 400,
damping: 25,
}}
onClick={onClick}
className={`inline-flex items-center gap-2 px-6 py-3 font-semibold rounded-md transition-all duration-fast ease-standard ${baseStyles[variant]} ${className}`}
>
{children}
</motion.button>
);
const sharedCls = `inline-flex items-center gap-2 px-6 py-3 font-semibold rounded-md transition-all duration-fast ease-standard ${baseStyles[variant]} ${className}`;
const pressMotion = {
whileHover: { y: -1 },
whileTap: { scale: 0.97, y: 0 },
transition: { type: 'spring' as const, stiffness: 400, damping: 25 },
};
// 有 href 时渲染单个 <a>(motion.a),而不是把 <button> 嵌进 <a>——后者是无效交互嵌套,
// 屏幕阅读器会同时播报「链接 + 按钮」两个控件,Enter/Space 激活语义含糊(S-5)。
if (href) {
return (
<a href={href} className="inline-block">
{content}
</a>
<motion.a href={href} onClick={onClick} className={sharedCls} {...pressMotion}>
{children}
</motion.a>
);
}
return content;
return (
<motion.button onClick={onClick} className={sharedCls} {...pressMotion}>
{children}
</motion.button>
);
}
interface HoverLinkProps {
+2 -2
View File
@@ -24,13 +24,13 @@ export function ProductCard({ product }: ProductCardProps) {
whileInView={{ opacity: 1, y: 0 }}
viewport={{ once: true }}
transition={{
duration: 0.3,
duration: 0.28,
ease: [0.22, 1, 0.36, 1] as const,
}}
className="group"
>
<Link href={`/products/${product.id}`} className="block">
<div className="relative h-full rounded-2xl bg-bg-elevated border border-border-primary overflow-hidden hover:border-brand/30 hover:shadow-lg hover:-translate-y-1 transition-all duration-300">
<div className="relative h-full rounded-2xl bg-bg-elevated border border-border-primary overflow-hidden hover:border-brand/30 hover:shadow-lg hover:-translate-y-1 transition-all duration-normal">
<div className="aspect-video relative overflow-hidden bg-bg-secondary">
<Image
src={product.image}
+4 -4
View File
@@ -26,7 +26,7 @@ export function ServiceValueSection({ service }: ServiceValueSectionProps) {
initial={{ opacity: 0, y: 32 }}
whileInView={{ opacity: 1, y: 0 }}
viewport={{ once: true, margin: '-120px' }}
transition={{ duration: 0.3, ease: [0.22, 1, 0.36, 1] }}
transition={{ duration: 0.28, ease: [0.22, 1, 0.36, 1] }}
className="mb-16 sm:mb-20"
>
<div className="flex items-center gap-3 mb-6">
@@ -63,7 +63,7 @@ export function ServiceValueSection({ service }: ServiceValueSectionProps) {
viewport={{ once: true }}
transition={{
delay: index * 0.06,
duration: 0.3,
duration: 0.28,
ease: [0.22, 1, 0.36, 1],
}}
className="bain-card p-6"
@@ -105,7 +105,7 @@ export function ServiceValueSection({ service }: ServiceValueSectionProps) {
viewport={{ once: true }}
transition={{
delay: index * 0.06,
duration: 0.3,
duration: 0.28,
ease: [0.22, 1, 0.36, 1],
}}
className="bain-card p-5 flex items-start gap-3"
@@ -135,7 +135,7 @@ export function ServiceValueSection({ service }: ServiceValueSectionProps) {
viewport={{ once: true }}
transition={{
delay: index * 0.06,
duration: 0.3,
duration: 0.28,
ease: [0.22, 1, 0.36, 1],
}}
className="bain-card p-5"
@@ -37,13 +37,13 @@ export function SolutionCard({ solution }: SolutionCardProps) {
whileInView={{ opacity: 1, y: 0 }}
viewport={{ once: true }}
transition={{
duration: 0.3,
duration: 0.28,
ease: [0.22, 1, 0.36, 1] as const,
}}
className="group"
>
<Link href={`/solutions/${solution.id}`} className="block">
<div className="relative h-full rounded-2xl bg-bg-elevated border border-border-primary overflow-hidden hover:border-brand/30 hover:shadow-lg hover:-translate-y-1 transition-all duration-300">
<div className="relative h-full rounded-2xl bg-bg-elevated border border-border-primary overflow-hidden hover:border-brand/30 hover:shadow-lg hover:-translate-y-1 transition-all duration-normal">
<div className="aspect-video relative overflow-hidden bg-bg-secondary flex items-center justify-center">
{solution.image ? (
<Image
@@ -117,19 +117,19 @@ export function ServiceCard({ service }: ServiceCardProps) {
whileInView={{ opacity: 1, y: 0 }}
viewport={{ once: true }}
transition={{
duration: 0.3,
duration: 0.28,
ease: [0.22, 1, 0.36, 1] as const,
}}
className="group"
>
<Link href={`/services/${service.id}`} className="block">
<div className="relative h-full rounded-2xl bg-bg-secondary border border-border-primary overflow-hidden hover:border-blue-300 hover:shadow-lg hover:-translate-y-1 transition-all duration-300">
<div className="relative h-full rounded-2xl bg-bg-secondary border border-border-primary overflow-hidden hover:border-brand/30 hover:shadow-lg hover:-translate-y-1 transition-all duration-normal">
<div className="p-8">
<div className="w-14 h-14 rounded-2xl bg-gradient-to-br from-[var(--color-accent-blue)] to-[#1d4ed8] flex items-center justify-center mb-5 shadow-md shadow-brand group-hover:scale-110 transition-transform">
<Cpu className="w-7 h-7 text-white" />
<div className="w-14 h-14 rounded-2xl bg-accent-blue-soft flex items-center justify-center mb-5 shadow-sm group-hover:scale-110 transition-transform">
<Cpu className="w-7 h-7 text-accent-blue" />
</div>
<h3 className="text-xl font-bold text-ink mb-3 group-hover:text-blue-600 transition-colors">
<h3 className="text-xl font-bold text-ink mb-3 group-hover:text-brand-ink transition-colors">
{service.title}
</h3>
@@ -142,7 +142,7 @@ export function ServiceCard({ service }: ServiceCardProps) {
{service.features.slice(0, 3).map((feature) => (
<span
key={feature}
className="px-2.5 py-1 rounded-md text-xs font-medium bg-bg-elevated text-blue-600 border border-border-primary"
className="px-2.5 py-1 rounded-md text-xs font-medium bg-bg-elevated text-text-secondary border border-border-primary"
>
{feature.split(':')[0]}
</span>
@@ -150,7 +150,7 @@ export function ServiceCard({ service }: ServiceCardProps) {
</div>
)}
<div className="flex items-center gap-2 text-sm font-semibold text-blue-600 group-hover:gap-3 transition-all">
<div className="flex items-center gap-2 text-sm font-semibold text-brand-ink group-hover:gap-3 transition-all">
了解服务
<ArrowRight className="w-4 h-4" />
</div>
+8 -8
View File
@@ -21,7 +21,7 @@ export function SolutionValueSection({ solution }: SolutionValueSectionProps) {
initial={{ opacity: 0, y: 32 }}
whileInView={{ opacity: 1, y: 0 }}
viewport={{ once: true, margin: '-120px' }}
transition={{ duration: 0.3, ease: [0.22, 1, 0.36, 1] }}
transition={{ duration: 0.28, ease: [0.22, 1, 0.36, 1] }}
className="mb-16 sm:mb-20"
>
<div className="flex items-center gap-3 mb-6">
@@ -45,7 +45,7 @@ export function SolutionValueSection({ solution }: SolutionValueSectionProps) {
initial={{ opacity: 0, x: -30 }}
whileInView={{ opacity: 1, x: 0 }}
viewport={{ once: true, margin: '-80px' }}
transition={{ duration: 0.3, ease: [0.22, 1, 0.36, 1] }}
transition={{ duration: 0.28, ease: [0.22, 1, 0.36, 1] }}
>
<div className="bain-card p-8">
<h3 className="text-xl font-bold text-ink mb-6 flex items-center gap-3">
@@ -63,7 +63,7 @@ export function SolutionValueSection({ solution }: SolutionValueSectionProps) {
viewport={{ once: true }}
transition={{
delay: index * 0.06,
duration: 0.3,
duration: 0.28,
ease: [0.22, 1, 0.36, 1],
}}
className="flex items-start gap-3 text-text-secondary"
@@ -81,7 +81,7 @@ export function SolutionValueSection({ solution }: SolutionValueSectionProps) {
initial={{ opacity: 0, x: 30 }}
whileInView={{ opacity: 1, x: 0 }}
viewport={{ once: true, margin: '-80px' }}
transition={{ duration: 0.3, delay: 0.15, ease: [0.22, 1, 0.36, 1] }}
transition={{ duration: 0.28, delay: 0.15, ease: [0.22, 1, 0.36, 1] }}
>
<div className="bain-card p-8">
<h3 className="text-xl font-bold text-ink mb-6 flex items-center gap-3">
@@ -99,7 +99,7 @@ export function SolutionValueSection({ solution }: SolutionValueSectionProps) {
viewport={{ once: true }}
transition={{
delay: 0.25 + index * 0.08,
duration: 0.3,
duration: 0.28,
ease: [0.22, 1, 0.36, 1],
}}
className="flex items-start gap-3 text-text-secondary"
@@ -119,7 +119,7 @@ export function SolutionValueSection({ solution }: SolutionValueSectionProps) {
initial={{ opacity: 0, y: 32 }}
whileInView={{ opacity: 1, y: 0 }}
viewport={{ once: true, margin: '-80px' }}
transition={{ duration: 0.3, delay: 0.3 }}
transition={{ duration: 0.28, delay: 0.3 }}
>
<div className="mb-12">
<div className="flex items-center gap-3 mb-6">
@@ -142,7 +142,7 @@ export function SolutionValueSection({ solution }: SolutionValueSectionProps) {
viewport={{ once: true }}
transition={{
delay: index * 0.06,
duration: 0.3,
duration: 0.28,
ease: [0.22, 1, 0.36, 1],
}}
className="bain-card p-7"
@@ -164,7 +164,7 @@ export function SolutionValueSection({ solution }: SolutionValueSectionProps) {
initial={{ opacity: 0, y: 32 }}
whileInView={{ opacity: 1, y: 0 }}
viewport={{ once: true, margin: '-80px' }}
transition={{ duration: 0.3, delay: 0.4 }}
transition={{ duration: 0.28, delay: 0.4 }}
className="mt-20"
>
<div className="mb-12">
@@ -1,107 +0,0 @@
'use client';
import { useState } from 'react';
import { trackContactForm } from '@/lib/analytics';
export function ContactFormAnalyticsExample() {
const [formData, setFormData] = useState({
name: '',
email: '',
phone: '',
company: '',
message: ''
});
const handleSubmit = async (e: React.FormEvent) => {
e.preventDefault();
try {
// 追踪表单提交
trackContactForm(formData);
// 提交表单逻辑...
console.log('Form submitted:', formData);
} catch (error) {
console.error('Form submission error:', error);
}
};
return (
<form onSubmit={handleSubmit} className="space-y-4">
<div>
<label htmlFor="name" className="block text-sm font-medium mb-1">
姓名
</label>
<input
id="name"
type="text"
value={formData.name}
onChange={(e) => setFormData({ ...formData, name: e.target.value })}
className="w-full px-3 py-2 border rounded-lg"
required
/>
</div>
<div>
<label htmlFor="email" className="block text-sm font-medium mb-1">
邮箱
</label>
<input
id="email"
type="email"
value={formData.email}
onChange={(e) => setFormData({ ...formData, email: e.target.value })}
className="w-full px-3 py-2 border rounded-lg"
required
/>
</div>
<div>
<label htmlFor="phone" className="block text-sm font-medium mb-1">
电话
</label>
<input
id="phone"
type="tel"
value={formData.phone}
onChange={(e) => setFormData({ ...formData, phone: e.target.value })}
className="w-full px-3 py-2 border rounded-lg"
/>
</div>
<div>
<label htmlFor="company" className="block text-sm font-medium mb-1">
公司
</label>
<input
id="company"
type="text"
value={formData.company}
onChange={(e) => setFormData({ ...formData, company: e.target.value })}
className="w-full px-3 py-2 border rounded-lg"
/>
</div>
<div>
<label htmlFor="message" className="block text-sm font-medium mb-1">
留言内容
</label>
<textarea
id="message"
value={formData.message}
onChange={(e) => setFormData({ ...formData, message: e.target.value })}
className="w-full px-3 py-2 border rounded-lg h-32"
required
/>
</div>
<button
type="submit"
className="w-full bg-blue-600 text-white py-2 px-4 rounded-lg hover:bg-blue-700 transition-colors"
>
提交
</button>
</form>
);
}
+1 -1
View File
@@ -168,7 +168,7 @@ export function Footer() {
</div>
</div>
<div className="border-t border-dark-border pt-6 pb-[calc(8rem+env(safe-area-inset-bottom,0px))] md:pb-8">
<div className="border-t border-dark-border pt-6 pb-8">
<div className="flex flex-col md:flex-row justify-between items-start md:items-center gap-6 mb-6">
<p className="text-dark-text-secondary text-xs">
© {new Date().getFullYear()} {config.name}. 版权所有.
+64 -4
View File
@@ -1,9 +1,10 @@
import { describe, it, expect, jest, beforeEach, afterEach } from '@jest/globals';
import { render, screen, fireEvent, waitFor } from '@testing-library/react';
import { render, screen, fireEvent, waitFor, within, act } from '@testing-library/react';
import '@testing-library/jest-dom';
const mockPush = jest.fn();
const mockReplace = jest.fn();
const mockUseFocusTrap = jest.fn((_isActive: boolean, _options?: unknown) => ({ current: null }));
jest.mock('next/navigation', () => ({
usePathname: jest.fn(() => '/'),
@@ -128,7 +129,7 @@ jest.mock('@/lib/constants', () => ({
}));
jest.mock('@/hooks/use-focus-trap', () => ({
useFocusTrap: () => ({ current: null }),
useFocusTrap: (isActive: boolean, options?: unknown) => mockUseFocusTrap(isActive, options),
}));
jest.mock('@/components/layout/mega-dropdown', () => ({
@@ -236,12 +237,71 @@ describe('Header', () => {
it('should have proper ARIA attributes on menu button', () => {
render(<Header />);
const menuButton = screen.getByTestId('mobile-menu-button');
expect(menuButton).toHaveAttribute('aria-expanded', 'false');
expect(menuButton).toHaveAttribute('aria-controls', 'mobile-menu');
expect(menuButton).toHaveAttribute('aria-label', '打开菜单');
});
it('should not expose a dangling aria-controls target while the drawer is closed', () => {
render(<Header />);
const menuButton = screen.getByTestId('mobile-menu-button');
// aria-controls 指向只存在于 {isOpen && …} 内的 id;关闭时必须撤掉,
// 否则 AT 解析到一个不存在的节点。
expect(menuButton).not.toHaveAttribute('aria-controls');
expect(document.getElementById('mobile-menu')).toBeNull();
});
it('should point aria-controls at a real element once the drawer is open', async () => {
render(<Header />);
const menuButton = screen.getByTestId('mobile-menu-button');
fireEvent.click(menuButton);
await waitFor(() => {
expect(menuButton).toHaveAttribute('aria-controls', 'mobile-menu');
});
const target = document.getElementById(menuButton.getAttribute('aria-controls') as string);
expect(target).not.toBeNull();
expect(target).toBe(screen.getByTestId('mobile-navigation'));
});
it('should hand Escape back to the drawer owner through useFocusTrap onEscape', async () => {
render(<Header />);
const menuButton = screen.getByTestId('mobile-menu-button');
fireEvent.click(menuButton);
await waitFor(() => {
expect(screen.getByTestId('mobile-navigation')).toBeInTheDocument();
});
const options = mockUseFocusTrap.mock.calls
.map((call) => call[1] as { onEscape?: () => void } | undefined)
.find((call) => typeof call?.onEscape === 'function');
expect(options?.onEscape).toBeInstanceOf(Function);
// 焦点归还/关闭由调用方决定:onEscape 必须真的关闭抽屉。
act(() => {
options?.onEscape?.();
});
await waitFor(() => {
expect(screen.queryByTestId('mobile-navigation')).not.toBeInTheDocument();
});
});
it('should render the theme toggle inside the mobile drawer with a >=44px target', async () => {
render(<Header />);
fireEvent.click(screen.getByTestId('mobile-menu-button'));
await waitFor(() => {
expect(screen.getByTestId('mobile-navigation')).toBeInTheDocument();
});
const drawer = screen.getByTestId('mobile-navigation');
const toggle = within(drawer).getByTestId('theme-toggle');
// w-11 / h-11 = 2.75rem = 44px(Tailwind 默认刻度)
expect(toggle).toHaveClass('w-11');
expect(toggle).toHaveClass('h-11');
});
it('should update aria-expanded when menu is toggled', async () => {
render(<Header />);
const menuButton = screen.getByTestId('mobile-menu-button');
+20 -11
View File
@@ -18,7 +18,9 @@ function HeaderContent() {
const [isScrolled, setIsScrolled] = useState(false);
const [openDropdown, setOpenDropdown] = useState<string | null>(null);
const pathname = usePathname();
const focusTrapRef = useFocusTrap<HTMLDivElement>(isOpen);
const focusTrapRef = useFocusTrap<HTMLDivElement>(isOpen, {
onEscape: () => setIsOpen(false),
});
useEffect(() => {
const handleScroll = () => {
@@ -86,8 +88,8 @@ function HeaderContent() {
animate={{
height: isScrolled ? 64 : 80,
}}
transition={{ duration: 0.3, ease: [0.22, 1, 0.36, 1] }}
className="fixed top-0 left-0 right-0 z-50 transition-colors duration-300 bg-bg-primary border-b border-border-primary"
transition={{ duration: 0.28, ease: [0.22, 1, 0.36, 1] }}
className="fixed top-0 left-0 right-0 z-50 transition-colors duration-normal bg-bg-primary border-b border-border-primary"
>
<div className="max-w-container mx-auto px-4 sm:px-6 lg:px-10">
<div className="flex items-center justify-between h-16 md:h-full">
@@ -103,7 +105,7 @@ function HeaderContent() {
alt={config.name}
width={160}
height={40}
className="logo-on-light relative transition-all duration-300 ease-out group-hover/logo:scale-[1.02] w-auto h-8 md:h-10"
className="logo-on-light relative transition-all duration-normal ease-out group-hover/logo:scale-[1.02] w-auto h-8 md:h-10"
loading="eager"
priority
suppressHydrationWarning
@@ -113,7 +115,7 @@ function HeaderContent() {
alt={config.name}
width={160}
height={40}
className="logo-on-dark relative transition-all duration-300 ease-out group-hover/logo:scale-[1.02] w-auto h-8 md:h-10"
className="logo-on-dark relative transition-all duration-normal ease-out group-hover/logo:scale-[1.02] w-auto h-8 md:h-10"
loading="eager"
suppressHydrationWarning
/>
@@ -141,7 +143,7 @@ function HeaderContent() {
onClick={handleNavClick}
className={cn(
'relative inline-flex items-center px-3 py-2 text-sm font-medium',
'transition-all duration-300 ease-out',
'transition-all duration-normal ease-out',
isActive(item)
? 'text-text-primary'
: 'text-text-secondary hover:text-text-primary hover:bg-bg-secondary'
@@ -152,7 +154,7 @@ function HeaderContent() {
<span
className={cn(
'absolute -bottom-0.5 left-3 right-3 h-0.5 bg-brand',
'transition-all duration-300 ease-out',
'transition-all duration-normal ease-out',
isActive(item)
? 'opacity-100 scale-x-100'
: 'opacity-0 scale-x-0'
@@ -180,11 +182,12 @@ function HeaderContent() {
</div>
<button
className="md:hidden p-2 -mr-2 text-text-secondary hover:text-text-primary hover:bg-bg-secondary rounded-sm transition-all duration-300 ease-out active:scale-95"
onClick={() => setIsOpen(!isOpen)}
className="md:hidden p-2 -mr-2 text-text-secondary hover:text-text-primary hover:bg-bg-secondary rounded-sm transition-all duration-normal ease-out active:scale-95"
onClick={() => setIsOpen((prev) => !prev)}
onKeyDown={handleKeyDown}
aria-expanded={isOpen}
aria-controls="mobile-menu"
/* 面板仅在 isOpen 时挂载:关闭时不给 aria-controls,避免指向不存在的 id。 */
aria-controls={isOpen ? 'mobile-menu' : undefined}
aria-label={isOpen ? '关闭菜单' : '打开菜单'}
data-testid="mobile-menu-button"
style={{ minWidth: '44px', minHeight: '44px' }}
@@ -221,6 +224,12 @@ function HeaderContent() {
aria-label="移动端导航"
data-testid="mobile-navigation"
>
{/* 桌面端 ThemeToggle 在 `hidden md:flex` 容器内,移动端只有抽屉可达;
w-11 h-11 = 44px,满足触摸目标下限。放在 nav 之外,避免混入导航链接列表。 */}
<div className="max-w-container mx-auto px-4 sm:px-6 pt-6 flex items-center justify-between">
<span className="text-sm text-text-secondary">外观主题</span>
<ThemeToggle className="w-11 h-11" />
</div>
<nav className="max-w-container mx-auto px-4 sm:px-6 py-6">
{config.mainNav.map((item, index) => (
<motion.div
@@ -234,7 +243,7 @@ function HeaderContent() {
onClick={handleNavClick}
className={`
block px-4 py-4 text-base font-medium
transition-all duration-300 ease-out
transition-all duration-normal ease-out
${isActive(item)
? 'text-text-primary bg-bg-secondary'
: 'text-text-secondary hover:text-text-primary hover:bg-bg-secondary'
-7
View File
@@ -1,7 +0,0 @@
export { Header } from './header';
export { Footer } from './footer';
export { Breadcrumb } from './breadcrumb';
export { MobileTabBar } from './mobile-tab-bar';
export { MegaDropdown } from './mega-dropdown';
export { PageNav } from './page-nav';
export { ClientLayout } from './client-layout';
@@ -0,0 +1,88 @@
import { describe, it, expect, jest, beforeEach } from '@jest/globals';
import { render, screen, fireEvent } from '@testing-library/react';
import '@testing-library/jest-dom';
import { MegaDropdown } from './mega-dropdown';
import type { MegaDropdownGroup } from '@/lib/site-config';
jest.mock('framer-motion', () => ({
motion: {
div: ({ children, className, ...props }: { children: React.ReactNode; className?: string; [key: string]: unknown }) => (
<div className={className} {...props}>
{children}
</div>
),
},
AnimatePresence: ({ children }: { children: React.ReactNode }) => <>{children}</>,
}));
jest.mock('@/components/ui/static-link', () => {
const MockStaticLink = ({ children, href, ...props }: { children: React.ReactNode; href: string; [key: string]: unknown }) => (
<a href={href} {...props}>
{children}
</a>
);
MockStaticLink.displayName = 'MockStaticLink';
return { StaticLink: MockStaticLink };
});
const GROUPS: MegaDropdownGroup[] = [
{
id: 'enterprise',
title: '企业套装',
items: [{ id: 'erp', title: 'ERP', description: '企业资源计划', href: '/products/erp' }],
},
];
function renderDropdown(overrides: Partial<Parameters<typeof MegaDropdown>[0]> = {}) {
const props = {
label: '产品',
groups: GROUPS,
isOpen: true,
onToggle: jest.fn(),
onOpen: jest.fn(),
onClose: jest.fn(),
...overrides,
};
render(<MegaDropdown {...props} />);
return props;
}
describe('MegaDropdown 键盘可达性(验收 B-10)', () => {
beforeEach(() => {
jest.clearAllMocks();
});
it('Escape 关闭面板并把焦点交还触发按钮', () => {
const props = renderDropdown();
const trigger = screen.getByRole('button', { name: /产品/ });
trigger.focus();
fireEvent.keyDown(trigger, { key: 'Escape' });
expect(props.onClose).toHaveBeenCalledTimes(1);
expect(trigger).toHaveFocus();
});
it('面板内的链接上按 Escape 同样关闭', () => {
const props = renderDropdown();
fireEvent.keyDown(screen.getByRole('link', { name: /ERP/ }), { key: 'Escape' });
expect(props.onClose).toHaveBeenCalledTimes(1);
});
it('面板未打开时 Escape 不触发关闭', () => {
const props = renderDropdown({ isOpen: false });
fireEvent.keyDown(screen.getByRole('button', { name: /产品/ }), { key: 'Escape' });
expect(props.onClose).not.toHaveBeenCalled();
});
it('焦点移出容器时关闭,容器内部移动不关闭', () => {
const props = renderDropdown();
const trigger = screen.getByRole('button', { name: /产品/ });
fireEvent.blur(trigger, { relatedTarget: trigger });
expect(props.onClose).not.toHaveBeenCalled();
fireEvent.blur(trigger, { relatedTarget: document.body });
expect(props.onClose).toHaveBeenCalledTimes(1);
});
});
+29 -5
View File
@@ -1,6 +1,6 @@
'use client';
import { useRef, useEffect } from 'react';
import { useRef, useEffect, type KeyboardEvent, type FocusEvent } from 'react';
import { ChevronDown, Lock, Sparkles } from 'lucide-react';
import { StaticLink } from '@/components/ui/static-link';
import { AnimatePresence, motion } from 'framer-motion';
@@ -18,6 +18,7 @@ interface MegaDropdownProps {
export function MegaDropdown({ label, groups, isOpen, isActive, onToggle, onOpen, onClose }: MegaDropdownProps) {
const dropdownRef = useRef<HTMLDivElement>(null);
const triggerRef = useRef<HTMLButtonElement>(null);
const timeoutRef = useRef<ReturnType<typeof setTimeout>>(undefined);
const handleMouseEnter = () => {
@@ -29,18 +30,41 @@ export function MegaDropdown({ label, groups, isOpen, isActive, onToggle, onOpen
timeoutRef.current = setTimeout(onClose, 300);
};
// 键盘与无指针设备(验收 B-10):Escape 关闭并把焦点还给触发按钮;
// 焦点移出整个下拉容器时关闭,否则面板会以「看不见但仍在 DOM 里」的状态滞留。
const handleKeyDown = (event: KeyboardEvent<HTMLDivElement>) => {
if (event.key !== 'Escape' || !isOpen) return;
event.stopPropagation();
onClose();
triggerRef.current?.focus();
};
const handleBlur = (event: FocusEvent<HTMLDivElement>) => {
if (!isOpen) return;
if (event.relatedTarget instanceof Node && event.currentTarget.contains(event.relatedTarget)) return;
onClose();
};
useEffect(() => {
return () => clearTimeout(timeoutRef.current);
}, []);
return (
<div ref={dropdownRef} className="relative" onMouseEnter={handleMouseEnter} onMouseLeave={handleMouseLeave}>
<div
ref={dropdownRef}
className="relative"
onMouseEnter={handleMouseEnter}
onMouseLeave={handleMouseLeave}
onKeyDown={handleKeyDown}
onBlur={handleBlur}
>
<div className="-mx-2 px-2 py-2">
<button
ref={triggerRef}
onClick={onToggle}
className={`
relative flex items-center gap-1 px-3 py-2 text-sm font-medium
transition-all duration-300 ease-out
transition-all duration-normal ease-out
${isOpen || isActive
? 'text-text-primary'
: 'text-text-secondary hover:text-text-primary hover:bg-bg-secondary'
@@ -57,7 +81,7 @@ export function MegaDropdown({ label, groups, isOpen, isActive, onToggle, onOpen
<span
className={`
absolute -bottom-0.5 left-3 right-3 h-0.5 bg-brand
transition-all duration-300 ease-out
transition-all duration-normal ease-out
${isActive
? 'opacity-100 scale-x-100'
: 'opacity-0 scale-x-0'
@@ -129,7 +153,7 @@ export function MegaDropdown({ label, groups, isOpen, isActive, onToggle, onOpen
<StaticLink
key={item.id}
href={item.href}
className="block p-3 border border-transparent transition-all duration-300 ease-out group hover:border-border-primary hover:bg-bg-secondary"
className="block p-3 border border-transparent transition-all duration-normal ease-out group hover:border-border-primary hover:bg-bg-secondary"
>
{content}
</StaticLink>
+2 -2
View File
@@ -54,13 +54,13 @@ export function MobileTabBar() {
<div className="relative flex flex-col items-center justify-center py-2">
<Icon
className={cn(
'w-6 h-6 transition-colors duration-300',
'w-6 h-6 transition-colors duration-normal',
active ? 'text-brand-ink' : 'text-text-muted group-hover:text-text-secondary'
)}
/>
<span
className={cn(
'text-xs mt-1 transition-colors duration-300',
'text-xs mt-1 transition-colors duration-normal',
active ? 'text-brand-ink font-medium' : 'text-text-muted'
)}
>
-43
View File
@@ -1,43 +0,0 @@
'use client';
import { StaticLink } from '@/components/ui/static-link';
import { ChevronRight, Home } from 'lucide-react';
interface BreadcrumbItem {
label: string;
href?: string;
}
interface PageNavProps {
items: BreadcrumbItem[];
}
export function PageNav({ items }: PageNavProps) {
return (
<nav aria-label="breadcrumb" className="flex items-center gap-[3px] md:gap-1 text-[11px] md:text-sm text-[var(--color-text-subtle)] mb-2 md:mb-8 -ml-0.5">
<StaticLink href="/" className="flex items-center w-fit hover:text-[var(--color-brand)] transition-colors" aria-label="返回首页">
<Home className="w-2.5 h-2.5 md:w-3.5 md:h-3.5" />
</StaticLink>
{items.map((item, index) => {
const isLast = index === items.length - 1;
return (
<div key={index} className="flex items-center gap-[3px] md:gap-1">
<ChevronRight className="w-2.5 h-2.5 md:w-3.5 md:h-3.5 text-[var(--color-border-secondary)]" />
{isLast || !item.href ? (
<span className={isLast ? 'text-[var(--color-text-primary)] font-medium' : ''}>
{item.label}
</span>
) : (
<StaticLink
href={item.href}
className="hover:text-[var(--color-brand)] transition-colors"
>
{item.label}
</StaticLink>
)}
</div>
);
})}
</nav>
);
}
+1 -1
View File
@@ -103,7 +103,7 @@ export function CaseCard({
{/* Impact numbers — Results (Bain-style, most visual weight) */}
<div className="grid grid-cols-2 gap-4 sm:gap-6 pt-5 md:pt-7 mb-5 md:mb-7 border-t border-[var(--color-border-primary)]">
{impact.map((item, i) => (
<div key={i} className="transition-transform duration-300 group-hover:scale-[1.02]">
<div key={i} className="transition-transform duration-normal group-hover:scale-[1.02]">
<div className="font-sans tabular-nums text-[32px] sm:text-[38px] md:text-[42px] font-bold leading-none mb-1 md:mb-1.5 tracking-[-1.5px] text-[var(--color-text-primary)]">
{item.value}
</div>
@@ -0,0 +1,529 @@
import { describe, it, expect, jest, beforeEach } from "@jest/globals";
import { createElement } from "react";
import {
render,
screen,
within,
act,
type RenderResult,
} from "@testing-library/react";
import "@testing-library/jest-dom";
import CaseDetailPage, { type CaseDetailData } from "./case-detail-page";
// ─── Mocks ───────────────────────────────────────────────────────────────
// motion 的 style 上挂的是 MotionValue,jsdom 无法求值:useTransform 降级为普通数值,
// 断言只落在「解析出的数据」与「条件渲染结果」上,不依赖动画实现。
jest.mock("framer-motion", () => {
// 动画专属 props 落在 DOM 上只会让 React 报未知属性,且 jsdom 无法求值:统一剔除,只保留结构相关属性
const animationOnly = [
"initial",
"animate",
"exit",
"variants",
"whileInView",
"viewport",
"transition",
"whileHover",
"whileTap",
"layout",
];
const motionTag =
(tag: string, testId: string) =>
({ children, ...rest }: any) => {
for (const key of animationOnly) delete rest[key];
return createElement(tag, { "data-testid": testId, ...rest }, children);
};
return {
motion: {
div: motionTag("div", "motion-div"),
h1: motionTag("h1", "motion-h1"),
h2: motionTag("h2", "motion-h2"),
p: motionTag("p", "motion-p"),
span: motionTag("span", "motion-span"),
},
useInView: jest.fn(() => true),
useScroll: jest.fn(() => ({ scrollYProgress: { get: () => 0 } })),
useTransform: jest.fn(() => 1),
AnimatePresence: ({ children }: any) => <>{children}</>,
};
});
jest.mock("@/hooks/use-reduced-motion", () => ({
useReducedMotion: jest.fn(() => false),
}));
jest.mock("@/components/ui/scroll-reveal", () => ({
ScrollReveal: ({ children, className }: any) => (
<div data-testid="scroll-reveal" className={className}>
{children}
</div>
),
StaggerReveal: ({ children, className }: any) => (
<div data-testid="stagger-reveal" className={className}>
{children}
</div>
),
}));
jest.mock("@/components/ui/static-link", () => ({
StaticLink: ({ children, href, className, onClick, ...props }: any) => (
<a
href={href}
className={className}
onClick={onClick}
data-testid="static-link"
{...props}
>
{children}
</a>
),
}));
jest.mock("@/components/ui/button", () => ({
Button: ({ children, size, variant }: any) => (
<span data-testid="mock-button" data-size={size} data-variant={variant}>
{children}
</span>
),
}));
jest.mock("next/link", () => ({
__esModule: true,
default: ({ children, href, className, ...props }: any) => (
<a href={href} className={className} data-testid="next-link" {...props}>
{children}
</a>
),
}));
// 计数器在这里只需要证明「数字被正确拆成 value + suffix + 小数位」,动画本身归 ui 层用例
jest.mock("@/components/ui/animated-counter", () => ({
AnimatedCounter: ({ value, decimals, suffix }: any) => (
<span
data-testid="animated-counter"
data-value={value}
data-decimals={decimals}
data-suffix={suffix}
>
{`${value}${suffix}`}
</span>
),
}));
// ─── Test Data ───────────────────────────────────────────────────────────
const baseData: CaseDetailData = {
id: "c1",
client: "华东某连锁零售",
industry: "零售",
title: "全渠道库存中台重构",
subtitle: "把 12 个系统的库存数据收敛成一份真相",
challenge: "多仓多店库存不互通,超卖频发",
solution: "统一库存域模型 + 实时对账链路",
result: "上线一个季度后超卖归零",
metrics: [
{ value: "40%", label: "库存周转提升" },
{ value: "99.9%", label: "系统可用率", highlight: true },
{ value: "12", label: "接入系统数" },
{ value: "3 座", label: "覆盖仓数" },
{ value: "8 步", label: "未被选中的第五项" },
],
timeline: [
{
phase: "现状盘点",
duration: "2 周",
description: "梳理库存口径与主数据来源",
},
{ phase: "模型重构", duration: "6 周", description: "落地统一库存域模型" },
],
services: [
{ id: "consulting", title: "战略咨询", description: "业务诊断" },
{ id: "data", title: "数据治理", description: "口径统一" },
{ id: "delivery", title: "敏捷交付", description: "系统建设" },
{ id: "support", title: "长期陪跑", description: "运营支持" },
],
testimonial: {
quote: "超卖问题彻底消失了",
author: "李总",
role: "供应链负责人",
},
projectDuration: "16 周",
departments: ["供应链", "电商", "财务"],
dataScale: "日均 200 万行",
businessProblem: "库存真相分散在 12 个系统里",
verified: true,
};
// 页面结构固定为 6 个并列 section,按文档顺序取用即可隔离同名文案
const SECTION = {
hero: 0,
challenge: 1,
solution: 2,
results: 3,
related: 4,
cta: 5,
} as const;
function section(view: RenderResult, which: number): HTMLElement {
const el = Array.from(view.container.querySelectorAll("section"))[which];
if (!el) throw new Error(`第 ${which} 个 section 未渲染`);
return el;
}
function reduced(v: boolean) {
const { useReducedMotion } = require("@/hooks/use-reduced-motion");
(useReducedMotion as jest.Mock).mockReturnValue(v);
}
beforeEach(() => {
reduced(false);
});
// ─── Hero ────────────────────────────────────────────────────────────────
describe("CaseDetailPage · Hero", () => {
it("leads with industry, client, the first metric and the H1 title", () => {
const view = render(<CaseDetailPage data={baseData} />);
const hero = within(section(view, SECTION.hero));
expect(hero.getByText("零售")).toBeInTheDocument();
expect(hero.getByText("华东某连锁零售")).toBeInTheDocument();
expect(hero.getByText("40%")).toBeInTheDocument();
expect(
hero.getByText("把 12 个系统的库存数据收敛成一份真相"),
).toBeInTheDocument();
expect(hero.getByRole("heading", { level: 1 })).toHaveTextContent(
"全渠道库存中台重构",
);
});
it("shows only metrics 2-4 in the quick stats row and brand-reds the highlighted one", () => {
const view = render(<CaseDetailPage data={baseData} />);
const hero = within(section(view, SECTION.hero));
expect(hero.getByText("99.9%")).toBeInTheDocument();
expect(hero.getByText("12")).toBeInTheDocument();
expect(hero.getByText("3 座")).toBeInTheDocument();
expect(hero.queryByText("8 步")).not.toBeInTheDocument();
// highlight 决定数字用品牌红还是正文色(CSS 变量原样透传,不做解析)
const brand = Array.from(
section(view, SECTION.hero).querySelectorAll(
'[style*="var(--color-brand)"]',
),
);
expect(brand.filter((n) => n.textContent === "99.9%")).toHaveLength(1);
expect(brand.some((n) => n.textContent === "3 座")).toBe(false);
});
it("无 metrics 时不编造成果数字(N-30:原实现兜底渲染 40% / 核心成果提升)", () => {
const view = render(<CaseDetailPage data={{ ...baseData, metrics: [] }} />);
const hero = within(section(view, SECTION.hero));
// AGENTS.md §3「零编造」:页面上出现的具体百分比必须来自数据本身。
expect(hero.queryByText("40%")).toBeNull();
expect(hero.queryByText("核心成果提升")).toBeNull();
// 快照区仍在结构里,但没有一张数据卡
expect(
section(view, SECTION.hero).querySelector('[class*="grid-cols-3"]')
?.children,
).toHaveLength(0);
});
it("renders every verifiable dimension with departments joined by 、", () => {
const view = render(<CaseDetailPage data={baseData} />);
const hero = within(section(view, SECTION.hero));
expect(hero.getByText("项目周期")).toBeInTheDocument();
expect(hero.getByText("16 周")).toBeInTheDocument();
expect(hero.getByText("涉及部门")).toBeInTheDocument();
expect(hero.getByText("供应链、电商、财务")).toBeInTheDocument();
expect(hero.getByText("数据规模")).toBeInTheDocument();
expect(hero.getByText("日均 200 万行")).toBeInTheDocument();
expect(hero.getByText("✓ 客户授权公开")).toBeInTheDocument();
});
it("hides each dimension whose data is missing, empty or false", () => {
const view = render(
<CaseDetailPage
data={{
...baseData,
projectDuration: undefined,
departments: [],
dataScale: undefined,
verified: false,
}}
/>,
);
const hero = within(section(view, SECTION.hero));
expect(hero.queryByText("项目周期")).not.toBeInTheDocument();
expect(hero.queryByText("涉及部门")).not.toBeInTheDocument();
expect(hero.queryByText("数据规模")).not.toBeInTheDocument();
expect(hero.queryByText("✓ 客户授权公开")).not.toBeInTheDocument();
});
it("drops only the dimensions that are absent instead of the whole row", () => {
const view = render(
<CaseDetailPage
data={{
...baseData,
departments: ["供应链"],
projectDuration: undefined,
}}
/>,
);
const hero = within(section(view, SECTION.hero));
expect(hero.queryByText("项目周期")).not.toBeInTheDocument();
expect(hero.getByText("供应链")).toBeInTheDocument();
expect(hero.getByText("数据规模")).toBeInTheDocument();
});
it("offers the consult CTA and an in-page anchor to the solution", () => {
const view = render(<CaseDetailPage data={baseData} />);
const hero = within(section(view, SECTION.hero));
expect(hero.getByText("预约咨询")).toBeInTheDocument();
expect(hero.getByRole("link", { name: "查看方案" })).toHaveAttribute(
"href",
"#solution",
);
});
});
// ─── 挑战 / 方案 ─────────────────────────────────────────────────────────
describe("CaseDetailPage · 挑战与方案", () => {
it("puts the concrete business problem above the challenge statement", () => {
const view = render(<CaseDetailPage data={baseData} />);
const challenge = within(section(view, SECTION.challenge));
expect(challenge.getByText("具体业务问题")).toBeInTheDocument();
expect(
challenge.getByText("库存真相分散在 12 个系统里"),
).toBeInTheDocument();
expect(challenge.getByText("面临的挑战")).toBeInTheDocument();
expect(
challenge.getByText("多仓多店库存不互通,超卖频发"),
).toBeInTheDocument();
});
it("drops the business problem block when the case has none", () => {
const view = render(
<CaseDetailPage data={{ ...baseData, businessProblem: undefined }} />,
);
const challenge = within(section(view, SECTION.challenge));
expect(challenge.queryByText("具体业务问题")).not.toBeInTheDocument();
expect(
challenge.getByText("多仓多店库存不互通,超卖频发"),
).toBeInTheDocument();
});
it("numbers the implementation path steps in order", () => {
const view = render(<CaseDetailPage data={baseData} />);
const solution = within(section(view, SECTION.solution));
expect(
solution.getByText("统一库存域模型 + 实时对账链路"),
).toBeInTheDocument();
expect(solution.getByText("现状盘点")).toBeInTheDocument();
expect(solution.getByText("梳理库存口径与主数据来源")).toBeInTheDocument();
expect(solution.getByText("落地统一库存域模型")).toBeInTheDocument();
expect(solution.getByText("2 周")).toBeInTheDocument();
expect(solution.getByText("6 周")).toBeInTheDocument();
expect(solution.getAllByText(/^[12]$/).map((n) => n.textContent)).toEqual([
"1",
"2",
]);
});
it("keeps the 实施路径 heading when the timeline is empty", () => {
const view = render(
<CaseDetailPage data={{ ...baseData, timeline: [] }} />,
);
const solution = within(section(view, SECTION.solution));
expect(solution.getByText("实施路径")).toBeInTheDocument();
expect(solution.queryByText("现状盘点")).not.toBeInTheDocument();
});
});
// ─── 成果 ────────────────────────────────────────────────────────────────
describe("CaseDetailPage · 成果", () => {
it("counts up the first four metrics, splitting value into number and suffix", () => {
const view = render(<CaseDetailPage data={baseData} />);
const results = within(section(view, SECTION.results));
const counters = results.getAllByTestId("animated-counter");
expect(counters).toHaveLength(4); // 第五项被 slice(0, 4) 截断
expect(counters.some((c) => c.textContent === "8 步")).toBe(false);
const ninetyNine = counters.find((c) => c.textContent === "99.9%");
expect(ninetyNine).toHaveAttribute("data-value", "99.9");
expect(ninetyNine).toHaveAttribute("data-decimals", "1");
const forty = counters.find((c) => c.textContent === "40%");
expect(forty).toHaveAttribute("data-value", "40");
expect(forty).toHaveAttribute("data-decimals", "0");
const plain = counters.find((c) => c.textContent === "12");
expect(plain).toHaveAttribute("data-suffix", "");
expect(counters.find((c) => c.textContent === "3 座")).toHaveAttribute(
"data-suffix",
" 座",
);
expect(results.getByText("可量化的业务成果")).toBeInTheDocument();
expect(results.getByText("上线一个季度后超卖归零")).toBeInTheDocument();
});
it("keeps a non-numeric metric verbatim instead of animating it", () => {
const view = render(
<CaseDetailPage
data={{
...baseData,
metrics: [
{ value: "N/A", label: "未量化" },
...baseData.metrics.slice(1),
],
}}
/>,
);
const results = within(section(view, SECTION.results));
expect(results.getByText("N/A")).toBeInTheDocument();
expect(results.getAllByTestId("animated-counter")).toHaveLength(3);
});
it("badges the highlighted metric as the core indicator", () => {
const view = render(<CaseDetailPage data={baseData} />);
const results = within(section(view, SECTION.results));
expect(results.getAllByText("核心指标")).toHaveLength(1);
});
it("renders no badge when no metric is highlighted", () => {
const view = render(
<CaseDetailPage
data={{
...baseData,
metrics: baseData.metrics.map((m) => ({ ...m, highlight: false })),
}}
/>,
);
expect(
within(section(view, SECTION.results)).queryByText("核心指标"),
).not.toBeInTheDocument();
});
it("renders the customer quote with author and role", () => {
const view = render(<CaseDetailPage data={baseData} />);
const results = within(section(view, SECTION.results));
expect(results.getByRole("blockquote")).toHaveTextContent(
"超卖问题彻底消失了",
);
expect(results.getByText("李总")).toBeInTheDocument();
expect(results.getByText("供应链负责人")).toBeInTheDocument();
});
it("omits the whole testimonial block when the case has none", () => {
const view = render(
<CaseDetailPage data={{ ...baseData, testimonial: undefined }} />,
);
expect(
within(section(view, SECTION.results)).queryByRole("blockquote"),
).not.toBeInTheDocument();
});
it("renders static numbers instead of the counter under reduced motion", () => {
reduced(true);
const view = render(<CaseDetailPage data={baseData} />);
const results = within(section(view, SECTION.results));
expect(results.queryByTestId("animated-counter")).not.toBeInTheDocument();
expect(results.getByText("99.9")).toBeInTheDocument();
expect(results.getByText("40")).toBeInTheDocument();
// 后缀被拆成独立的小号 span:40% 与 99.9% 各一个,'12' 无后缀不产生
expect(results.getAllByText("%")).toHaveLength(2);
expect(results.getByText("3")).toBeInTheDocument();
expect(results.getByText("座")).toBeInTheDocument();
});
it("starts the counters only when the results block actually enters the viewport", () => {
// 全局 IntersectionObserver 桩恒定报 isIntersecting: true,这里换成手动触发的桩以覆盖「未进入视口」与「进入后即停止观察」
const NativeIO = global.IntersectionObserver;
const observers: StubIO[] = [];
class StubIO {
targets: Element[] = [];
disconnected = false;
constructor(
private readonly cb: (
entries: Array<{ isIntersecting: boolean }>,
obs: StubIO,
) => void,
) {
observers.push(this);
}
observe(el: Element) {
this.targets.push(el);
}
unobserve() {}
disconnect() {
this.disconnected = true;
}
fire(entries: Array<{ isIntersecting: boolean }>) {
this.cb(entries, this);
}
}
global.IntersectionObserver =
StubIO as unknown as typeof IntersectionObserver;
const view = render(<CaseDetailPage data={baseData} />);
try {
const results = within(section(view, SECTION.results));
expect(observers).toHaveLength(1);
expect(observers[0]!.targets).toHaveLength(1);
// 视口外:数字保持解析后的原值,计数器不挂载
expect(results.queryByTestId("animated-counter")).not.toBeInTheDocument();
expect(results.getByText("99.9")).toBeInTheDocument();
// 回传空列表 / isIntersecting 为 false 都不能提前点亮计数器
observers[0]!.fire([]);
act(() => observers[0]!.fire([{ isIntersecting: false }]));
expect(results.queryByTestId("animated-counter")).not.toBeInTheDocument();
expect(observers[0]!.disconnected).toBe(false);
act(() => observers[0]!.fire([{ isIntersecting: true }]));
expect(results.getAllByTestId("animated-counter")).toHaveLength(4);
expect(observers[0]!.disconnected).toBe(true); // 只观察一次
} finally {
global.IntersectionObserver = NativeIO; // 卸载留给 RTL 自动 cleanup,effect 清的是实例本身
}
});
});
// ─── 相关服务 / CTA ──────────────────────────────────────────────────────
describe("CaseDetailPage · 相关服务与 CTA", () => {
it("lists at most three related services linked by id", () => {
const view = render(<CaseDetailPage data={baseData} />);
const related = within(section(view, SECTION.related));
const links = related.getAllByTestId("next-link");
expect(links).toHaveLength(3);
expect(links.map((l) => l.getAttribute("href"))).toEqual([
"/services/consulting",
"/services/data",
"/services/delivery",
]);
expect(related.getByText("战略咨询")).toBeInTheDocument();
expect(related.queryByText("长期陪跑")).not.toBeInTheDocument();
});
it("renders an empty service grid when the case declares no services", () => {
const view = render(
<CaseDetailPage data={{ ...baseData, services: [] }} />,
);
const related = within(section(view, SECTION.related));
expect(related.getByText("相关")).toBeInTheDocument();
expect(related.queryAllByTestId("next-link")).toHaveLength(0);
});
it("closes with the two conversion links and the shared CTA label", () => {
const view = render(<CaseDetailPage data={baseData} />);
const cta = within(section(view, SECTION.cta));
const links = cta.getAllByTestId("static-link");
expect(links.map((a) => a.getAttribute("href"))).toEqual([
"/contact",
"/cases",
]);
expect(cta.getByText("预约咨询")).toBeInTheDocument();
expect(cta.getByText("查看更多案例")).toBeInTheDocument();
});
it("does not mount its own reading-progress bar(P-4:全站唯一实例归 layout)", () => {
render(<CaseDetailPage data={baseData} />);
expect(screen.queryByTestId("scroll-progress")).not.toBeInTheDocument();
});
});
+166 -85
View File
@@ -1,17 +1,23 @@
'use client';
"use client";
import { motion, useScroll, useTransform } from 'framer-motion';
import { useRef, useState, useEffect } from 'react';
import { ScrollReveal, StaggerReveal } from '@/components/ui/scroll-reveal';
import { StaticLink } from '@/components/ui/static-link';
import { CTA_LABELS } from '@/lib/constants/cta-labels';
import { SectionHeader } from '@/components/sections/section-header';
import { ServiceCard } from '@/components/sections/service-card';
import { ScrollProgress } from '@/components/ui/scroll-progress';
import { useReducedMotion } from '@/hooks/use-reduced-motion';
import { ArrowRight, Quote, Building2, Target, Lightbulb, TrendingUp } from 'lucide-react';
import { Button } from '@/components/ui/button';
import { AnimatedCounter } from '@/components/ui/animated-counter';
import { motion, useScroll, useTransform } from "framer-motion";
import { useRef, useState, useEffect } from "react";
import { ScrollReveal, StaggerReveal } from "@/components/ui/scroll-reveal";
import { StaticLink } from "@/components/ui/static-link";
import { CTA_LABELS } from "@/lib/constants/cta-labels";
import { SectionHeader } from "@/components/sections/section-header";
import { ServiceCard } from "@/components/sections/service-card";
import { useReducedMotion } from "@/hooks/use-reduced-motion";
import {
ArrowRight,
Quote,
Building2,
Target,
Lightbulb,
TrendingUp,
} from "lucide-react";
import { Button } from "@/components/ui/button";
import { AnimatedCounter } from "@/components/ui/animated-counter";
const EASE = [0.22, 1, 0.36, 1] as const;
@@ -44,7 +50,7 @@ function CaseDetailHero({ data }: CaseDetailHeroProps) {
const heroRef = useRef<HTMLDivElement>(null);
const { scrollYProgress } = useScroll({
target: heroRef,
offset: ['start start', 'end start'],
offset: ["start start", "end start"],
});
const opacity = useTransform(scrollYProgress, [0, 0.6], [1, 0]);
@@ -54,7 +60,7 @@ function CaseDetailHero({ data }: CaseDetailHeroProps) {
<section
ref={heroRef}
className="relative min-h-[85svh] flex items-center overflow-hidden pt-20"
style={{ background: 'var(--color-bg-primary)' }}
style={{ background: "var(--color-bg-primary)" }}
>
<motion.div
className="relative z-10 w-full max-w-[1280px] mx-auto px-5 sm:px-8 lg:px-16 py-20 md:py-28"
@@ -64,19 +70,22 @@ function CaseDetailHero({ data }: CaseDetailHeroProps) {
className="flex flex-wrap items-center gap-3 mb-8"
initial={shouldReduceMotion ? {} : { opacity: 0, y: 20 }}
animate={{ opacity: 1, y: 0 }}
transition={{ duration: 0.3, ease: EASE }}
transition={{ duration: 0.28, ease: EASE }}
>
<span
className="inline-flex items-center gap-2 px-4 py-1.5 rounded-full text-xs font-medium"
style={{
backgroundColor: 'var(--color-brand-soft)',
color: 'var(--color-brand)',
backgroundColor: "var(--color-brand-soft)",
color: "var(--color-brand)",
}}
>
<Building2 className="w-3.5 h-3.5" />
{data.industry}
</span>
<span className="text-[12px]" style={{ color: 'var(--color-text-muted)' }}>
<span
className="text-[12px]"
style={{ color: "var(--color-text-muted)" }}
>
{data.client}
</span>
</motion.div>
@@ -86,19 +95,19 @@ function CaseDetailHero({ data }: CaseDetailHeroProps) {
className="mb-8"
initial={shouldReduceMotion ? {} : { opacity: 0, y: 30 }}
animate={{ opacity: 1, y: 0 }}
transition={{ duration: 0.3, delay: 0.1, ease: EASE }}
transition={{ duration: 0.28, delay: 0.1, ease: EASE }}
>
<div
className="font-sans text-[clamp(56px,12vw,120px)] font-black leading-none tracking-[-2px] mb-2"
style={{ color: 'var(--color-brand)' }}
style={{ color: "var(--color-brand)" }}
>
{data.metrics[0]?.value || '40%'}
{data.metrics[0]?.value}
</div>
<div
className="text-lg md:text-xl font-medium"
style={{ color: 'var(--color-text-secondary)' }}
style={{ color: "var(--color-text-secondary)" }}
>
{data.metrics[0]?.label || '核心成果提升'}
{data.metrics[0]?.label}
</div>
</motion.div>
@@ -106,17 +115,17 @@ function CaseDetailHero({ data }: CaseDetailHeroProps) {
className="font-sans text-[clamp(28px,5vw,48px)] font-bold leading-[1.15] tracking-[-0.5px] text-[var(--color-text-primary)] mb-6 max-w-3xl"
initial={shouldReduceMotion ? {} : { opacity: 0, y: 30 }}
animate={{ opacity: 1, y: 0 }}
transition={{ duration: 0.3, delay: 0.25, ease: EASE }}
transition={{ duration: 0.28, delay: 0.25, ease: EASE }}
>
{data.title}
</motion.h1>
<motion.p
className="text-base md:text-lg max-w-2xl leading-relaxed mb-10 font-light"
style={{ color: 'var(--color-text-secondary)' }}
style={{ color: "var(--color-text-secondary)" }}
initial={shouldReduceMotion ? {} : { opacity: 0, y: 24 }}
animate={{ opacity: 1, y: 0 }}
transition={{ duration: 0.3, delay: 0.4, ease: EASE }}
transition={{ duration: 0.28, delay: 0.4, ease: EASE }}
>
{data.subtitle}
</motion.p>
@@ -126,17 +135,24 @@ function CaseDetailHero({ data }: CaseDetailHeroProps) {
className="grid grid-cols-3 gap-6 sm:gap-10 max-w-lg mb-10"
initial={shouldReduceMotion ? {} : { opacity: 0, y: 24 }}
animate={{ opacity: 1, y: 0 }}
transition={{ duration: 0.3, delay: 0.55, ease: EASE }}
transition={{ duration: 0.28, delay: 0.55, ease: EASE }}
>
{data.metrics.slice(1, 4).map((m, i) => (
<div key={i}>
<div
className="font-sans tabular-nums text-[28px] sm:text-[32px] font-bold leading-none mb-1.5"
style={{ color: m.highlight ? 'var(--color-brand)' : 'var(--color-text-primary)' }}
style={{
color: m.highlight
? "var(--color-brand)"
: "var(--color-text-primary)",
}}
>
{m.value}
</div>
<div className="text-[11px] sm:text-[12px]" style={{ color: 'var(--color-text-muted)' }}>
<div
className="text-[11px] sm:text-[12px]"
style={{ color: "var(--color-text-muted)" }}
>
{m.label}
</div>
</div>
@@ -148,25 +164,28 @@ function CaseDetailHero({ data }: CaseDetailHeroProps) {
className="flex flex-wrap gap-x-6 gap-y-3 text-sm mb-10 border-y border-border-primary py-4"
initial={shouldReduceMotion ? {} : { opacity: 0, y: 24 }}
animate={{ opacity: 1, y: 0 }}
transition={{ duration: 0.3, delay: 0.65, ease: EASE }}
transition={{ duration: 0.28, delay: 0.65, ease: EASE }}
>
{data.projectDuration && (
<div style={{ color: 'var(--color-text-secondary)' }}>
<span style={{ color: 'var(--color-text-muted)' }}>项目周期</span> {data.projectDuration}
<div style={{ color: "var(--color-text-secondary)" }}>
<span style={{ color: "var(--color-text-muted)" }}>项目周期</span>{" "}
{data.projectDuration}
</div>
)}
{data.departments && data.departments.length > 0 && (
<div style={{ color: 'var(--color-text-secondary)' }}>
<span style={{ color: 'var(--color-text-muted)' }}>涉及部门</span> {data.departments.join('、')}
<div style={{ color: "var(--color-text-secondary)" }}>
<span style={{ color: "var(--color-text-muted)" }}>涉及部门</span>{" "}
{data.departments.join("、")}
</div>
)}
{data.dataScale && (
<div style={{ color: 'var(--color-text-secondary)' }}>
<span style={{ color: 'var(--color-text-muted)' }}>数据规模</span> {data.dataScale}
<div style={{ color: "var(--color-text-secondary)" }}>
<span style={{ color: "var(--color-text-muted)" }}>数据规模</span>{" "}
{data.dataScale}
</div>
)}
{data.verified && (
<div style={{ color: 'var(--color-brand)' }}>✓ 客户授权公开</div>
<div style={{ color: "var(--color-brand)" }}>✓ 客户授权公开</div>
)}
</motion.div>
@@ -174,7 +193,7 @@ function CaseDetailHero({ data }: CaseDetailHeroProps) {
className="flex flex-wrap gap-4"
initial={shouldReduceMotion ? {} : { opacity: 0, y: 24 }}
animate={{ opacity: 1, y: 0 }}
transition={{ duration: 0.3, delay: 0.8, ease: EASE }}
transition={{ duration: 0.28, delay: 0.8, ease: EASE }}
>
<Button size="lg" asChild>
<StaticLink href="/contact">
@@ -193,7 +212,10 @@ function CaseDetailHero({ data }: CaseDetailHeroProps) {
function ChallengeSection({ data }: { data: CaseDetailData }) {
return (
<section className="relative py-20 sm:py-28 md:py-36 lg:py-44" style={{ background: 'var(--color-bg-primary)' }}>
<section
className="relative py-20 sm:py-28 md:py-36 lg:py-44"
style={{ background: "var(--color-bg-primary)" }}
>
<div className="max-w-[1280px] mx-auto px-5 sm:px-8 lg:px-16">
<div className="grid lg:grid-cols-12 gap-12 lg:gap-16 items-start">
<ScrollReveal className="lg:col-span-5">
@@ -209,17 +231,17 @@ function ChallengeSection({ data }: { data: CaseDetailData }) {
{data.businessProblem && (
<div
className="mb-6 pl-4 border-l-2"
style={{ borderColor: 'var(--color-brand)' }}
style={{ borderColor: "var(--color-brand)" }}
>
<div
className="text-xs font-medium mb-2"
style={{ color: 'var(--color-text-muted)' }}
style={{ color: "var(--color-text-muted)" }}
>
具体业务问题
</div>
<p
className="text-base md:text-lg leading-relaxed"
style={{ color: 'var(--color-text-primary)' }}
style={{ color: "var(--color-text-primary)" }}
>
{data.businessProblem}
</p>
@@ -228,21 +250,24 @@ function ChallengeSection({ data }: { data: CaseDetailData }) {
<div
className="p-8 sm:p-10 lg:p-12"
style={{
backgroundColor: 'var(--color-bg-secondary)',
backgroundColor: "var(--color-bg-secondary)",
}}
>
<div className="flex items-center gap-3 mb-6">
<Target className="w-6 h-6" style={{ color: 'var(--color-brand)' }} />
<Target
className="w-6 h-6"
style={{ color: "var(--color-brand)" }}
/>
<span
className="text-sm font-semibold"
style={{ color: 'var(--color-brand)' }}
style={{ color: "var(--color-brand)" }}
>
面临的挑战
</span>
</div>
<p
className="text-lg md:text-xl leading-relaxed mb-6"
style={{ color: 'var(--color-text-primary)' }}
style={{ color: "var(--color-text-primary)" }}
>
{data.challenge}
</p>
@@ -259,7 +284,7 @@ function SolutionSection({ data }: { data: CaseDetailData }) {
<section
id="solution"
className="relative py-20 sm:py-28 md:py-36 lg:py-44 overflow-hidden"
style={{ background: 'var(--color-bg-secondary)' }}
style={{ background: "var(--color-bg-secondary)" }}
>
<div className="max-w-[1280px] mx-auto px-5 sm:px-8 lg:px-16">
<ScrollReveal className="mb-16 sm:mb-20 max-w-2xl">
@@ -271,30 +296,45 @@ function SolutionSection({ data }: { data: CaseDetailData }) {
/>
</ScrollReveal>
<div className="grid lg:grid-cols-2 gap-0" style={{ border: '1px solid var(--color-border-primary)' }}>
<div style={{ backgroundColor: 'var(--color-bg-primary)' }}>
<div
className="grid lg:grid-cols-2 gap-0"
style={{ border: "1px solid var(--color-border-primary)" }}
>
<div style={{ backgroundColor: "var(--color-bg-primary)" }}>
<div className="p-8 sm:p-10 lg:p-12">
<div className="flex items-center gap-3 mb-6">
<Lightbulb className="w-6 h-6" style={{ color: 'var(--color-brand)' }} />
<Lightbulb
className="w-6 h-6"
style={{ color: "var(--color-brand)" }}
/>
<span
className="text-sm font-semibold"
style={{ color: 'var(--color-brand)' }}
style={{ color: "var(--color-brand)" }}
>
核心思路
</span>
</div>
<p className="text-base md:text-lg leading-relaxed" style={{ color: 'var(--color-text-secondary)' }}>
<p
className="text-base md:text-lg leading-relaxed"
style={{ color: "var(--color-text-secondary)" }}
>
{data.solution}
</p>
</div>
</div>
<div className="p-8 sm:p-10 lg:p-12" style={{ backgroundColor: 'var(--color-bg-primary)' }}>
<div
className="p-8 sm:p-10 lg:p-12"
style={{ backgroundColor: "var(--color-bg-primary)" }}
>
<div className="flex items-center gap-3 mb-6">
<TrendingUp className="w-6 h-6" style={{ color: 'var(--color-brand)' }} />
<TrendingUp
className="w-6 h-6"
style={{ color: "var(--color-brand)" }}
/>
<span
className="text-sm font-semibold"
style={{ color: 'var(--color-brand)' }}
style={{ color: "var(--color-brand)" }}
>
实施路径
</span>
@@ -305,20 +345,31 @@ function SolutionSection({ data }: { data: CaseDetailData }) {
<div
className="shrink-0 w-8 h-8 rounded-full flex items-center justify-center text-xs font-bold"
style={{
backgroundColor: 'var(--color-brand-soft)',
color: 'var(--color-brand)',
backgroundColor: "var(--color-brand-soft)",
color: "var(--color-brand)",
}}
>
{i + 1}
</div>
<div>
<div className="flex items-center gap-3 mb-1">
<h4 className="text-[var(--color-text-primary)] font-semibold">{t.phase}</h4>
<span className="text-[11px] px-2 py-0.5 rounded" style={{ backgroundColor: 'var(--color-bg-tertiary)', color: 'var(--color-text-muted)' }}>
<h4 className="text-[var(--color-text-primary)] font-semibold">
{t.phase}
</h4>
<span
className="text-[11px] px-2 py-0.5 rounded"
style={{
backgroundColor: "var(--color-bg-tertiary)",
color: "var(--color-text-muted)",
}}
>
{t.duration}
</span>
</div>
<p className="text-sm leading-relaxed" style={{ color: 'var(--color-text-secondary)' }}>
<p
className="text-sm leading-relaxed"
style={{ color: "var(--color-text-secondary)" }}
>
{t.description}
</p>
</div>
@@ -346,16 +397,22 @@ function ResultsSection({ data }: { data: CaseDetailData }) {
observer.disconnect();
}
},
{ threshold: 0.2 }
{ threshold: 0.2 },
);
observer.observe(resultsRef.current);
return () => observer.disconnect();
}, []);
const parseValue = (val: string): { num: number; suffix: string; isNumeric: boolean } => {
const parseValue = (
val: string,
): { num: number; suffix: string; isNumeric: boolean } => {
const match = val.match(/^([\d.]+)(.*)$/);
if (match && match[1] && !isNaN(parseFloat(match[1]))) {
return { num: parseFloat(match[1]), suffix: match[2] || '', isNumeric: true };
return {
num: parseFloat(match[1]),
suffix: match[2] || "",
isNumeric: true,
};
}
return { num: 0, suffix: val, isNumeric: false };
};
@@ -364,24 +421,26 @@ function ResultsSection({ data }: { data: CaseDetailData }) {
<section
ref={resultsRef}
className="relative py-20 sm:py-28 md:py-36 lg:py-44 overflow-hidden"
style={{ background: 'var(--color-brand)' }}
style={{ background: "var(--color-brand)" }}
>
{/* Background decoration */}
<div className="absolute inset-0 pointer-events-none">
<div
className="absolute w-[600px] h-[600px] rounded-full opacity-[0.15] blur-[120px]"
style={{
background: 'radial-gradient(circle, rgba(255,255,255,0.8), transparent 70%)',
top: '-30%',
right: '-10%',
background:
"radial-gradient(circle, rgba(255,255,255,0.8), transparent 70%)",
top: "-30%",
right: "-10%",
}}
/>
<div
className="absolute w-[400px] h-[400px] rounded-full opacity-[0.1] blur-[100px]"
style={{
background: 'radial-gradient(circle, rgba(255,255,255,0.6), transparent 70%)',
bottom: '-20%',
left: '10%',
background:
"radial-gradient(circle, rgba(255,255,255,0.6), transparent 70%)",
bottom: "-20%",
left: "10%",
}}
/>
</div>
@@ -390,7 +449,7 @@ function ResultsSection({ data }: { data: CaseDetailData }) {
<ScrollReveal className="mb-16 sm:mb-20 text-center max-w-3xl mx-auto">
<div
className="text-xs font-medium mb-4"
style={{ color: 'rgba(255,255,255,0.6)' }}
style={{ color: "rgba(255,255,255,0.6)" }}
>
项目成果
</div>
@@ -402,15 +461,20 @@ function ResultsSection({ data }: { data: CaseDetailData }) {
</p>
</ScrollReveal>
<div className="grid md:grid-cols-2 lg:grid-cols-4 gap-px mb-16" style={{ backgroundColor: 'rgba(255,255,255,0.15)' }}>
<div
className="grid md:grid-cols-2 lg:grid-cols-4 gap-px mb-16"
style={{ backgroundColor: "rgba(255,255,255,0.15)" }}
>
{data.metrics.slice(0, 4).map((m, i) => {
const { num, suffix, isNumeric } = parseValue(m.value);
const decimals = String(num).includes('.') ? String(num).split('.')[1]?.length ?? 0 : 0;
const decimals = String(num).includes(".")
? (String(num).split(".")[1]?.length ?? 0)
: 0;
return (
<div
key={i}
className="p-10 sm:p-12 text-center transition-all duration-150 hover:bg-white/[0.05] group relative overflow-hidden"
style={{ backgroundColor: 'var(--color-brand)' }}
style={{ backgroundColor: "var(--color-brand)" }}
>
{m.highlight && (
<div className="absolute top-4 right-4 px-2 py-1 text-[10px] font-bold text-brand bg-white rounded-full">
@@ -430,7 +494,9 @@ function ResultsSection({ data }: { data: CaseDetailData }) {
<>
{isNumeric ? num : suffix}
{isNumeric && suffix && (
<span className="text-[0.5em] font-bold text-white/80 ml-0.5">{suffix}</span>
<span className="text-[0.5em] font-bold text-white/80 ml-0.5">
{suffix}
</span>
)}
</>
)}
@@ -456,8 +522,12 @@ function ResultsSection({ data }: { data: CaseDetailData }) {
<Building2 className="w-5 h-5 text-white/60" />
</div>
<div>
<div className="font-semibold text-white text-lg">{data.testimonial.author}</div>
<div className="text-sm text-white/50">{data.testimonial.role}</div>
<div className="font-semibold text-white text-lg">
{data.testimonial.author}
</div>
<div className="text-sm text-white/50">
{data.testimonial.role}
</div>
</div>
</div>
</div>
@@ -469,9 +539,16 @@ function ResultsSection({ data }: { data: CaseDetailData }) {
);
}
function RelatedServicesSection({ services }: { services: CaseDetailData['services'] }) {
function RelatedServicesSection({
services,
}: {
services: CaseDetailData["services"];
}) {
return (
<section className="relative py-20 sm:py-28 md:py-36 lg:py-44" style={{ background: 'var(--color-bg-primary)' }}>
<section
className="relative py-20 sm:py-28 md:py-36 lg:py-44"
style={{ background: "var(--color-bg-primary)" }}
>
<div className="max-w-[1280px] mx-auto px-5 sm:px-8 lg:px-16">
<ScrollReveal className="mb-16 sm:mb-20 max-w-2xl">
<SectionHeader
@@ -501,15 +578,20 @@ function RelatedServicesSection({ services }: { services: CaseDetailData['servic
function CTASection() {
return (
<section className="relative py-20 sm:py-28 md:py-36 lg:py-44 overflow-hidden" style={{ background: 'var(--color-bg-secondary)' }}>
<section
className="relative py-20 sm:py-28 md:py-36 lg:py-44 overflow-hidden"
style={{ background: "var(--color-bg-secondary)" }}
>
<div className="max-w-[800px] mx-auto px-5 sm:px-8 lg:px-16 text-center relative z-10">
<ScrollReveal>
<h2 className="font-sans text-3xl sm:text-4xl md:text-5xl lg:text-6xl font-bold text-[var(--color-text-primary)] leading-tight tracking-tight mb-6">
您也想实现类似的
<span style={{ color: 'var(--color-brand)' }}> 业务突破</span>
?
<span style={{ color: "var(--color-brand)" }}> 业务突破</span>?
</h2>
<p className="text-lg md:text-xl mb-10 font-light" style={{ color: 'var(--color-text-secondary)' }}>
<p
className="text-lg md:text-xl mb-10 font-light"
style={{ color: "var(--color-text-secondary)" }}
>
免费咨询,48小时内给出初步方案建议
</p>
<div className="flex flex-col sm:flex-row justify-center gap-4">
@@ -532,7 +614,6 @@ function CTASection() {
export default function CaseDetailPage({ data }: { data: CaseDetailData }) {
return (
<div className="min-h-screen">
<ScrollProgress />
<CaseDetailHero data={data} />
<ChallengeSection data={data} />
<SolutionSection data={data} />
@@ -40,7 +40,7 @@ export function ChallengeSection() {
initial={shouldReduceMotion ? {} : { opacity: 0, y: 20 }}
whileInView={{ opacity: 1, y: 0 }}
viewport={{ once: true, margin: '-100px' }}
transition={{ duration: 0.3, ease: [0.16, 1, 0.3, 1] }}
transition={{ duration: 0.28, ease: [0.16, 1, 0.3, 1] }}
className="mb-14"
>
<div className="flex items-center gap-4 mb-4">
@@ -49,7 +49,7 @@ export function ChallengeSection() {
<div className="h-px flex-1 bg-[var(--color-border-primary)]" />
</div>
<h2 className="text-3xl sm:text-4xl font-semibold text-[var(--color-text-primary)] text-center">
您的挑战,我们的<span className="text-[var(--color-brand)] font-calligraphy">使命</span>
您的挑战,我们的<span className="text-brand-ink font-calligraphy">使命</span>
</h2>
<p className="text-base text-[var(--color-text-muted)] text-center mt-4 max-w-xl mx-auto">
深入理解企业数字化进程中的核心痛点,提供针对性解决方案
+3 -3
View File
@@ -41,7 +41,7 @@ export function CTASection({
initial={shouldReduceMotion ? {} : { opacity: 0, scale: 0.96, y: 16 }}
whileInView={{ opacity: 1, scale: 1, y: 0 }}
viewport={{ once: true, margin: '-80px' }}
transition={{ duration: 0.3, ease: [0.16, 1, 0.3, 1] }}
transition={{ duration: 0.28, ease: [0.16, 1, 0.3, 1] }}
className="text-center max-w-3xl mx-auto relative"
>
<div className="absolute -top-8 left-1/2 -translate-x-1/2 hidden md:block">
@@ -51,10 +51,10 @@ export function CTASection({
initial={shouldReduceMotion ? {} : { opacity: 0, y: -8 }}
whileInView={{ opacity: 1, y: 0 }}
viewport={{ once: true }}
transition={{ duration: 0.3, delay: 0.15 }}
transition={{ duration: 0.28, delay: 0.15 }}
className="inline-flex items-center gap-2 px-4 py-1.5 rounded-full bg-[var(--color-brand-soft)] border border-[var(--color-border-primary)] mb-8"
>
<Sparkles className="w-3.5 h-3.5 text-[var(--color-brand)]" />
<Sparkles className="w-3.5 h-3.5 text-brand-ink" />
<span className="text-sm font-medium text-[var(--color-text-primary)]">开始对话</span>
</motion.div>
@@ -0,0 +1,507 @@
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<string, unknown> = {
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<typeof HTMLCanvasElement.prototype.getContext>;
let rectSpy: jest.SpiedFunction<typeof Element.prototype.getBoundingClientRect>;
let frameQueue: Array<(t: number) => void>;
let rafSpy: jest.SpiedFunction<typeof window.requestAnimationFrame>;
let cafSpy: jest.SpiedFunction<typeof window.cancelAnimationFrame>;
/** 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<string, unknown>).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(<HeroParticleField />);
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(<HeroParticleField />);
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(<HeroParticleField />);
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(<HeroParticleField />);
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(<HeroParticleField />);
paintOnce();
expect(arcPositions()).toHaveLength(56);
});
it('draws nothing extra when the container has zero area', () => {
setViewport({ width: 0, height: 0 });
render(<HeroParticleField />);
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(<HeroParticleField variant={variant} dark={dark} />);
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(<HeroParticleField variant="drift" />);
paintOnce();
expect(ctxStub.gradients).toHaveLength(0);
const before = ctxStub.calls.length;
rerender(<HeroParticleField variant="constellation" />);
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(<HeroParticleField />);
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(<HeroParticleField />);
paintOnce();
expect(written('fillStyle')[0]).toContain('rgba(196, 30, 58,');
});
it('falls back when the token is not declared at all', () => {
render(<HeroParticleField />);
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(<HeroParticleField />);
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(<HeroParticleField />);
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(<HeroParticleField />);
runFrames([16]);
unmount();
expect(cafSpy).toHaveBeenCalled();
});
it('paints a single static frame and never schedules rAF under reduced motion', () => {
setReduceMotion(true);
render(<HeroParticleField />);
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(<HeroParticleField />);
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(<HeroParticleField />);
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(<HeroParticleField />);
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<string, unknown>).IntersectionObserver;
delete (globalThis as Record<string, unknown>).IntersectionObserver;
try {
const { unmount } = render(<HeroParticleField />);
expect(rafSpy).toHaveBeenCalledTimes(1);
paintOnce();
expect(arcPositions()).toHaveLength(32);
expect(() => unmount()).not.toThrow();
expect(cafSpy).toHaveBeenCalled();
} finally {
(globalThis as Record<string, unknown>).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<string, unknown>).ResizeObserver = MockResizeObserver;
render(<HeroParticleField />);
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<string, unknown>).ResizeObserver = MockResizeObserver;
const { unmount } = render(<HeroParticleField />);
unmount();
expect(observers[0]?.disconnected).toBe(true);
});
it('appends a custom class to the canvas layer', () => {
render(<HeroParticleField className="hero-overlay" />);
const canvas = screen.getByTestId('hero-particle-field');
expect(canvas.className).toContain('hero-overlay');
expect(canvas.className).toContain('pointer-events-none');
});
});
@@ -270,10 +270,14 @@ export function HeroParticleField({
// 离屏或标签页隐藏即停,回到视口且可见再启动
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 {
@@ -286,7 +290,7 @@ export function HeroParticleField({
}
const onVisibility = () => {
if (document.visibilityState !== 'visible') stop();
else if (!reduceMotion && !isAutomation) start();
else if (intersecting && !reduceMotion && !isAutomation) start();
};
document.addEventListener('visibilitychange', onVisibility);
+11 -11
View File
@@ -44,7 +44,7 @@ export function HeroSectionV2() {
const fadeUp = (delay: number) => ({
initial: shouldReduceMotion ? {} : { opacity: 0, y: 24 },
animate: { opacity: 1, y: 0 },
transition: { duration: 0.3, delay, ease: EASE },
transition: { duration: 0.28, delay, ease: EASE },
});
return (
@@ -60,7 +60,7 @@ export function HeroSectionV2() {
{...fadeUp(0)}
className="mb-6"
>
<span className="inline-flex items-center gap-2 px-3 py-1.5 sm:px-4 sm:py-2 rounded-full bg-[var(--color-brand-bg)] text-[var(--color-brand)] text-xs sm:text-sm font-medium border border-[var(--color-brand)]/10">
<span className="inline-flex items-center gap-2 px-3 py-1.5 sm:px-4 sm:py-2 rounded-full bg-[var(--color-brand-bg)] text-brand-ink text-xs sm:text-sm font-medium border border-brand/10">
{COMPANY_INFO.slogan}
</span>
</motion.div>
@@ -92,7 +92,7 @@ export function HeroSectionV2() {
{...fadeUp(0.35)}
className="flex flex-col sm:flex-row items-start gap-4 mb-10"
>
<Button size="lg" asChild className="min-h-[52px] px-8 text-base font-semibold shadow-lg shadow-[var(--color-brand)]/20">
<Button size="lg" asChild className="min-h-[52px] px-8 text-base font-semibold shadow-lg shadow-brand/20">
<StaticLink href="/contact">
{CTA_LABELS.consult}
<ArrowRight className="w-4 h-4 ml-2" />
@@ -107,7 +107,7 @@ export function HeroSectionV2() {
<motion.div
initial={shouldReduceMotion ? {} : { opacity: 0, y: 32 }}
animate={{ opacity: 1, y: 0 }}
transition={{ duration: 0.3, delay: 0.5, ease: EASE }}
transition={{ duration: 0.28, delay: 0.5, ease: EASE }}
>
<div
ref={cardRef}
@@ -123,16 +123,16 @@ export function HeroSectionV2() {
onMouseLeave={() => setIsCardHovered(false)}
>
<div
className="absolute inset-0 rounded-2xl pointer-events-none transition-opacity duration-300"
className="absolute inset-0 rounded-2xl pointer-events-none transition-opacity duration-normal"
style={{
opacity: isCardHovered ? 1 : 0,
background: `radial-gradient(400px circle at ${mousePos.x}px ${mousePos.y}px, rgba(var(--color-brand-rgb), 0.06), transparent 40%)`,
}}
/>
<div className="relative rounded-2xl bg-[var(--color-bg-primary)]/80 backdrop-blur-sm p-6 sm:p-8 lg:p-10">
<div className="relative rounded-2xl bg-bg-primary/80 backdrop-blur-sm p-6 sm:p-8 lg:p-10">
<div className="w-12 h-12 lg:w-14 lg:h-14 rounded-xl bg-[var(--color-brand-bg)] flex items-center justify-center mb-5 lg:mb-6">
<Handshake className="w-5 h-5 lg:w-6 lg:h-6 text-[var(--color-brand)]" strokeWidth={1.8} />
<Handshake className="w-5 h-5 lg:w-6 lg:h-6 text-brand-ink" strokeWidth={1.8} />
</div>
<h3 className="text-lg lg:text-xl font-semibold text-[var(--color-text-primary)] mb-2">
@@ -148,14 +148,14 @@ export function HeroSectionV2() {
return (
<div
key={step.label}
className="flex items-center gap-3 lg:gap-4 p-2.5 lg:p-3 rounded-lg bg-[var(--color-bg-section)]/60"
className="flex items-center gap-3 lg:gap-4 p-2.5 lg:p-3 rounded-lg bg-bg-section/60"
>
<div className="w-8 h-8 lg:w-9 lg:h-9 rounded-lg bg-[var(--color-brand-bg)] flex items-center justify-center shrink-0">
<Icon className="w-3.5 h-3.5 lg:w-4 lg:h-4 text-[var(--color-brand)]" strokeWidth={2.2} />
<Icon className="w-3.5 h-3.5 lg:w-4 lg:h-4 text-brand-ink" strokeWidth={2.2} />
</div>
<div className="flex-1 min-w-0">
<div className="flex items-center gap-1.5 lg:gap-2">
<span className="text-[10px] lg:text-xs font-bold text-[var(--color-brand)]">0{idx + 1}</span>
<span className="text-[10px] lg:text-xs font-bold text-brand-ink">0{idx + 1}</span>
<span className="text-xs lg:text-sm font-medium text-[var(--color-text-primary)]">{step.label}</span>
</div>
<p className="text-[10px] lg:text-xs text-[var(--color-text-muted)] mt-0.5 hidden sm:block">{step.desc}</p>
@@ -166,7 +166,7 @@ export function HeroSectionV2() {
</div>
{/* Integrated capabilities */}
<div className="mt-4 pt-4 border-t border-[var(--color-border-primary)]/50">
<div className="mt-4 pt-4 border-t border-border-primary/50">
<div className="flex flex-wrap gap-1.5">
{CAPABILITIES.map((cap, idx) => {
const Icon = cap.icon;
-24
View File
@@ -1,24 +0,0 @@
export { SectionHeader } from './section-header';
export { ServiceCard } from './service-card';
export { ServiceGrid } from './service-grid';
export { ProductCard as SectionProductCard } from './product-card';
export { ProductMatrixSection } from './product-matrix-section';
export { CaseCard } from './case-card';
export { default as CaseDetailPage } from './case-detail-page';
export { InsightCard } from './insight-card';
export { IndustryGrid } from './industry-grid';
export { StatsBar } from './stats-bar';
export { SocialProofSection } from './social-proof-section';
export { WhyUsSection } from './why-us-section';
export { ChallengeSection } from './challenge-section';
export { MethodologySection } from './methodology-section';
export { CTASection } from './cta-section';
export { HeroSectionV2 } from './hero-section-v2';
export { QuestionCard } from './question-card';
+2 -2
View File
@@ -30,8 +30,8 @@ export function IndustryGrid({ items, className = '' }: IndustryGridProps) {
tabIndex={0}
>
<div className="relative z-10">
<Icon className="w-7 h-7 sm:w-8 sm:h-8 mx-auto mb-2 sm:mb-3 transition-transform duration-150 group-hover:scale-110 text-[var(--color-text-primary)] group-hover:text-[var(--color-brand)]" />
<div className="text-[13px] sm:text-[14px] font-medium transition-colors duration-150 text-[var(--color-text-primary)] group-hover:text-[var(--color-brand)]">
<Icon className="w-7 h-7 sm:w-8 sm:h-8 mx-auto mb-2 sm:mb-3 transition-transform duration-150 group-hover:scale-110 text-[var(--color-text-primary)] group-hover:text-brand-ink" />
<div className="text-[13px] sm:text-[14px] font-medium transition-colors duration-150 text-[var(--color-text-primary)] group-hover:text-brand-ink">
{item.name}
</div>
<div className="text-[10px] sm:text-[11px] mt-1 sm:mt-1.5 transition-colors duration-150 text-[var(--color-text-subtle)] group-hover:text-[var(--color-text-muted)]">
+1 -1
View File
@@ -56,7 +56,7 @@ export function InsightCard({
<p className="text-[13px] sm:text-[14px] leading-relaxed max-w-[400px] mb-5 md:mb-6 text-[var(--color-text-secondary)]">
{desc}
</p>
<span className="text-[12px] inline-flex items-center gap-1.5 transition-colors duration-300 text-[var(--color-text-muted)] group-hover:text-[var(--color-brand)]">
<span className="text-[12px] inline-flex items-center gap-1.5 transition-colors duration-normal text-[var(--color-text-muted)] group-hover:text-brand-ink">
阅读全文
<ArrowUpRight className="w-3 h-3" />
</span>
@@ -19,11 +19,11 @@ export function MethodologySection() {
<motion.div
initial={{ opacity: 0, y: 20 }}
animate={isInView ? { opacity: 1, y: 0 } : {}}
transition={{ duration: 0.3, ease: [0.16, 1, 0.3, 1] }}
transition={{ duration: 0.28, ease: [0.16, 1, 0.3, 1] }}
className="text-center max-w-3xl mx-auto mb-14"
>
<h2 id="methodology-heading" className="text-3xl sm:text-4xl font-semibold text-[var(--color-text-primary)] mb-4">
实施<span className="text-[var(--color-brand)]">方法论</span>
实施<span className="text-brand-ink">方法论</span>
</h2>
<p className="text-base text-[var(--color-text-muted)]">
经过核心团队实践打磨的四阶段模型,确保每个项目都能科学推进、高效落地
@@ -40,7 +40,7 @@ export function MethodologySection() {
return (
<Card
key={phase.id}
className="relative overflow-hidden transition-all duration-300 hover:-translate-y-1 hover:shadow-lg"
className="relative overflow-hidden transition-all duration-normal hover:-translate-y-1 hover:shadow-lg"
>
<div className="p-6 md:p-8">
<div
@@ -51,7 +51,7 @@ export function MethodologySection() {
</div>
<h3 className="text-lg font-semibold text-[var(--color-text-primary)] mb-1">{phase.title}</h3>
<p className="text-xs text-[var(--color-brand)] font-medium mb-3">{phase.subtitle}</p>
<p className="text-xs text-brand-ink font-medium mb-3">{phase.subtitle}</p>
<p className="text-sm text-[var(--color-text-muted)] leading-relaxed mb-5">{phase.description}</p>
<div className="mb-4">
@@ -59,7 +59,7 @@ export function MethodologySection() {
<ul className="space-y-1.5">
{phase.activities.map((activity, i) => (
<li key={i} className="flex items-start gap-2 text-xs text-[var(--color-text-muted)]">
<CheckCircle2 className="w-3.5 h-3.5 text-[var(--color-brand)] mt-0.5 shrink-0" />
<CheckCircle2 className="w-3.5 h-3.5 text-brand-ink mt-0.5 shrink-0" />
{activity}
</li>
))}
@@ -71,7 +71,7 @@ export function MethodologySection() {
<ul className="space-y-1.5">
{phase.deliverables.map((deliverable, i) => (
<li key={i} className="flex items-start gap-2 text-xs text-[var(--color-text-subtle)]">
<span className="w-1.5 h-1.5 bg-[var(--color-brand)]/40 rounded-full mt-1.5 shrink-0" />
<span className="w-1.5 h-1.5 bg-brand/40 rounded-full mt-1.5 shrink-0" />
{deliverable}
</li>
))}
+6 -6
View File
@@ -29,12 +29,12 @@ export function ProductCard({
return (
<StaticLink
href={href}
className={`group relative block p-6 sm:p-8 lg:p-10 bg-[var(--color-bg-primary)] border border-[var(--color-border-primary)] rounded-sm transition-all duration-300 overflow-hidden ${className}`}
className={`group relative block p-6 sm:p-8 lg:p-10 bg-[var(--color-bg-primary)] border border-[var(--color-border-primary)] rounded-sm transition-all duration-normal overflow-hidden ${className}`}
style={{ minHeight: '44px', minWidth: '44px' }}
>
{/* Left accent bar — visible on hover */}
<div
className="absolute left-0 top-0 bottom-0 w-[3px] bg-[var(--color-brand)] transition-transform duration-300 origin-top"
className="absolute left-0 top-0 bottom-0 w-[3px] bg-[var(--color-brand)] transition-transform duration-normal origin-top"
style={{ transform: 'scaleY(0)' }}
onMouseEnter={(e) => {
e.currentTarget.style.transform = 'scaleY(1)';
@@ -54,7 +54,7 @@ export function ProductCard({
{title}
</h3>
{badge && (
<span className="text-[10px] tracking-[2px] uppercase px-2 py-0.5 rounded-full bg-[var(--color-brand-bg)] text-[var(--color-brand)] font-medium">
<span className="text-[10px] tracking-[2px] uppercase px-2 py-0.5 rounded-full bg-[var(--color-brand-bg)] text-brand-ink font-medium">
{badge}
</span>
)}
@@ -66,16 +66,16 @@ export function ProductCard({
</p>
{/* CTA link */}
<span className="inline-flex items-center gap-1.5 text-[13px] font-medium text-[var(--color-text-primary)] transition-all duration-300 group-hover:text-[var(--color-brand)] group-hover:gap-2.5">
<span className="inline-flex items-center gap-1.5 text-[13px] font-medium text-[var(--color-text-primary)] transition-all duration-normal group-hover:text-brand-ink group-hover:gap-2.5">
了解更多
<ArrowRight className="w-3.5 h-3.5 transition-transform duration-300 group-hover:translate-x-1" />
<ArrowRight className="w-3.5 h-3.5 transition-transform duration-normal group-hover:translate-x-1" />
</span>
</div>
{/* Hover background lift */}
<div className="absolute inset-0 bg-[var(--color-bg-hover)] opacity-0 transition-opacity duration-150 pointer-events-none" />
<div
className="absolute inset-0 opacity-0 transition-opacity duration-300 pointer-events-none"
className="absolute inset-0 opacity-0 transition-opacity duration-normal pointer-events-none"
onMouseEnter={(e) => { e.currentTarget.style.opacity = '1'; }}
/>
</StaticLink>
@@ -17,7 +17,7 @@ export function ProductMatrixSection() {
initial={shouldReduceMotion ? {} : { opacity: 0, y: 20 }}
whileInView={{ opacity: 1, y: 0 }}
viewport={{ once: true, margin: '-100px' }}
transition={{ duration: 0.3, ease: [0.16, 1, 0.3, 1] }}
transition={{ duration: 0.28, ease: [0.16, 1, 0.3, 1] }}
className="flex flex-col md:flex-row md:items-end md:justify-between gap-4 mb-14"
>
<div>
@@ -25,11 +25,11 @@ export function ProductMatrixSection() {
产品矩阵
</h2>
<p className="text-base text-[var(--color-text-muted)] max-w-lg">
6 款自研产品覆盖企业数字化全场景,目前全部<span className="text-[var(--color-brand)] font-medium">研发中</span>,欢迎提前了解规划
6 款自研产品覆盖企业数字化全场景,目前全部<span className="text-brand-ink font-medium">研发中</span>,欢迎提前了解规划
</p>
</div>
<div className="flex items-center gap-2">
<span className="inline-flex items-center gap-1.5 px-3 py-1 rounded-full bg-[var(--color-brand-bg)] text-[var(--color-brand)] text-xs font-medium border border-[var(--color-brand)]/10">
<span className="inline-flex items-center gap-1.5 px-3 py-1 rounded-full bg-[var(--color-brand-bg)] text-brand-ink text-xs font-medium border border-brand/10">
<span className="w-1.5 h-1.5 rounded-full bg-[var(--color-brand)] animate-pulse" />
研发中 · 即将上线
</span>
+3 -3
View File
@@ -27,7 +27,7 @@ export function QuestionCard({
className={`group md:grid md:grid-cols-2 border-b border-[var(--color-border-primary)] relative overflow-hidden ${className}`}
>
{/* Left accent bar — visible on hover */}
<div className="absolute left-0 top-0 bottom-0 w-[3px] hidden md:block transition-transform duration-300 origin-top bg-[var(--color-brand)]"
<div className="absolute left-0 top-0 bottom-0 w-[3px] hidden md:block transition-transform duration-normal origin-top bg-[var(--color-brand)]"
style={{ transform: 'scaleY(0)' }}
onMouseEnter={(e) => { e.currentTarget.style.transform = 'scaleY(1)'; }}
/>
@@ -46,11 +46,11 @@ export function QuestionCard({
</p>
<StaticLink
href={href}
className="inline-flex items-center gap-2 text-[13px] font-medium text-[var(--color-text-primary)] transition-all duration-300 hover:text-[var(--color-brand)] group/link"
className="inline-flex items-center gap-2 text-[13px] font-medium text-[var(--color-text-primary)] transition-all duration-normal hover:text-brand-ink group/link"
style={{ minHeight: '44px', minWidth: '44px' }}
>
{linkText}
<ChevronRight className="w-3.5 h-3.5 transition-transform duration-300 group-hover/link:translate-x-1" />
<ChevronRight className="w-3.5 h-3.5 transition-transform duration-normal group-hover/link:translate-x-1" />
</StaticLink>
</div>
</div>
+3 -3
View File
@@ -35,7 +35,7 @@ export function SectionHeader({
initial={shouldReduceMotion ? {} : { opacity: 0, y: 24 }}
whileInView={{ opacity: 1, y: 0 }}
viewport={{ once: true, margin: '-40px' }}
transition={{ duration: 0.3, ease: EASE }}
transition={{ duration: 0.28, ease: EASE }}
>
{/* Eyebrow label with brand accent bar */}
<div className="flex items-center gap-3 mb-4 md:mb-5">
@@ -51,7 +51,7 @@ export function SectionHeader({
initial={shouldReduceMotion ? {} : { scaleY: 0 }}
whileInView={{ scaleY: 1 }}
viewport={{ once: true, margin: '-40px' }}
transition={{ duration: 0.3, delay: 0.1, ease: EASE }}
transition={{ duration: 0.28, delay: 0.1, ease: EASE }}
/>
<motion.div
className="text-[10px] tracking-[4px] uppercase font-medium"
@@ -63,7 +63,7 @@ export function SectionHeader({
initial={shouldReduceMotion ? {} : { opacity: 0, x: -8 }}
whileInView={{ opacity: 1, x: 0 }}
viewport={{ once: true, margin: '-40px' }}
transition={{ duration: 0.3, delay: 0.2, ease: EASE }}
transition={{ duration: 0.28, delay: 0.2, ease: EASE }}
>
{label}
</motion.div>
+9 -34
View File
@@ -131,6 +131,15 @@ describe('SectionHeader', () => {
expect(heading.closest('h2')?.style.color).toBe('rgb(255, 255, 255)');
});
it('washes the description white on dark sections and keeps it muted on light ones', async () => {
const { SectionHeader } = await import('./section-header');
const { unmount } = render(<SectionHeader label="TEST" title="Title" desc="深色底的说明文字" light />);
expect(screen.getByText('深色底的说明文字').style.color).toBe('rgba(255, 255, 255, 0.5)');
unmount();
render(<SectionHeader label="TEST" title="Title" desc="浅色底的说明文字" />);
expect(screen.getByText('浅色底的说明文字').style.color).toBe('var(--color-text-muted)');
});
it('should apply custom className', async () => {
const { SectionHeader } = await import('./section-header');
render(<SectionHeader label="T" title="T" className="my-class" />);
@@ -149,40 +158,6 @@ describe('SectionHeader', () => {
});
});
describe('StatsBar', () => {
const mockItems = [
{ number: '500', unit: '+', label: '客户' },
{ number: '99', unit: '%', label: '满意度', desc: '客户反馈评分' },
];
it('should render stat items', async () => {
const { StatsBar } = await import('./stats-bar');
render(<StatsBar items={mockItems} />);
expect(screen.getByText('客户')).toBeInTheDocument();
expect(screen.getByText('满意度')).toBeInTheDocument();
});
it('should render description when provided', async () => {
const { StatsBar } = await import('./stats-bar');
render(<StatsBar items={mockItems} />);
expect(screen.getByText('客户反馈评分')).toBeInTheDocument();
});
it('should apply custom className', async () => {
const { StatsBar } = await import('./stats-bar');
const { container } = render(<StatsBar items={mockItems} className="stats-class" />);
const grid = container.querySelector('.stats-class');
expect(grid).toBeInTheDocument();
});
it('should render in dark mode', async () => {
const { StatsBar } = await import('./stats-bar');
render(<StatsBar items={mockItems} dark />);
const labels = screen.getAllByText('客户');
expect(labels.length).toBeGreaterThan(0);
});
});
describe('ProductCard', () => {
it('should render title, description and icon', async () => {
const { ProductCard } = await import('./product-card');
+3 -3
View File
@@ -30,11 +30,11 @@ export function ServiceCard({
return (
<motion.div
className={`group relative bg-[var(--color-bg-primary)] border border-[var(--color-border-primary)] rounded-[var(--radius-lg)] overflow-hidden transition-all duration-normal ease-ink hover:-translate-y-1 hover:shadow-[var(--shadow-lg)] hover:border-[var(--color-brand)]/20 ${className}`}
className={`group relative bg-[var(--color-bg-primary)] border border-[var(--color-border-primary)] rounded-[var(--radius-lg)] overflow-hidden transition-all duration-normal ease-ink hover:-translate-y-1 hover:shadow-[var(--shadow-lg)] hover:border-brand/20 ${className}`}
initial={shouldReduceMotion ? {} : { opacity: 0, y: 24 }}
whileInView={{ opacity: 1, y: 0 }}
viewport={{ once: true, margin: '-40px' }}
transition={{ duration: 0.3, delay, ease: [0.22, 1, 0.36, 1] }}
transition={{ duration: 0.28, delay, ease: [0.22, 1, 0.36, 1] }}
>
<div className="p-6 md:p-8">
{/* Title */}
@@ -50,7 +50,7 @@ export function ServiceCard({
{/* Link */}
<Link
href={href}
className="inline-flex items-center text-sm font-medium transition-all duration-fast group-hover:gap-2.5 text-[var(--color-brand)]"
className="inline-flex items-center text-sm font-medium transition-all duration-fast group-hover:gap-2.5 text-brand-ink"
style={{ minHeight: '44px', minWidth: '44px' }}
>
<span>了解详情</span>
@@ -31,7 +31,7 @@ export function SocialProofSection() {
<section id="social-proof" role="region" aria-labelledby="social-proof-heading" className="py-16 md:py-24 lg:py-28 relative overflow-hidden">
{/* Background accent */}
<div className="absolute inset-0 bg-[var(--color-bg-primary)]" aria-hidden="true" />
<div className="absolute top-0 left-0 right-0 h-px bg-gradient-to-r from-transparent via-[var(--color-brand)]/10 to-transparent" aria-hidden="true" />
<div className="absolute top-0 left-0 right-0 h-px bg-gradient-to-r from-transparent via-brand/10 to-transparent" aria-hidden="true" />
<div className="absolute bottom-0 left-0 right-0 h-px bg-gradient-to-r from-transparent via-[var(--color-border-primary)] to-transparent" aria-hidden="true" />
<div className="container-wide relative z-10">
@@ -40,7 +40,7 @@ export function SocialProofSection() {
initial={shouldReduceMotion ? {} : { opacity: 0, y: 20 }}
whileInView={{ opacity: 1, y: 0 }}
viewport={{ once: true, margin: '-100px' }}
transition={{ duration: 0.3, ease: [0.16, 1, 0.3, 1] }}
transition={{ duration: 0.28, ease: [0.16, 1, 0.3, 1] }}
className="text-center max-w-3xl mx-auto mb-16"
>
<h2 id="social-proof-heading" className="text-3xl sm:text-4xl font-semibold text-[var(--color-text-primary)] mb-4">
@@ -56,7 +56,7 @@ export function SocialProofSection() {
initial={shouldReduceMotion ? {} : { opacity: 0, y: 24 }}
whileInView={{ opacity: 1, y: 0 }}
viewport={{ once: true, margin: '-80px' }}
transition={{ duration: 0.3, ease: [0.16, 1, 0.3, 1] }}
transition={{ duration: 0.28, ease: [0.16, 1, 0.3, 1] }}
className="grid grid-cols-2 lg:grid-cols-4 gap-6 md:gap-8 mb-16"
>
{METRICS.map((metric, idx) => {
@@ -67,11 +67,11 @@ export function SocialProofSection() {
initial={shouldReduceMotion ? {} : { opacity: 0, y: 20 }}
whileInView={{ opacity: 1, y: 0 }}
viewport={{ once: true, margin: '-60px' }}
transition={{ duration: 0.3, delay: idx * 0.06, ease: [0.16, 1, 0.3, 1] }}
transition={{ duration: 0.28, delay: idx * 0.06, ease: [0.16, 1, 0.3, 1] }}
className="text-center group"
>
<div className="w-12 h-12 rounded-full bg-[var(--color-brand)]/5 flex items-center justify-center mx-auto mb-4 group-hover:bg-[var(--color-brand)]/10 transition-colors duration-300">
<Icon className="w-5 h-5 text-[var(--color-brand)]" strokeWidth={1.5} />
<div className="w-12 h-12 rounded-full bg-brand/5 flex items-center justify-center mx-auto mb-4 group-hover:bg-brand/10 transition-colors duration-normal">
<Icon className="w-5 h-5 text-brand-ink" strokeWidth={1.5} />
</div>
<div className="text-4xl md:text-5xl font-bold text-[var(--color-text-primary)] tracking-tight mb-1">
{metric.value}
@@ -95,16 +95,16 @@ export function SocialProofSection() {
initial={shouldReduceMotion ? {} : { opacity: 0, y: 20 }}
whileInView={{ opacity: 1, y: 0 }}
viewport={{ once: true, margin: '-60px' }}
transition={{ duration: 0.3, delay: 0.2 + idx * 0.1, ease: [0.16, 1, 0.3, 1] }}
className="relative p-6 md:p-8 rounded-2xl bg-[var(--color-bg-section)] border border-[var(--color-border-primary)] hover:border-[rgba(var(--color-brand-rgb),0.2)] transition-all duration-300"
transition={{ duration: 0.28, delay: 0.2 + idx * 0.1, ease: [0.16, 1, 0.3, 1] }}
className="relative p-6 md:p-8 rounded-2xl bg-[var(--color-bg-section)] border border-[var(--color-border-primary)] hover:border-[rgba(var(--color-brand-rgb),0.2)] transition-all duration-normal"
>
<Quote className="w-8 h-8 text-[var(--color-brand)]/15 mb-4" strokeWidth={1.5} />
<Quote className="w-8 h-8 text-brand-ink/15 mb-4" strokeWidth={1.5} />
<blockquote className="text-[var(--color-text-secondary)] text-base leading-relaxed mb-6">
&ldquo;{t.quote}&rdquo;
</blockquote>
<div className="flex items-center gap-3">
<div className="w-10 h-10 rounded-full bg-gradient-to-br from-[var(--color-brand)]/10 to-[var(--color-brand)]/5 flex items-center justify-center">
<span className="text-sm font-semibold text-[var(--color-brand)]">{t.author[0]}</span>
<div className="w-10 h-10 rounded-full bg-gradient-to-br from-brand/10 to-brand/5 flex items-center justify-center">
<span className="text-sm font-semibold text-brand-ink">{t.author[0]}</span>
</div>
<div>
<div className="text-sm font-medium text-[var(--color-text-primary)]">{t.author}</div>
-131
View File
@@ -1,131 +0,0 @@
'use client';
import { useState, useEffect, useRef } from 'react';
interface StatItem {
number: string;
unit: string;
label: string;
desc?: string;
}
interface StatsBarProps {
items: StatItem[];
/** Whether to show on dark background */
dark?: boolean;
className?: string;
}
function CountUpNumber({ end, startCounting }: { end: number; startCounting: boolean }) {
const [count, setCount] = useState(0);
const frameRef = useRef<number>(0);
useEffect(() => {
if (!startCounting) return;
const duration = 1800;
const startTime = performance.now();
const easeOutCubic = (t: number) => 1 - Math.pow(1 - t, 3);
const animate = (now: number) => {
const progress = Math.min((now - startTime) / duration, 1);
const eased = easeOutCubic(progress);
setCount(Math.floor(end * eased));
if (progress < 1) {
frameRef.current = requestAnimationFrame(animate);
} else {
setCount(end);
}
};
frameRef.current = requestAnimationFrame(animate);
return () => cancelAnimationFrame(frameRef.current);
}, [end, startCounting]);
return <>{count}</>;
}
export function StatsBar({ items, dark = false, className = '' }: StatsBarProps) {
const [inView, setInView] = useState(false);
const sectionRef = useRef<HTMLDivElement>(null);
useEffect(() => {
const el = sectionRef.current;
if (!el) return;
const observer = new IntersectionObserver(
([entry]) => {
if (entry?.isIntersecting) {
setInView(true);
observer.disconnect();
}
},
{ threshold: 0.1 },
);
observer.observe(el);
return () => observer.disconnect();
}, []);
return (
<div
ref={sectionRef}
className={`grid grid-cols-2 md:grid-cols-3 lg:grid-cols-${items.length} gap-px rounded-sm overflow-hidden ${className}`}
style={{
background: dark ? 'rgba(255,255,255,0.04)' : 'var(--color-border-primary)',
}}
>
{items.map((item, i) => (
<div
key={i}
className="py-10 sm:py-12 md:py-14 px-4 sm:px-6 md:px-8 text-center transition-all duration-normal ease-ink hover:bg-[var(--color-bg-hover)] group"
style={{ background: dark ? 'var(--color-brand)' : 'var(--color-bg-primary)' }}
>
<div
className="font-sans tabular-nums text-[clamp(36px,8vw,64px)] font-bold leading-none mb-1 md:mb-2 tracking-[-0.02em] transition-all duration-slow ease-ink group-hover:scale-105"
style={{
color: dark ? '#FFFFFF' : 'var(--color-text-primary)',
transform: inView ? 'scale(1)' : 'scale(0.9)',
opacity: inView ? 1 : 0,
transitionDelay: `${i * 80}ms`,
}}
>
{inView ? (
<CountUpNumber end={parseInt(item.number)} startCounting={true} />
) : (
item.number
)}
<span
style={{
color: dark ? 'rgba(255,255,255,0.6)' : 'var(--color-brand)',
fontSize: '0.4em',
fontWeight: 700,
}}
>
{item.unit}
</span>
</div>
<div
className="text-[12px] sm:text-[13px] font-medium mb-3 md:mb-4 tracking-[0.08em] uppercase transition-all duration-normal"
style={{
color: dark ? 'rgba(255,255,255,0.5)' : 'var(--color-text-muted)',
opacity: inView ? 1 : 0,
transform: inView ? 'translateY(0)' : 'translateY(8px)',
transitionDelay: `${i * 80 + 150}ms`,
}}
>
{item.label}
</div>
{item.desc && (
<div
className="text-[12px] sm:text-[13px] leading-relaxed transition-all duration-normal"
style={{
color: dark ? 'rgba(255,255,255,0.35)' : 'var(--color-text-subtle)',
opacity: inView ? 1 : 0,
transform: inView ? 'translateY(0)' : 'translateY(6px)',
transitionDelay: `${i * 80 + 250}ms`,
}}
>
{item.desc}
</div>
)}
</div>
))}
</div>
);
}
+12 -12
View File
@@ -51,23 +51,23 @@ export function WhyUsSection() {
<section id="why-us" className="relative py-20 md:py-28 bg-[var(--color-bg-section)] bg-texture-dots overflow-hidden">
{/* Decorative large numbers background */}
<div className="absolute inset-0 overflow-hidden pointer-events-none" aria-hidden="true">
<span className="absolute -top-24 -left-12 text-[20rem] font-bold text-[var(--color-brand)]/[0.02] leading-none select-none font-calligraphy">睿</span>
<span className="absolute -bottom-32 -right-8 text-[16rem] font-bold text-[var(--color-brand)]/[0.02] leading-none select-none">新</span>
<span className="absolute -top-24 -left-12 text-[20rem] font-bold text-brand-ink/[0.02] leading-none select-none font-calligraphy">睿</span>
<span className="absolute -bottom-32 -right-8 text-[16rem] font-bold text-brand-ink/[0.02] leading-none select-none">新</span>
</div>
<div className="container-wide relative z-10">
<motion.div
initial={shouldReduceMotion ? {} : { opacity: 0, y: 20 }}
whileInView={{ opacity: 1, y: 0 }}
viewport={{ once: true, margin: '-100px' }}
transition={{ duration: 0.3, ease: [0.16, 1, 0.3, 1] }}
transition={{ duration: 0.28, ease: [0.16, 1, 0.3, 1] }}
className="mb-14"
>
<div className="inline-flex items-center gap-2 px-4 py-1.5 rounded-full bg-[var(--color-brand-bg)] border border-[var(--color-brand)]/10 mb-4">
<div className="inline-flex items-center gap-2 px-4 py-1.5 rounded-full bg-[var(--color-brand-bg)] border border-brand/10 mb-4">
<span className="w-1.5 h-1.5 rounded-full bg-[var(--color-brand)]" />
<span className="text-xs font-medium tracking-wider text-[var(--color-brand)]">核心优势</span>
<span className="text-xs font-medium tracking-wider text-brand-ink">核心优势</span>
</div>
<h2 className="text-3xl sm:text-4xl font-semibold text-[var(--color-text-primary)] mb-4">
为什么选择<span className="text-[var(--color-brand)] font-calligraphy">我们</span>
为什么选择<span className="text-brand-ink font-calligraphy">我们</span>
</h2>
<p className="text-base text-[var(--color-text-muted)]">
我们不是一家&ldquo;做完就跑&rdquo;的外包公司,而是愿意与您一起成长的数字化转型同行者
@@ -83,8 +83,8 @@ export function WhyUsSection() {
initial={shouldReduceMotion ? {} : { opacity: 0, y: 24, scale: 0.96 }}
whileInView={{ opacity: 1, y: 0, scale: 1 }}
viewport={{ once: true, margin: '-60px' }}
transition={{ duration: 0.3, delay: idx * 0.06, ease: [0.16, 1, 0.3, 1] }}
className="relative group p-6 md:p-8 rounded-2xl bg-[var(--color-bg-primary)] border border-[var(--color-border-primary)] hover:border-[rgba(var(--color-brand-rgb),0.25)] transition-all duration-300"
transition={{ duration: 0.28, delay: idx * 0.06, ease: [0.16, 1, 0.3, 1] }}
className="relative group p-6 md:p-8 rounded-2xl bg-[var(--color-bg-primary)] border border-[var(--color-border-primary)] hover:border-[rgba(var(--color-brand-rgb),0.25)] transition-all duration-normal"
>
<div className="flex items-start justify-between mb-4">
<div
@@ -134,7 +134,7 @@ export function WhyUsSection() {
initial={shouldReduceMotion ? {} : { opacity: 0, y: 16 }}
whileInView={{ opacity: 1, y: 0 }}
viewport={{ once: true, margin: '-80px' }}
transition={{ duration: 0.3, delay: 0.3, ease: [0.16, 1, 0.3, 1] }}
transition={{ duration: 0.28, delay: 0.3, ease: [0.16, 1, 0.3, 1] }}
className="text-center"
>
<p className="text-sm text-[var(--color-text-muted)] mb-6">想深入了解我们的团队能力?</p>
@@ -151,7 +151,7 @@ export function WhyUsSection() {
initial={shouldReduceMotion ? {} : { opacity: 0, y: 16 }}
whileInView={{ opacity: 1, y: 0 }}
viewport={{ once: true, margin: '-60px' }}
transition={{ duration: 0.3, delay: 0.4, ease: [0.16, 1, 0.3, 1] }}
transition={{ duration: 0.28, delay: 0.4, ease: [0.16, 1, 0.3, 1] }}
className="mt-16 pt-10 border-t border-[var(--color-border-primary)]"
>
<p className="text-xs text-center text-[var(--color-text-subtle)] mb-6 tracking-wide uppercase">技术伙伴 / 技术栈</p>
@@ -169,8 +169,8 @@ export function WhyUsSection() {
key={tech.name}
className="group flex flex-col items-center gap-1.5"
>
<div className="px-4 py-2 rounded-lg bg-[var(--color-bg-section)] border border-[var(--color-border-primary)] group-hover:border-[rgba(var(--color-brand-rgb),0.2)] group-hover:bg-[var(--color-brand-bg)]/30 transition-all duration-300">
<span className="text-sm font-mono font-medium text-[var(--color-text-subtle)] group-hover:text-[var(--color-brand)] transition-colors duration-300 tracking-wider">
<div className="px-4 py-2 rounded-lg bg-[var(--color-bg-section)] border border-[var(--color-border-primary)] group-hover:border-[rgba(var(--color-brand-rgb),0.2)] group-hover:bg-brand-bg/30 transition-all duration-normal">
<span className="text-sm font-mono font-medium text-[var(--color-text-subtle)] group-hover:text-brand-ink transition-colors duration-normal tracking-wider">
{tech.abbr}
</span>
</div>
@@ -230,6 +230,24 @@ describe('StructuredData', () => {
});
});
describe('JSON-LD 序列化的 </script> 闭合防护', () => {
const PAYLOAD = '</script><img src=x onerror=alert(1)>';
it('序列化结果里不出现字面 </script>,改为 \\u003c 转义', () => {
const { container } = render(<FAQSchema items={[{ question: PAYLOAD, answer: 'a' }]} />);
const text = container.querySelector('script[type="application/ld+json"]')?.textContent ?? '';
expect(text).not.toContain('</script>');
expect(text).toContain('\\u003c/script\\u003e');
});
it('转义不改变 JSON 语义,解析后仍是原字符串', () => {
const { container } = render(<FAQSchema items={[{ question: PAYLOAD, answer: 'b' }]} />);
const script = container.querySelector('script[type="application/ld+json"]');
const schema = JSON.parse(script?.textContent || '{}');
expect(schema.mainEntity[0].name).toBe(PAYLOAD);
});
});
describe('LocalBusinessSchema', () => {
it('should render local business schema', () => {
const { container } = render(<LocalBusinessSchema />);
+16 -7
View File
@@ -1,5 +1,14 @@
import { COMPANY_INFO } from '@/lib/constants';
/**
* JSON-LD 内联脚本的序列化。JSON.stringify 不转义尖括号,因此字符串值里出现的 `</script>`
* 会提前闭合 <script>,把后续内容放回 HTML 标记流(与 A-3 同一类缺陷,只是换了 sink)。
* `\u003c` / `\u003e` 在 JSON 解析后逐字等值,对搜索引擎解析器无影响。
*/
function jsonLd(schema: unknown): string {
return JSON.stringify(schema).replace(/</g, '\\u003c').replace(/>/g, '\\u003e');
}
export function OrganizationSchema() {
const schema = {
"@context": "https://schema.org",
@@ -50,7 +59,7 @@ export function OrganizationSchema() {
return (
<script
type="application/ld+json"
dangerouslySetInnerHTML={{ __html: JSON.stringify(schema) }}
dangerouslySetInnerHTML={{ __html: jsonLd(schema) }}
/>
);
}
@@ -76,7 +85,7 @@ export function WebsiteSchema() {
return (
<script
type="application/ld+json"
dangerouslySetInnerHTML={{ __html: JSON.stringify(schema) }}
dangerouslySetInnerHTML={{ __html: jsonLd(schema) }}
/>
);
}
@@ -120,7 +129,7 @@ export function ServiceSchema({ name, description, areaServed }: ServiceSchemaPr
return (
<script
type="application/ld+json"
dangerouslySetInnerHTML={{ __html: JSON.stringify(schema) }}
dangerouslySetInnerHTML={{ __html: jsonLd(schema) }}
/>
);
}
@@ -159,7 +168,7 @@ export function ProductSchema({ name, description, image, category }: ProductSch
return (
<script
type="application/ld+json"
dangerouslySetInnerHTML={{ __html: JSON.stringify(schema) }}
dangerouslySetInnerHTML={{ __html: jsonLd(schema) }}
/>
);
}
@@ -186,7 +195,7 @@ export function FAQSchema({ items }: { items: FAQItem[] }) {
return (
<script
type="application/ld+json"
dangerouslySetInnerHTML={{ __html: JSON.stringify(schema) }}
dangerouslySetInnerHTML={{ __html: jsonLd(schema) }}
/>
);
}
@@ -211,7 +220,7 @@ export function BreadcrumbSchema({ items }: { items: BreadcrumbItem[] }) {
return (
<script
type="application/ld+json"
dangerouslySetInnerHTML={{ __html: JSON.stringify(schema) }}
dangerouslySetInnerHTML={{ __html: jsonLd(schema) }}
/>
);
}
@@ -263,7 +272,7 @@ export function LocalBusinessSchema() {
return (
<script
type="application/ld+json"
dangerouslySetInnerHTML={{ __html: JSON.stringify(schema) }}
dangerouslySetInnerHTML={{ __html: jsonLd(schema) }}
/>
);
}
-128
View File
@@ -1,128 +0,0 @@
// @ts-nocheck
import { describe, it, expect } from '@jest/globals';
import { render, screen } from '@testing-library/react';
import '@testing-library/jest-dom';
import { Accordion, AccordionItem, AccordionTrigger, AccordionContent } from './accordion';
describe('Accordion Components', () => {
describe('AccordionItem', () => {
it('should render item with children', () => {
render(
<Accordion type="single">
<AccordionItem value="item1">Item Content</AccordionItem>
</Accordion>
);
expect(screen.getByText('Item Content')).toBeInTheDocument();
});
it('should have data-slot attribute', () => {
render(
<Accordion type="single">
<AccordionItem value="item1" data-testid="item">Item</AccordionItem>
</Accordion>
);
expect(screen.getByTestId('item')).toHaveAttribute('data-slot', 'accordion-item');
});
it('should apply custom className', () => {
render(
<Accordion type="single">
<AccordionItem value="item1" className="custom-item">Item</AccordionItem>
</Accordion>
);
expect(screen.getByText('Item')).toHaveClass('custom-item');
});
});
describe('AccordionTrigger', () => {
it('should render trigger text', () => {
render(
<Accordion type="single">
<AccordionItem value="item1">
<AccordionTrigger>点击展开</AccordionTrigger>
</AccordionItem>
</Accordion>
);
expect(screen.getByText('点击展开')).toBeInTheDocument();
});
it('should have data-slot attribute', () => {
render(
<Accordion type="single">
<AccordionItem value="item1">
<AccordionTrigger data-testid="trigger">Trigger</AccordionTrigger>
</AccordionItem>
</Accordion>
);
expect(screen.getByTestId('trigger')).toHaveAttribute('data-slot', 'accordion-trigger');
});
it('should apply custom className', () => {
render(
<Accordion type="single">
<AccordionItem value="item1">
<AccordionTrigger className="custom-trigger">Trigger</AccordionTrigger>
</AccordionItem>
</Accordion>
);
expect(screen.getByText('Trigger')).toHaveClass('custom-trigger');
});
});
describe('AccordionContent', () => {
it('should render content when item is open', () => {
render(
<Accordion type="single" defaultValue="item1">
<AccordionItem value="item1">
<AccordionTrigger>标题</AccordionTrigger>
<AccordionContent>展开内容</AccordionContent>
</AccordionItem>
</Accordion>
);
expect(screen.getByText('展开内容')).toBeInTheDocument();
});
it('should have data-slot attribute', () => {
render(
<Accordion type="single" defaultValue="item1">
<AccordionItem value="item1">
<AccordionContent data-testid="content">Content</AccordionContent>
</AccordionItem>
</Accordion>
);
expect(screen.getByTestId('content')).toHaveAttribute('data-slot', 'accordion-content');
});
it('should apply custom className', () => {
render(
<Accordion type="single" defaultValue="item1">
<AccordionItem value="item1">
<AccordionContent className="custom-content">Content</AccordionContent>
</AccordionItem>
</Accordion>
);
expect(screen.getByText('Content')).toHaveClass('custom-content');
});
});
describe('Accordion Composition', () => {
it('should render complete accordion structure', () => {
render(
<Accordion type="single" defaultValue="faq1">
<AccordionItem value="faq1">
<AccordionTrigger>问题一</AccordionTrigger>
<AccordionContent>答案一</AccordionContent>
</AccordionItem>
<AccordionItem value="faq2">
<AccordionTrigger>问题二</AccordionTrigger>
<AccordionContent>答案二</AccordionContent>
</AccordionItem>
</Accordion>
);
expect(screen.getByText('问题一')).toBeInTheDocument();
expect(screen.getByText('答案一')).toBeInTheDocument();
expect(screen.getByText('问题二')).toBeInTheDocument();
});
});
});
-65
View File
@@ -1,65 +0,0 @@
'use client';
import * as React from 'react';
import * as AccordionPrimitive from '@radix-ui/react-accordion';
import { ChevronDown } from 'lucide-react';
import { cn } from '@/lib/utils';
/**
* 标准 shadcn/ui Accordion 组件
* 基于 @radix-ui/react-accordion
*/
const Accordion = AccordionPrimitive.Root;
const AccordionItem = React.forwardRef<
React.ElementRef<typeof AccordionPrimitive.Item>,
React.ComponentPropsWithoutRef<typeof AccordionPrimitive.Item>
>(({ className, ...props }, ref) => (
<AccordionPrimitive.Item
ref={ref}
data-slot="accordion-item"
className={cn('border-b border-border-primary', className)}
{...props}
/>
));
AccordionItem.displayName = 'AccordionItem';
const AccordionTrigger = React.forwardRef<
React.ElementRef<typeof AccordionPrimitive.Trigger>,
React.ComponentPropsWithoutRef<typeof AccordionPrimitive.Trigger>
>(({ className, children, ...props }, ref) => (
<AccordionPrimitive.Header className="flex">
<AccordionPrimitive.Trigger
ref={ref}
data-slot="accordion-trigger"
className={cn(
'flex flex-1 items-center justify-between py-4 text-sm font-medium transition-all hover:underline',
'focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-brand focus-visible:ring-offset-2',
'[&[data-state=open]>svg]:rotate-180',
className
)}
{...props}
>
{children}
<ChevronDown className="size-4 shrink-0 text-text-muted transition-transform duration-normal" />
</AccordionPrimitive.Trigger>
</AccordionPrimitive.Header>
));
AccordionTrigger.displayName = AccordionPrimitive.Trigger.displayName;
const AccordionContent = React.forwardRef<
React.ElementRef<typeof AccordionPrimitive.Content>,
React.ComponentPropsWithoutRef<typeof AccordionPrimitive.Content>
>(({ className, children, ...props }, ref) => (
<AccordionPrimitive.Content
ref={ref}
data-slot="accordion-content"
className="overflow-hidden text-sm data-[state=closed]:animate-accordion-up data-[state=open]:animate-accordion-down"
{...props}
>
<div className={cn('pb-4 pt-0', className)}>{children}</div>
</AccordionPrimitive.Content>
));
AccordionContent.displayName = AccordionPrimitive.Content.displayName;
export { Accordion, AccordionItem, AccordionTrigger, AccordionContent };
+30 -7
View File
@@ -3,9 +3,9 @@ import { describe, it, expect, jest } from '@jest/globals';
import { render, screen } from '@testing-library/react';
import '@testing-library/jest-dom';
// Mock hooks
// Mock hooks:忠实于 useCountUp 的真实语义 —— enabled=false 时停在起点
jest.mock('@/hooks/use-count-up', () => ({
useCountUp: jest.fn(() => 500),
useCountUp: jest.fn(({ enabled, end, start = 0 }) => (enabled ? end : start)),
}));
jest.mock('@/hooks/use-reduced-motion', () => ({
@@ -15,34 +15,57 @@ jest.mock('@/hooks/use-reduced-motion', () => ({
describe('AnimatedCounter', () => {
it('renders value with prefix and suffix', () => {
const { AnimatedCounter } = require('./animated-counter');
render(<AnimatedCounter value={500} prefix="¥" suffix="+" />);
render(<AnimatedCounter value={500} prefix="¥" suffix="+" startOnView={false} />);
expect(screen.getByText('¥500+')).toBeInTheDocument();
});
it('renders with aria-label containing prefix, value, and suffix', () => {
const { AnimatedCounter } = require('./animated-counter');
render(<AnimatedCounter value={500} prefix="¥" suffix="+" />);
render(<AnimatedCounter value={500} prefix="¥" suffix="+" startOnView={false} />);
const el = screen.getByText('¥500+');
expect(el).toHaveAttribute('aria-label', '¥500+');
});
it('renders with tabular-nums class', () => {
const { AnimatedCounter } = require('./animated-counter');
render(<AnimatedCounter value={500} />);
render(<AnimatedCounter value={500} startOnView={false} />);
const el = screen.getByText('500');
expect(el).toHaveClass('tabular-nums');
});
it('renders with custom decimals', () => {
const { AnimatedCounter } = require('./animated-counter');
render(<AnimatedCounter value={500} decimals={1} />);
render(<AnimatedCounter value={500} decimals={1} startOnView={false} />);
expect(screen.getByText('500.0')).toBeInTheDocument();
});
it('applies custom className', () => {
const { AnimatedCounter } = require('./animated-counter');
render(<AnimatedCounter value={500} className="custom-class" />);
render(<AnimatedCounter value={500} className="custom-class" startOnView={false} />);
const el = screen.getByText('500');
expect(el).toHaveClass('custom-class');
});
// S-23:旧实现 displayValue 在「未进入视口」分支直显终值,
// IntersectionObserver 异步首回调后突然跳到 0 再爬升 —— 用户先看到答案再看计数。
it('startOnView 时入视口前显示起点 0 而不是终值(S-23 回归)', () => {
let observerCallback;
global.IntersectionObserver = class {
constructor(cb) { observerCallback = cb; }
observe() {}
disconnect() {}
unobserve() {}
};
const { AnimatedCounter } = require('./animated-counter');
render(<AnimatedCounter value={500} />);
// 尚未相交:必须停在起点 0(旧码此处直显 500 ⇒ 判红)
observerCallback([{ isIntersecting: false }]);
expect(screen.getByText('0')).toBeInTheDocument();
// 相交后动画接管(useCountUp mock 回 500);observer 回调里的 setState 需 act 包裹
const { act } = require('@testing-library/react');
act(() => {
observerCallback([{ isIntersecting: true }]);
});
expect(screen.getByText('500')).toBeInTheDocument();
});
});
+3 -1
View File
@@ -59,7 +59,9 @@ export function AnimatedCounter({
return () => observer.disconnect();
}, [startOnView, threshold]);
const displayValue = start ? (shouldReduceMotion ? value : count) : value;
// 未进入视口时显示起点而不是终值:旧写法先闪出答案再跳回 0 计数(S-23)。
// useCountUp 在 enabled=false 期间本就停在起点 0。
const displayValue = shouldReduceMotion ? value : count;
return (
<span
+4 -1
View File
@@ -16,6 +16,9 @@ export function BackToTop() {
};
window.addEventListener('scroll', handleScroll, { passive: true });
// 初始同步:浏览器滚动还原或经 hash 锚点落到页面中部时,首帧尚未触发 scroll 事件,
// 不调用则按钮在 scrollY>500 的载入下一直隐藏(S-9)。
handleScroll();
return () => window.removeEventListener('scroll', handleScroll);
}, []);
@@ -35,7 +38,7 @@ export function BackToTop() {
exit={shouldReduceMotion ? {} : { opacity: 0, y: 20, scale: 0.8 }}
transition={{ duration: 0.2, ease: 'easeOut' }}
onClick={scrollToTop}
className="fixed right-4 bottom-20 md:bottom-8 md:right-8 z-40 p-3 bg-brand text-white hover:bg-brand-hover transition-all duration-300 ease-out focus:outline-none focus:ring-2 focus:ring-brand focus:ring-offset-2 focus:ring-offset-white"
className="fixed right-4 bottom-20 md:bottom-8 md:right-8 z-40 p-3 bg-brand text-white hover:bg-brand-hover transition-all duration-normal ease-out focus:outline-none focus:ring-2 focus:ring-brand focus:ring-offset-2 focus:ring-offset-white"
aria-label="返回顶部"
title="返回顶部"
whileHover={shouldReduceMotion ? {} : { scale: 1.05 }}
+9 -9
View File
@@ -9,9 +9,9 @@ export function GeometricDecoration({ variant = 'circles' }: { variant?: 'circle
return (
<div className="absolute inset-0 overflow-hidden pointer-events-none" aria-hidden="true">
<svg className="absolute top-[10%] right-[5%] w-64 h-64 opacity-[0.04]" viewBox="0 0 200 200">
<circle cx="100" cy="100" r="80" fill="none" stroke="currentColor" className="text-[var(--color-brand)]" strokeWidth="0.5" />
<circle cx="100" cy="100" r="60" fill="none" stroke="currentColor" className="text-[var(--color-brand)]" strokeWidth="0.5" />
<circle cx="100" cy="100" r="40" fill="none" stroke="currentColor" className="text-[var(--color-brand)]" strokeWidth="0.5" />
<circle cx="100" cy="100" r="80" fill="none" stroke="currentColor" className="text-brand-ink" strokeWidth="0.5" />
<circle cx="100" cy="100" r="60" fill="none" stroke="currentColor" className="text-brand-ink" strokeWidth="0.5" />
<circle cx="100" cy="100" r="40" fill="none" stroke="currentColor" className="text-brand-ink" strokeWidth="0.5" />
<circle
cx="100" cy="100" r="20"
fill="rgba(var(--color-brand-rgb, 196, 30, 58), 0.1)"
@@ -29,9 +29,9 @@ export function GeometricDecoration({ variant = 'circles' }: { variant?: 'circle
return (
<div className="absolute inset-0 overflow-hidden pointer-events-none" aria-hidden="true">
<svg className="absolute top-0 right-0 w-full h-full opacity-[0.02]" viewBox="0 0 1000 1000" preserveAspectRatio="none">
<line x1="800" y1="0" x2="1000" y2="400" stroke="currentColor" className="text-[var(--color-brand)]" strokeWidth="1" />
<line x1="850" y1="0" x2="1000" y2="300" stroke="currentColor" className="text-[var(--color-brand)]" strokeWidth="0.5" />
<line x1="900" y1="0" x2="1000" y2="200" stroke="currentColor" className="text-[var(--color-brand)]" strokeWidth="0.5" />
<line x1="800" y1="0" x2="1000" y2="400" stroke="currentColor" className="text-brand-ink" strokeWidth="1" />
<line x1="850" y1="0" x2="1000" y2="300" stroke="currentColor" className="text-brand-ink" strokeWidth="0.5" />
<line x1="900" y1="0" x2="1000" y2="200" stroke="currentColor" className="text-brand-ink" strokeWidth="0.5" />
<line x1="0" y1="600" x2="300" y2="1000" stroke="currentColor" className="text-[var(--color-text-subtle)]" strokeWidth="0.5" />
<line x1="0" y1="700" x2="200" y2="1000" stroke="currentColor" className="text-[var(--color-text-subtle)]" strokeWidth="0.5" />
</svg>
@@ -63,7 +63,7 @@ export function DataBar({ value, max = 100, label, color = 'brand' }: { value: n
initial={{ width: 0 }}
whileInView={{ width: `${percentage}%` }}
viewport={{ once: true }}
transition={{ duration: 0.3, ease: [0.16, 1, 0.3, 1], delay: 0.2 }}
transition={{ duration: 0.28, ease: [0.16, 1, 0.3, 1], delay: 0.2 }}
className="h-full rounded-full"
style={{ backgroundColor: colorMap[color] }}
/>
@@ -92,14 +92,14 @@ export function BrandStamp({ children }: { children: React.ReactNode }) {
initial={shouldReduceMotion ? {} : { scale: 1.3, opacity: 0, rotate: -12 }}
whileInView={{ scale: 1, opacity: 1, rotate: -5 }}
viewport={{ once: true }}
transition={{ duration: 0.3, ease: [0.16, 1, 0.3, 1] }}
transition={{ duration: 0.28, ease: [0.16, 1, 0.3, 1] }}
className="inline-block px-3 py-1.5 border-2 border-[var(--color-brand)] rounded-sm"
style={{
transform: 'rotate(-5deg)',
background: 'repeating-linear-gradient(45deg, transparent, transparent 2px, rgba(var(--color-brand-rgb), 0.03) 2px, rgba(var(--color-brand-rgb), 0.03) 4px)',
}}
>
<span className="text-xs font-bold tracking-widest text-[var(--color-brand)] font-calligraphy">
<span className="text-xs font-bold tracking-widest text-brand-ink font-calligraphy">
{children}
</span>
</motion.div>
+24 -1
View File
@@ -1,5 +1,5 @@
import { describe, it, expect } from '@jest/globals';
import { render, screen } from '@testing-library/react';
import { render, screen, fireEvent, act } from '@testing-library/react';
import '@testing-library/jest-dom';
import { Button } from './button';
@@ -146,4 +146,27 @@ describe('Button Component', () => {
expect(button).toHaveClass('min-w-[44px]');
});
});
describe('Ripple (Q-10)', () => {
// 诚实说明:真正修的缺陷是「同毫秒点击 id 相撞(重复 key)+ 卸载不清定时器」。
// 但本仓 Jest 跑的是 production React 构建 ⇒ 重复 key 的 dev 告警被剥离,
// 且 timer-on-unmount 在 React 18 不再告警——两条都无法在本环境里做出「移除修复即判红」的
// 判别性断言(做过 RED 探针:还原成 Date.now() 后本用例仍绿 ⇒ 不能假装它是回归锁)。
// 因此这里只覆盖被我改动的渲染路径本身(涟漪出现→按窗口清除),它能捕获
// 「涟漪永不清除 / 根本不出现」这类真实回归;id 唯一性与卸载清理靠 code review 保证。
it('adds a ripple on click and clears it after the 600ms animation window', () => {
jest.useFakeTimers();
try {
const { container } = render(<Button data-testid="ripple-btn">Go</Button>);
fireEvent.click(screen.getByTestId('ripple-btn'));
expect(container.querySelectorAll('.animate-ripple')).toHaveLength(1);
act(() => {
jest.advanceTimersByTime(600);
});
expect(container.querySelectorAll('.animate-ripple')).toHaveLength(0);
} finally {
jest.useRealTimers();
}
});
});
});
+16 -2
View File
@@ -48,6 +48,18 @@ export interface ButtonProps
const Button = React.forwardRef<HTMLButtonElement, ButtonProps>(
({ className, variant, size, asChild = false, onClick, children, showRipple = true, ...props }, ref) => {
const [ripples, setRipples] = React.useState<{ x: number; y: number; id: number }[]>([]);
// 自增序号:Date.now() 在同一毫秒内的多次点击会算出相同 id ⇒ 重复 React key + 清理时
// filter 会把同 id 的多条涟漪一起删掉。用 ref 计数器保证每条涟漪 key 唯一(Q-10)。
const rippleSeq = React.useRef(0);
const rippleTimers = React.useRef<ReturnType<typeof setTimeout>[]>([]);
// 卸载时清空未触发的定时器,避免卸载后 setState 泄漏。
React.useEffect(
() => () => {
rippleTimers.current.forEach(clearTimeout);
},
[]
);
const handleClick = (e: React.MouseEvent<HTMLButtonElement>) => {
if (showRipple && variant !== 'link' && variant !== 'ghost') {
@@ -55,13 +67,15 @@ const Button = React.forwardRef<HTMLButtonElement, ButtonProps>(
const rect = button.getBoundingClientRect();
const x = e.clientX - rect.left;
const y = e.clientY - rect.top;
const id = Date.now();
const id = rippleSeq.current++;
setRipples((prev) => [...prev, { x, y, id }]);
setTimeout(() => {
const timer = setTimeout(() => {
setRipples((prev) => prev.filter((r) => r.id !== id));
rippleTimers.current = rippleTimers.current.filter((t) => t !== timer);
}, 600);
rippleTimers.current.push(timer);
}
onClick?.(e);
+3 -3
View File
@@ -29,7 +29,7 @@ export function ChallengeCard({ title, description, scenario, href, index }: Cha
return (
<a href={href}>
<Card className="group relative overflow-hidden transition-all duration-300 hover:-translate-y-1 hover:shadow-lg">
<Card className="group relative overflow-hidden transition-all duration-normal hover:-translate-y-1 hover:shadow-lg">
<div className="p-6 md:p-8">
<div className="flex items-start justify-between mb-5">
<div
@@ -37,7 +37,7 @@ export function ChallengeCard({ title, description, scenario, href, index }: Cha
style={{ backgroundColor: `rgba(var(--color-brand-rgb), ${config.iconBgOpacity})` }}
>
<IconComponent
className="w-5 h-5 text-[var(--color-brand)]"
className="w-5 h-5 text-brand-ink"
strokeWidth={1.8}
/>
</div>
@@ -54,7 +54,7 @@ export function ChallengeCard({ title, description, scenario, href, index }: Cha
{description}
</p>
<div className="flex items-center gap-2 text-sm font-medium text-[var(--color-brand)]">
<div className="flex items-center gap-2 text-sm font-medium text-brand-ink">
<span>了解方案</span>
<ArrowRight className="w-4 h-4" />
</div>
+4 -4
View File
@@ -50,10 +50,10 @@ const VARIANT_STYLES: Record<CTAButtonVariant, string> = {
};
const ARROW_STYLES: Record<CTAButtonVariant, string> = {
primary: 'w-5 h-5 transition-transform duration-300 group-hover:translate-x-2',
secondary: 'w-5 h-5 transition-transform duration-300 group-hover:translate-x-2',
dark: 'w-5 h-5 transition-transform duration-300 group-hover:translate-x-2',
inline: 'w-4 h-4 transition-transform duration-300 group-hover:translate-x-1',
primary: 'w-5 h-5 transition-transform duration-normal group-hover:translate-x-2',
secondary: 'w-5 h-5 transition-transform duration-normal group-hover:translate-x-2',
dark: 'w-5 h-5 transition-transform duration-normal group-hover:translate-x-2',
inline: 'w-4 h-4 transition-transform duration-normal group-hover:translate-x-1',
};
export function CTAButton({
-131
View File
@@ -1,131 +0,0 @@
// @ts-nocheck
import { describe, it, expect } from '@jest/globals';
import { render, screen } from '@testing-library/react';
import '@testing-library/jest-dom';
import {
Dialog,
DialogTrigger,
DialogContent,
DialogHeader,
DialogTitle,
DialogDescription,
} from './dialog';
describe('Dialog Components', () => {
describe('DialogTrigger', () => {
it('should render trigger button', () => {
render(
<Dialog>
<DialogTrigger>打开对话框</DialogTrigger>
</Dialog>
);
expect(screen.getByText('打开对话框')).toBeInTheDocument();
});
});
describe('DialogHeader', () => {
it('should render header with children', () => {
render(<DialogHeader>Header Content</DialogHeader>);
expect(screen.getByText('Header Content')).toBeInTheDocument();
});
it('should have data-slot attribute', () => {
render(<DialogHeader data-testid="header">Header</DialogHeader>);
expect(screen.getByTestId('header')).toHaveAttribute('data-slot', 'dialog-header');
});
it('should apply custom className', () => {
render(<DialogHeader className="custom-class">Header</DialogHeader>);
const header = screen.getByText('Header');
expect(header).toHaveClass('custom-class');
});
});
describe('DialogTitle', () => {
it('should render title text', () => {
render(
<Dialog open>
<DialogTitle>Dialog Title</DialogTitle>
</Dialog>
);
expect(screen.getByText('Dialog Title')).toBeInTheDocument();
});
it('should have data-slot attribute', () => {
render(
<Dialog open>
<DialogTitle data-testid="title">Title</DialogTitle>
</Dialog>
);
expect(screen.getByTestId('title')).toHaveAttribute('data-slot', 'dialog-title');
});
it('should apply custom className', () => {
render(
<Dialog open>
<DialogTitle className="custom-title">Title</DialogTitle>
</Dialog>
);
expect(screen.getByText('Title')).toHaveClass('custom-title');
});
});
describe('DialogDescription', () => {
it('should render description text', () => {
render(
<Dialog open>
<DialogDescription>Dialog Description</DialogDescription>
</Dialog>
);
expect(screen.getByText('Dialog Description')).toBeInTheDocument();
});
it('should have data-slot attribute', () => {
render(
<Dialog open>
<DialogDescription data-testid="desc">Desc</DialogDescription>
</Dialog>
);
expect(screen.getByTestId('desc')).toHaveAttribute('data-slot', 'dialog-description');
});
it('should apply custom className', () => {
render(
<Dialog open>
<DialogDescription className="custom-desc">Desc</DialogDescription>
</Dialog>
);
expect(screen.getByText('Desc')).toHaveClass('custom-desc');
});
});
describe('DialogContent', () => {
it('should render content with children when open', () => {
render(
<Dialog open>
<DialogContent>Content Body</DialogContent>
</Dialog>
);
expect(screen.getByText('Content Body')).toBeInTheDocument();
});
});
describe('Dialog Composition', () => {
it('should render complete dialog structure', () => {
render(
<Dialog open>
<DialogTrigger>打开</DialogTrigger>
<DialogContent>
<DialogHeader>
<DialogTitle>确认操作</DialogTitle>
<DialogDescription>确定要执行此操作吗?</DialogDescription>
</DialogHeader>
</DialogContent>
</Dialog>
);
expect(screen.getByText('确认操作')).toBeInTheDocument();
expect(screen.getByText('确定要执行此操作吗?')).toBeInTheDocument();
});
});
});
-124
View File
@@ -1,124 +0,0 @@
'use client';
import * as React from 'react';
import * as DialogPrimitive from '@radix-ui/react-dialog';
import { X } from 'lucide-react';
import { cn } from '@/lib/utils';
/**
* 标准 shadcn/ui Dialog 组件
* 基于 @radix-ui/react-dialog
*/
const Dialog = DialogPrimitive.Root;
const DialogTrigger = DialogPrimitive.Trigger;
const DialogPortal = DialogPrimitive.Portal;
const DialogClose = DialogPrimitive.Close;
const DialogOverlay = React.forwardRef<
React.ElementRef<typeof DialogPrimitive.Overlay>,
React.ComponentPropsWithoutRef<typeof DialogPrimitive.Overlay>
>(({ className, ...props }, ref) => (
<DialogPrimitive.Overlay
ref={ref}
data-slot="dialog-overlay"
className={cn(
'fixed inset-0 z-50 bg-overlay/60 backdrop-blur-sm',
'data-[state=open]:animate-in data-[state=closed]:animate-out data-[state=closed]:fade-out-0 data-[state=open]:fade-in-0',
className
)}
{...props}
/>
));
DialogOverlay.displayName = DialogPrimitive.Overlay.displayName;
const DialogContent = React.forwardRef<
React.ElementRef<typeof DialogPrimitive.Content>,
React.ComponentPropsWithoutRef<typeof DialogPrimitive.Content>
>(({ className, children, ...props }, ref) => (
<DialogPortal>
<DialogOverlay />
<DialogPrimitive.Content
ref={ref}
data-slot="dialog-content"
className={cn(
'fixed left-[50%] top-[50%] z-50 grid w-full max-w-lg translate-x-[-50%] translate-y-[-50%] gap-4 border border-border-primary bg-bg-primary p-6 shadow-lg duration-fast',
'data-[state=open]:animate-in data-[state=closed]:animate-out data-[state=closed]:fade-out-0 data-[state=open]:fade-in-0 data-[state=closed]:zoom-out-95 data-[state=open]:zoom-in-95',
'sm:rounded-lg',
className
)}
{...props}
>
{children}
<DialogPrimitive.Close
data-slot="dialog-close"
className={cn(
'absolute right-4 top-4 rounded-sm opacity-70 transition-opacity',
'hover:opacity-100 focus:outline-none focus:ring-2 focus:ring-brand',
'disabled:pointer-events-none',
className
)}
>
<X className="size-4" />
<span className="sr-only">关闭</span>
</DialogPrimitive.Close>
</DialogPrimitive.Content>
</DialogPortal>
));
DialogContent.displayName = DialogPrimitive.Content.displayName;
const DialogHeader = ({ className, ...props }: React.ComponentProps<'div'>) => (
<div
data-slot="dialog-header"
className={cn('flex flex-col space-y-1.5 text-center sm:text-left', className)}
{...props}
/>
);
DialogHeader.displayName = 'DialogHeader';
const DialogFooter = ({ className, ...props }: React.ComponentProps<'div'>) => (
<div
data-slot="dialog-footer"
className={cn('flex flex-col-reverse sm:flex-row sm:justify-end sm:space-x-2', className)}
{...props}
/>
);
DialogFooter.displayName = 'DialogFooter';
const DialogTitle = React.forwardRef<
React.ElementRef<typeof DialogPrimitive.Title>,
React.ComponentPropsWithoutRef<typeof DialogPrimitive.Title>
>(({ className, ...props }, ref) => (
<DialogPrimitive.Title
ref={ref}
data-slot="dialog-title"
className={cn('text-lg font-semibold leading-none tracking-tight text-text-primary', className)}
{...props}
/>
));
DialogTitle.displayName = DialogPrimitive.Title.displayName;
const DialogDescription = React.forwardRef<
React.ElementRef<typeof DialogPrimitive.Description>,
React.ComponentPropsWithoutRef<typeof DialogPrimitive.Description>
>(({ className, ...props }, ref) => (
<DialogPrimitive.Description
ref={ref}
data-slot="dialog-description"
className={cn('text-sm text-text-muted', className)}
{...props}
/>
));
DialogDescription.displayName = DialogPrimitive.Description.displayName;
export {
Dialog,
DialogPortal,
DialogOverlay,
DialogTrigger,
DialogClose,
DialogContent,
DialogHeader,
DialogFooter,
DialogTitle,
DialogDescription,
};
-148
View File
@@ -1,148 +0,0 @@
'use client';
import { useReducer, useEffect } from 'react';
import { motion, AnimatePresence } from 'framer-motion';
interface FlipCardProps {
value: number;
label: string;
maxDigits?: number;
}
interface FlipDigitProps {
digit: number;
prevDigit: number;
}
function FlipDigit({ digit, prevDigit }: FlipDigitProps) {
return (
<div className="relative w-14 h-20 sm:w-16 sm:h-24 md:w-20 md:h-28 perspective-1000">
{/* 背景卡片 - 静态显示当前数字 */}
<div className="absolute inset-0 bg-gradient-to-b from-[var(--color-bg-primary)] via-[var(--color-bg-primary)] to-[var(--color-bg-secondary)] rounded-lg shadow-xl overflow-hidden border border-[var(--color-border-primary)]">
<div className="absolute top-0 left-0 right-0 h-1/2 bg-gradient-to-b from-[var(--color-bg-primary)] to-[var(--color-bg-secondary)] border-b border-[var(--color-border-primary)] overflow-hidden">
<div className="absolute inset-0 flex items-center justify-center text-4xl sm:text-5xl md:text-6xl font-bold text-[var(--color-brand)]">
{digit}
</div>
</div>
<div className="absolute bottom-0 left-0 right-0 h-1/2 bg-gradient-to-b from-[var(--color-bg-primary)] to-[var(--color-bg-secondary)] overflow-hidden">
<div className="absolute inset-0 flex items-center justify-center text-4xl sm:text-5xl md:text-6xl font-bold text-[var(--color-brand)]">
{digit}
</div>
</div>
</div>
{/* 翻转动画层 */}
<AnimatePresence custom={true}>
{/* 上半部分翻转 */}
<motion.div
key={`top-${prevDigit}`}
initial={{ rotateX: 0 }}
animate={{ rotateX: -180 }}
exit={{ rotateX: -180 }}
transition={{ duration: 0.6, ease: [0.4, 0, 0.2, 1] }}
className="absolute inset-0 bg-gradient-to-b from-[var(--color-bg-primary)] to-[var(--color-bg-secondary)] rounded-t-lg overflow-hidden border-t border-l border-r border-[var(--color-border-primary)]"
style={{
transformOrigin: 'bottom',
backfaceVisibility: 'hidden',
}}
>
<div className="absolute inset-0 flex items-center justify-center text-4xl sm:text-5xl md:text-6xl font-bold text-[var(--color-brand)]">
{prevDigit}
</div>
</motion.div>
{/* 下半部分翻转 */}
<motion.div
key={`bottom-${digit}`}
initial={{ rotateX: 180 }}
animate={{ rotateX: 0 }}
exit={{ rotateX: 0 }}
transition={{ duration: 0.6, ease: [0.4, 0, 0.2, 1] }}
className="absolute inset-0 bg-gradient-to-b from-[var(--color-bg-primary)] to-[var(--color-bg-secondary)] rounded-b-lg overflow-hidden border-b border-l border-r border-[var(--color-border-primary)]"
style={{
transformOrigin: 'top',
backfaceVisibility: 'hidden',
}}
>
<div className="absolute inset-0 flex items-center justify-center text-4xl sm:text-5xl md:text-6xl font-bold text-[var(--color-brand)]">
{digit}
</div>
</motion.div>
</AnimatePresence>
<div className="absolute top-1/2 left-0 right-0 h-px bg-[var(--color-border-primary)] transform -translate-y-1/2" />
<div className="absolute top-0 left-0 right-0 h-px bg-[var(--color-border-light)]/50" />
<div className="absolute bottom-0 left-0 right-0 h-px bg-[var(--color-border-light)]/50" />
{/* 侧面阴影增强立体感 */}
<div className="absolute inset-0 rounded-lg shadow-[inset_0_2px_4px_rgba(0,0,0,0.1)] pointer-events-none" />
</div>
);
}
function FlipCard({ value, label, maxDigits = 2 }: FlipCardProps) {
const [state, dispatch] = useReducer(
(prev: { current: number; previous: number }, next: number) => {
if (next === prev.current) {
return prev;
}
return { current: next, previous: prev.current };
},
{ current: value, previous: value }
);
useEffect(() => {
dispatch(value);
}, [value]);
const formatNumber = (num: number) => {
const str = num.toString().padStart(maxDigits, '0');
return str.split('').map(c => parseInt(c));
};
const currentDigits = formatNumber(state.current);
const prevDigits = formatNumber(state.previous);
return (
<div className="flex flex-col items-center">
<div className="flex gap-1 sm:gap-2 mb-3">
{currentDigits.map((digit, index) => (
<FlipDigit
key={index}
digit={digit}
prevDigit={prevDigits[index] ?? digit}
/>
))}
</div>
<div className="text-sm sm:text-base text-[var(--color-text-placeholder)] font-medium">{label}</div>
</div>
);
}
interface FlipClockProps {
years: number;
months: number;
days: number;
}
export function FlipClock({ years, months, days }: FlipClockProps) {
return (
<div className="bg-[var(--color-bg-secondary)] rounded-2xl p-8 border border-[var(--color-border-primary)]">
<h2 className="text-2xl font-bold text-[var(--color-text-primary)] mb-6">运营时长</h2>
<p className="text-[var(--color-text-placeholder)] mb-6 leading-relaxed">
自 <span className="font-semibold text-[var(--color-text-primary)]">2026 年 1 月 15 日</span> 成立以来
</p>
<div className="flex flex-wrap justify-center items-center gap-4 sm:gap-6 mb-6">
<FlipCard value={years} label="年" maxDigits={2} />
<div className="text-2xl sm:text-3xl font-bold text-[var(--color-brand)]">:</div>
<FlipCard value={months} label="个月" maxDigits={2} />
<div className="text-2xl sm:text-3xl font-bold text-[var(--color-brand)]">:</div>
<FlipCard value={days} label="天" maxDigits={3} />
</div>
<p className="text-[var(--color-text-placeholder)] leading-relaxed font-medium">
持续打磨产品,致力于为企业提供优质的数字化转型服务
</p>
</div>
);
}
-201
View File
@@ -1,201 +0,0 @@
// === shadcn/ui 标准组件 ===
export { Button, buttonVariants } from './button';
export type { ButtonProps } from './button';
export {
Card,
CardHeader,
CardFooter,
CardTitle,
CardAction,
CardDescription,
CardContent,
} from './card';
export { Badge, badgeVariants } from './badge';
export { Input } from './input';
export { Textarea } from './textarea';
export { Label, labelVariants } from './label';
export { LabeledInput } from './labeled-input';
export type { LabeledInputProps } from './labeled-input';
export { LabeledTextarea } from './labeled-textarea';
export type { LabeledTextareaProps } from './labeled-textarea';
export { Skeleton, SkeletonText, SkeletonCard, SkeletonList, SkeletonHero, SkeletonForm } from './skeleton';
// === 表单类 ===
export { Checkbox } from './checkbox';
export { Switch } from './switch';
export { RadioGroup, RadioGroupItem } from './radio-group';
export { Slider } from './slider';
export {
Select,
SelectGroup,
SelectValue,
SelectTrigger,
SelectContent,
SelectLabel,
SelectItem,
SelectSeparator,
SelectScrollUpButton,
SelectScrollDownButton,
} from './select';
export {
Form,
FormField,
FormItem,
FormLabel,
FormControl,
FormDescription,
FormMessage,
useFormField,
useFormWithZod,
} from './form';
// === 反馈类 ===
export { Alert, AlertTitle, AlertDescription, alertVariants } from './alert';
export {
AlertDialog,
AlertDialogPortal,
AlertDialogOverlay,
AlertDialogTrigger,
AlertDialogContent,
AlertDialogHeader,
AlertDialogFooter,
AlertDialogTitle,
AlertDialogDescription,
AlertDialogAction,
AlertDialogCancel,
} from './alert-dialog';
export {
Dialog,
DialogPortal,
DialogOverlay,
DialogTrigger,
DialogClose,
DialogContent,
DialogHeader,
DialogFooter,
DialogTitle,
DialogDescription,
} from './dialog';
export { Progress } from './progress';
// === 导航类 ===
export {
DropdownMenu,
DropdownMenuTrigger,
DropdownMenuContent,
DropdownMenuItem,
DropdownMenuCheckboxItem,
DropdownMenuRadioItem,
DropdownMenuLabel,
DropdownMenuSeparator,
DropdownMenuShortcut,
DropdownMenuGroup,
DropdownMenuPortal,
DropdownMenuSub,
DropdownMenuSubContent,
DropdownMenuSubTrigger,
DropdownMenuRadioGroup,
} from './dropdown-menu';
export { Tabs, TabsList, TabsTrigger, TabsContent } from './tabs';
export { Accordion, AccordionItem, AccordionTrigger, AccordionContent } from './accordion';
export {
Pagination,
PaginationContent,
PaginationLink,
PaginationItem,
PaginationPrevious,
PaginationNext,
PaginationEllipsis,
} from './pagination';
export {
Breadcrumb,
BreadcrumbList,
BreadcrumbItem,
BreadcrumbLink,
BreadcrumbPage,
BreadcrumbSeparator,
BreadcrumbEllipsis,
} from './breadcrumb';
// === 数据类 ===
export {
Table,
TableHeader,
TableBody,
TableFooter,
TableHead,
TableRow,
TableCell,
TableCaption,
} from './table';
export { Avatar, AvatarImage, AvatarFallback } from './avatar';
export { Separator } from './separator';
export { ScrollArea, ScrollBar } from './scroll-area';
// === 浮层类 ===
export {
Tooltip,
TooltipTrigger,
TooltipContent,
TooltipProvider,
LegacyTooltip,
} from './tooltip';
export { Popover, PopoverTrigger, PopoverContent, PopoverAnchor } from './popover';
export { HoverCard, HoverCardTrigger, HoverCardContent } from './hover-card';
export {
ContextMenu,
ContextMenuTrigger,
ContextMenuContent,
ContextMenuItem,
ContextMenuCheckboxItem,
ContextMenuRadioItem,
ContextMenuLabel,
ContextMenuSeparator,
ContextMenuShortcut,
ContextMenuGroup,
ContextMenuPortal,
ContextMenuSub,
ContextMenuSubContent,
ContextMenuSubTrigger,
ContextMenuRadioGroup,
} from './context-menu';
// === Toast (Sonner) ===
export { Toaster, toast } from './sonner';
export { Toast } from './toast';
// === 业务自定义组件(保留) ===
export { ScrollReveal, StaggerReveal } from './scroll-reveal';
export { ScrollProgress } from './scroll-progress';
export { BackToTop } from './back-to-top';
export { StaticLink } from './static-link';
export { Spinner, LoadingState, PageLoader, useLoadingState } from './loading-state';
export { ErrorBoundary } from './error-boundary';
export { PageTransition, StaggerChildren } from './page-transition';
export {
EASE_OUT,
GrainOverlay,
SectionLabel,
} from './page-decoration';
export {
GeometricDecoration,
DataBar,
GradientDivider,
BrandStamp,
} from './brand-visuals';
export { ChallengeCard } from './challenge-card';
export { ProductCard as UiProductCard } from './product-card';
export { DetailSwipeNav } from './detail-swipe-nav';
export { FlipClock } from './flip-clock';
export { AnimatedCounter } from './animated-counter';
export { MetricCard } from './metric-card';
export { StatsShowcase } from './stats-showcase';
export { MilestoneTimeline } from './milestone-timeline';
-150
View File
@@ -1,150 +0,0 @@
import { describe, it, expect } from '@jest/globals';
import { render } from '@testing-library/react';
import '@testing-library/jest-dom';
import {
Skeleton,
CardSkeleton,
ServiceCardSkeleton,
CaseCardSkeleton,
ProductCardSkeleton,
NewsCardSkeleton,
SectionSkeleton,
} from './loading-skeleton';
describe('Loading Skeleton Components', () => {
describe('Skeleton', () => {
it('should render skeleton element', () => {
const { container } = render(<Skeleton />);
expect(container.firstChild).toBeInTheDocument();
});
it('should apply default styles', () => {
const { container } = render(<Skeleton />);
const skeleton = container.firstChild as HTMLElement;
// loading-skeleton.tsx 使用 skeleton-brand 自定义类
expect(skeleton).toHaveClass('skeleton-brand');
expect(skeleton).toHaveClass('rounded-md');
});
it('should apply custom className', () => {
const { container } = render(<Skeleton className="custom-class" />);
const skeleton = container.firstChild as HTMLElement;
expect(skeleton).toHaveClass('custom-class');
});
});
describe('CardSkeleton', () => {
it('should render card skeleton', () => {
const { container } = render(<CardSkeleton />);
expect(container.firstChild).toBeInTheDocument();
});
it('should have correct structure', () => {
const { container } = render(<CardSkeleton />);
// CardSkeleton 包含 4 个子 Skeleton,使用 skeleton-brand 类
const skeletonElements = container.querySelectorAll('.skeleton-brand');
expect(skeletonElements.length).toBeGreaterThan(0);
});
});
describe('ServiceCardSkeleton', () => {
it('should render service card skeleton', () => {
const { container } = render(<ServiceCardSkeleton />);
expect(container.firstChild).toBeInTheDocument();
});
it('should have full height', () => {
const { container } = render(<ServiceCardSkeleton />);
const card = container.firstChild as HTMLElement;
expect(card).toHaveClass('h-full');
});
});
describe('CaseCardSkeleton', () => {
it('should render case card skeleton', () => {
const { container } = render(<CaseCardSkeleton />);
expect(container.firstChild).toBeInTheDocument();
});
it('should have image placeholder', () => {
const { container } = render(<CaseCardSkeleton />);
const imageSkeleton = container.querySelector('.h-48');
expect(imageSkeleton).toBeInTheDocument();
});
});
describe('ProductCardSkeleton', () => {
it('should render product card skeleton', () => {
const { container } = render(<ProductCardSkeleton />);
expect(container.firstChild).toBeInTheDocument();
});
it('should have flex column layout', () => {
const { container } = render(<ProductCardSkeleton />);
const card = container.firstChild as HTMLElement;
expect(card).toHaveClass('flex');
expect(card).toHaveClass('flex-col');
});
});
describe('NewsCardSkeleton', () => {
it('should render news card skeleton', () => {
const { container } = render(<NewsCardSkeleton />);
expect(container.firstChild).toBeInTheDocument();
});
it('should have image placeholder', () => {
const { container } = render(<NewsCardSkeleton />);
const imageSkeleton = container.querySelector('.h-48');
expect(imageSkeleton).toBeInTheDocument();
});
});
describe('SectionSkeleton', () => {
it('should render section skeleton', () => {
const { container } = render(<SectionSkeleton />);
expect(container.firstChild).toBeInTheDocument();
});
it('should render multiple service card skeletons', () => {
const { container } = render(<SectionSkeleton />);
// SectionSkeleton 渲染 4 个 ServiceCardSkeleton
// ServiceCardSkeleton 容器使用 var(--color-bg-primary)
const cards = container.querySelectorAll('.skeleton-brand');
// 每个 ServiceCardSkeleton 包含 4 个 Skeleton,4 个卡片共 16 个
expect(cards.length).toBeGreaterThanOrEqual(4);
});
});
describe('Accessibility', () => {
it('should not have any accessible content', () => {
const { container } = render(<CardSkeleton />);
const textContent = container.textContent;
expect(textContent).toBe('');
});
it('should be purely decorative', () => {
const { container } = render(<SectionSkeleton />);
const elements = container.querySelectorAll('*');
elements.forEach(element => {
expect(element).not.toHaveAttribute('aria-label');
expect(element).not.toHaveAttribute('aria-labelledby');
});
});
});
describe('Animation', () => {
it('should have pulse animation', () => {
const { container } = render(<Skeleton />);
const skeleton = container.firstChild as HTMLElement;
// loading-skeleton.tsx 使用 skeleton-brand 自定义类(CSS 中包含动画)
expect(skeleton).toHaveClass('skeleton-brand');
});
it('should apply animation to all skeleton elements', () => {
const { container } = render(<CardSkeleton />);
const skeletons = container.querySelectorAll('.skeleton-brand');
expect(skeletons.length).toBeGreaterThan(0);
});
});
});
-96
View File
@@ -1,96 +0,0 @@
'use client';
import { cn } from '@/lib/utils';
interface SkeletonProps {
className?: string;
}
export function Skeleton({ className }: SkeletonProps) {
return (
<div
className={cn(
'skeleton-brand rounded-md',
className
)}
/>
);
}
export function CardSkeleton() {
return (
<div className="bg-[var(--color-bg-section)] rounded-xl border border-[var(--color-border-primary)] p-6">
<Skeleton className="h-12 w-12 rounded-xl mb-4" />
<Skeleton className="h-6 w-3/4 mb-3" />
<Skeleton className="h-4 w-full mb-2" />
<Skeleton className="h-4 w-2/3" />
</div>
);
}
export function ServiceCardSkeleton() {
return (
<div className="bg-[var(--color-bg-primary)] rounded-xl border border-[var(--color-border-primary)] p-6 h-full">
<Skeleton className="h-14 w-14 rounded-xl mb-4" />
<Skeleton className="h-6 w-3/4 mb-3" />
<Skeleton className="h-4 w-full mb-2" />
<Skeleton className="h-4 w-2/3" />
</div>
);
}
export function CaseCardSkeleton() {
return (
<div className="bg-[var(--color-bg-primary)] rounded-xl border border-[var(--color-border-primary)] overflow-hidden">
<Skeleton className="h-48 w-full" />
<div className="p-6">
<Skeleton className="h-5 w-1/2 mb-3" />
<Skeleton className="h-6 w-3/4 mb-3" />
<Skeleton className="h-4 w-full mb-2" />
<Skeleton className="h-4 w-2/3" />
</div>
</div>
);
}
export function ProductCardSkeleton() {
return (
<div className="bg-[var(--color-bg-section)] rounded-xl border border-[var(--color-border-primary)] p-6 h-full flex flex-col">
<Skeleton className="h-6 w-1/3 mb-3" />
<Skeleton className="h-7 w-3/4 mb-4" />
<Skeleton className="h-4 w-full mb-2" />
<Skeleton className="h-4 w-2/3 mb-4" />
<Skeleton className="h-10 w-full mt-auto" />
</div>
);
}
export function NewsCardSkeleton() {
return (
<div className="bg-[var(--color-bg-primary)] rounded-xl border border-[var(--color-border-primary)] overflow-hidden">
<Skeleton className="h-48 w-full" />
<div className="p-6">
<Skeleton className="h-5 w-1/4 mb-3" />
<Skeleton className="h-6 w-3/4 mb-3" />
<Skeleton className="h-4 w-full mb-2" />
<Skeleton className="h-4 w-2/3" />
</div>
</div>
);
}
export function SectionSkeleton() {
return (
<div className="py-24">
<div className="container-wide">
<div className="max-w-6xl mx-auto">
<div className="grid md:grid-cols-2 gap-8">
{Array.from({ length: 4 }).map((_, index) => (
<ServiceCardSkeleton key={index} />
))}
</div>
</div>
</div>
</div>
);
}
+2 -2
View File
@@ -54,7 +54,7 @@ export function LoadingState({
if (isLoading && showSkeleton) {
return (
<div
className={cn('animate-in fade-in duration-300', className)}
className={cn('animate-in fade-in duration-normal', className)}
role="status"
aria-label="内容加载中"
aria-busy="true"
@@ -97,7 +97,7 @@ export function Spinner({ size = 'md', className }: SpinnerProps) {
return (
<svg
className={cn(
'animate-spin text-[var(--color-brand)]',
'animate-spin text-brand-ink',
sizeClasses[size],
className
)}
-104
View File
@@ -1,104 +0,0 @@
// @ts-nocheck
import { describe, it, expect, jest } from '@jest/globals';
import { render, screen } from '@testing-library/react';
import '@testing-library/jest-dom';
import { MetricCard } from './metric-card';
// ─── Mocks ───────────────────────────────────────────────────────────────
jest.mock('framer-motion', () => ({
motion: {
div: ({ children, className, ...props }: any) => (
<div className={className} {...props}>{children}</div>
),
span: ({ children, className, ...props }: any) => (
<span className={className} {...props}>{children}</span>
),
},
useInView: jest.fn(() => true),
}));
jest.mock('lucide-react', () => ({
ArrowUpRight: (props: any) => <svg data-testid="icon-trend-up" className={props.className} />,
ArrowDownRight: (props: any) => <svg data-testid="icon-trend-down" className={props.className} />,
}));
jest.mock('@/components/ui/animated-counter', () => ({
AnimatedCounter: ({ value, prefix, suffix }: any) => (
<span>{prefix}{value}{suffix}</span>
),
}));
// ─── Tests ───────────────────────────────────────────────────────────────
describe('MetricCard', () => {
it('should render label and value', () => {
render(<MetricCard label="客户数" value={500} />);
expect(screen.getByText('客户数')).toBeInTheDocument();
expect(screen.getByText('500')).toBeInTheDocument();
});
it('should render icon when provided', () => {
render(
<MetricCard
label="收入"
value={1000}
icon={<span data-testid="custom-icon">$</span>}
/>
);
expect(screen.getByTestId('custom-icon')).toBeInTheDocument();
});
it('should render prefix and suffix', () => {
render(<MetricCard label="增长率" value={99} prefix="+" suffix="%" />);
expect(screen.getByText('+99%')).toBeInTheDocument();
});
it('should render description when provided', () => {
render(<MetricCard label="用户" value={1000} description="活跃用户数" />);
expect(screen.getByText('活跃用户数')).toBeInTheDocument();
});
it('should render trend with up direction', () => {
render(
<MetricCard
label="收入"
value={500}
trend={{ value: '+12%', direction: 'up' }}
/>
);
expect(screen.getByText('+12%')).toBeInTheDocument();
expect(screen.getByTestId('icon-trend-up')).toBeInTheDocument();
});
it('should render trend with down direction', () => {
render(
<MetricCard
label="流失率"
value={5}
trend={{ value: '-2%', direction: 'down', label: '较上月' }}
/>
);
expect(screen.getByText('-2%')).toBeInTheDocument();
expect(screen.getByText('较上月')).toBeInTheDocument();
expect(screen.getByTestId('icon-trend-down')).toBeInTheDocument();
});
it('should apply custom className', () => {
const { container } = render(
<MetricCard label="测试" value={1} className="custom-class" />
);
const div = container.querySelector('.custom-class');
expect(div).toBeInTheDocument();
});
it('should render in dark theme', () => {
render(<MetricCard label="Dark" value={100} theme="dark" />);
expect(screen.getByText('Dark')).toBeInTheDocument();
});
it('should render with different accent colors', () => {
render(<MetricCard label="Blue" value={1} accentColor="blue" />);
expect(screen.getByText('Blue')).toBeInTheDocument();
});
});
-123
View File
@@ -1,123 +0,0 @@
'use client';
import type { ReactNode } from 'react';
import { ArrowUpRight, ArrowDownRight } from 'lucide-react';
import { AnimatedCounter } from '@/components/ui/animated-counter';
import { cn } from '@/lib/utils';
type TrendDirection = 'up' | 'down' | 'neutral';
interface MetricCardProps {
icon?: ReactNode;
label: string;
value: number;
prefix?: string;
suffix?: string;
decimals?: number;
description?: string;
trend?: {
value: string;
direction: TrendDirection;
label?: string;
};
accentColor?: 'brand' | 'blue' | 'teal' | 'amber' | 'purple';
className?: string;
theme?: 'light' | 'dark';
}
const accentStyles: Record<string, string> = {
brand: 'text-brand-ink bg-brand-bg',
blue: 'text-accent-blue bg-accent-blue/10',
teal: 'text-accent-teal bg-accent-teal/10',
amber: 'text-accent-amber bg-accent-amber/10',
purple: 'text-accent-purple bg-accent-purple/10',
};
const trendIcon = {
up: ArrowUpRight,
down: ArrowDownRight,
neutral: ArrowUpRight,
};
const trendColor: Record<TrendDirection, string> = {
up: 'text-success',
down: 'text-error',
neutral: 'text-text-muted',
};
export function MetricCard({
icon,
label,
value,
prefix = '',
suffix = '',
decimals = 0,
description,
trend,
accentColor = 'brand',
className,
theme = 'light',
}: MetricCardProps) {
const TrendIcon = trend ? trendIcon[trend.direction] : null;
const isDark = theme === 'dark';
return (
<div
className={cn(
'group relative overflow-hidden rounded-sm border p-6 sm:p-7 transition-all duration-300 ease-out',
isDark
? 'bg-overlay/50 border-white/[0.08] hover:border-white/20 hover:bg-overlay'
: 'border-border-primary bg-bg-primary hover:bg-bg-secondary',
className
)}
>
<div className="flex items-start justify-between mb-5">
{icon && (
<div
className={cn(
'flex w-12 h-12 items-center justify-center rounded-xl transition-transform duration-300 group-hover:scale-110',
accentStyles[accentColor]
)}
>
{icon}
</div>
)}
{trend && TrendIcon && (
<div className={cn('flex items-center gap-1 text-xs font-medium', trendColor[trend.direction])}>
<TrendIcon className="w-3.5 h-3.5" />
<span>{trend.value}</span>
{trend.label && <span className={isDark ? 'text-white/40' : 'text-text-subtle'}>{trend.label}</span>}
</div>
)}
</div>
<div className="space-y-1.5">
<div className={cn(
'text-sm font-medium tracking-wide uppercase',
isDark ? 'text-white/50' : 'text-text-muted'
)}>
{label}
</div>
<div className={cn(
'text-3xl sm:text-4xl font-bold tracking-tight',
isDark ? 'text-white' : 'text-text-primary'
)}>
<AnimatedCounter
value={value}
decimals={decimals}
prefix={prefix}
suffix={suffix}
/>
</div>
{description && (
<p className={cn(
'text-sm leading-relaxed pt-2',
isDark ? 'text-white/60' : 'text-text-muted'
)}>
{description}
</p>
)}
</div>
</div>
);
}
-129
View File
@@ -1,129 +0,0 @@
'use client';
import { useRef, useState, useEffect } from 'react';
import { cn } from '@/lib/utils';
interface MilestoneItem {
year: string;
title: string;
description: string;
highlight?: string;
icon?: React.ReactNode;
}
interface MilestoneTimelineProps {
items: MilestoneItem[];
className?: string;
variant?: 'horizontal' | 'vertical';
theme?: 'light' | 'dark';
}
export function MilestoneTimeline({
items,
className,
variant = 'horizontal',
theme = 'light',
}: MilestoneTimelineProps) {
const ref = useRef<HTMLDivElement>(null);
const [inView, setInView] = useState(false);
useEffect(() => {
const el = ref.current;
if (!el) return;
const observer = new IntersectionObserver(
([entry]) => {
if (entry?.isIntersecting) {
setInView(true);
observer.disconnect();
}
},
{ threshold: 0.15 },
);
observer.observe(el);
return () => observer.disconnect();
}, []);
const isDark = theme === 'dark';
if (variant === 'vertical') {
return (
<div ref={ref} className={cn('relative', className)}>
<div className={cn('absolute left-4 top-0 bottom-0 w-px', isDark ? 'bg-white/10' : 'bg-border-primary')} />
<div className="space-y-10">
{items.map((item, i) => (
<div
key={i}
className="relative pl-14"
style={{
opacity: inView ? 1 : 0,
transform: inView ? 'translateX(0)' : 'translateX(-20px)',
transition: `all 0.6s cubic-bezier(0.22, 1, 0.36, 1) ${i * 120}ms`,
}}
>
<div className={cn(
'absolute left-2 top-1 w-5 h-5 rounded-full border-2 flex items-center justify-center',
isDark ? 'bg-dark-bg border-brand' : 'bg-bg-primary border-brand'
)}>
<div className="w-2 h-2 rounded-full bg-brand" />
</div>
<div className="text-sm font-bold text-brand-ink mb-1 tracking-wider">
{item.year}
</div>
<h4 className={cn('text-lg font-semibold mb-2', isDark ? 'text-white' : 'text-text-primary')}>
{item.title}
</h4>
<p className={cn('text-sm leading-relaxed', isDark ? 'text-white/60' : 'text-text-muted')}>
{item.description}
</p>
{item.highlight && (
<div className={cn(
'mt-3 inline-flex items-center px-3 py-1 rounded-full text-xs font-medium',
isDark ? 'bg-brand/10 text-brand-ink' : 'bg-brand-bg text-brand-ink'
)}>
{item.highlight}
</div>
)}
</div>
))}
</div>
</div>
);
}
return (
<div ref={ref} className={cn('relative', className)}>
<div className={cn('absolute left-0 right-0 top-6 h-px', isDark ? 'bg-white/10' : 'bg-border-primary')} />
<div className="grid grid-cols-1 sm:grid-cols-2 md:grid-cols-4 gap-6 lg:gap-8">
{items.map((item, i) => (
<div
key={i}
className="relative pt-12 text-center"
style={{
opacity: inView ? 1 : 0,
transform: inView ? 'translateY(0)' : 'translateY(20px)',
transition: `all 0.6s cubic-bezier(0.22, 1, 0.36, 1) ${i * 120}ms`,
}}
>
<div className={cn(
'absolute top-4 left-1/2 -translate-x-1/2 w-5 h-5 rounded-full border-2 flex items-center justify-center z-10',
isDark ? 'bg-ink border-brand' : 'bg-bg-primary border-brand'
)}>
<div className="w-2 h-2 rounded-full bg-brand" />
</div>
<div className="text-sm font-bold text-brand-ink mb-2 tracking-wider">
{item.year}
</div>
<h4 className={cn('text-base font-semibold mb-2 leading-snug', isDark ? 'text-white' : 'text-text-primary')}>
{item.title}
</h4>
<p className={cn('text-xs sm:text-sm leading-relaxed', isDark ? 'text-white/60' : 'text-text-muted')}>
{item.description}
</p>
</div>
))}
</div>
</div>
);
}
+9
View File
@@ -0,0 +1,9 @@
'use client';
import { type ReactNode } from 'react';
import { MotionConfig } from 'framer-motion';
// 组件级 useReducedMotion 只覆盖显式调用它的文件;这里让全部 framer-motion 动效遵守系统设置(验收 R-5)
export function MotionProvider({ children }: { children: ReactNode }) {
return <MotionConfig reducedMotion="user">{children}</MotionConfig>;
}
+2 -2
View File
@@ -16,7 +16,7 @@ const pageVariants = {
y: 0,
scale: 1,
transition: {
duration: 0.3,
duration: 0.28,
ease: [0.25, 1, 0.5, 1] as const,
staggerChildren: 0.05,
},
@@ -72,7 +72,7 @@ const sectionVariants = {
y: 0,
transition: {
delay: i * 0.06,
duration: 0.3,
duration: 0.28,
ease: [0.25, 1, 0.5, 1] as const,
},
}),
+4 -4
View File
@@ -46,7 +46,7 @@ export function ProductCard({ title, description, href, index, status }: Product
return (
<a href={href}>
<Card className="group h-full relative overflow-hidden transition-all duration-300 hover:-translate-y-1 hover:shadow-lg">
<Card className="group h-full relative overflow-hidden transition-all duration-normal hover:-translate-y-1 hover:shadow-lg">
{/* 产品图标 */}
<div className="flex items-start justify-between mb-4">
<div
@@ -81,7 +81,7 @@ export function ProductCard({ title, description, href, index, status }: Product
</div>
{/* 标题 */}
<h3 className="text-base font-semibold mb-2 leading-snug tracking-tight text-[var(--color-text-primary)] group-hover:text-[var(--color-brand)] transition-colors">
<h3 className="text-base font-semibold mb-2 leading-snug tracking-tight text-[var(--color-text-primary)] group-hover:text-brand-ink transition-colors">
{title}
</h3>
@@ -92,7 +92,7 @@ export function ProductCard({ title, description, href, index, status }: Product
{/* 研发中/内测中 提示 */}
{(status === '研发中' || status === '内测中') && (
<div className="flex items-center gap-1.5 text-xs text-[var(--color-brand)]/70 mb-4 px-3 py-2 rounded-lg bg-[var(--color-brand-bg)]/50">
<div className="flex items-center gap-1.5 text-xs text-brand-ink/70 mb-4 px-3 py-2 rounded-lg bg-brand-bg/50">
<svg className="w-3.5 h-3.5 animate-spin" viewBox="0 0 24 24" fill="none">
<circle cx="12" cy="12" r="10" stroke="currentColor" strokeWidth="2.5" strokeLinecap="round" strokeDasharray="32 16" />
</svg>
@@ -101,7 +101,7 @@ export function ProductCard({ title, description, href, index, status }: Product
)}
{/* CTA 链接 */}
<div className="flex items-center gap-1.5 text-sm font-medium text-[var(--color-text-subtle)] group-hover:text-[var(--color-brand)] transition-colors min-h-[44px] mt-auto">
<div className="flex items-center gap-1.5 text-sm font-medium text-[var(--color-text-subtle)] group-hover:text-brand-ink transition-colors min-h-[44px] mt-auto">
<span>{status === '研发中' ? '了解规划' : status === '内测中' ? '申请内测' : '了解更多'}</span>
<ArrowUpRight className="w-4 h-4" strokeWidth={2} />
</div>
+27 -1
View File
@@ -1,15 +1,19 @@
import { render } from '@testing-library/react';
import '@testing-library/jest-dom';
import { ScrollProgress } from './scroll-progress';
import { useReducedMotion } from '@/hooks/use-reduced-motion';
// Mock useReducedMotion
jest.mock('@/hooks/use-reduced-motion', () => ({
useReducedMotion: () => false,
useReducedMotion: jest.fn(() => false),
}));
const mockedReduced = useReducedMotion as jest.MockedFunction<typeof useReducedMotion>;
describe('ScrollProgress', () => {
beforeEach(() => {
jest.clearAllMocks();
mockedReduced.mockReturnValue(false);
// Mock document/scroll geometry for predictable progress calculation
Object.defineProperty(document.documentElement, 'scrollHeight', {
value: 1000,
@@ -92,4 +96,26 @@ describe('ScrollProgress', () => {
expect(innerBar.style.background).toContain('255');
expect(innerBar.style.background).toContain('0');
});
it('prefers-reduced-motion 下只去掉过渡、保留进度宽度', () => {
mockedReduced.mockReturnValue(true);
Object.defineProperty(window, 'scrollY', { value: 250, configurable: true, writable: true });
const { container } = render(<ScrollProgress />);
const innerBar = (container.firstChild as HTMLElement).firstChild as HTMLElement;
// scrollY 250 / 可滚动高度 500 ⇒ 进度 50%:宽度信号不得被坍缩为 0
expect(innerBar.style.transform).toBe('scaleX(0.5)');
expect(innerBar.style.transition).toBe('none');
});
it('未开启 reduced-motion 时进度宽度与过渡同时在场', () => {
Object.defineProperty(window, 'scrollY', { value: 250, configurable: true, writable: true });
const { container } = render(<ScrollProgress />);
const innerBar = (container.firstChild as HTMLElement).firstChild as HTMLElement;
expect(innerBar.style.transform).toBe('scaleX(0.5)');
expect(innerBar.style.transition).toBe('transform 0.1s linear');
});
});
+1 -1
View File
@@ -56,7 +56,7 @@ export function ScrollProgress({
height: '100%',
background: color,
transformOrigin: 'left',
transform: `scaleX(${shouldReduceMotion ? 0 : progress / 100})`,
transform: `scaleX(${progress / 100})`,
transition: shouldReduceMotion ? 'none' : 'transform 0.1s linear',
}}
/>
+7 -4
View File
@@ -66,11 +66,11 @@ export function ScrollReveal({
xOffset = 0,
margin = '-40px',
variant = 'fadeIn',
// 入场时长默认值:CONTEXT.md L52「动效设计四原则 · Fast」规定入场 200-300ms。
// 原值 0.4(400ms)超出目标区间,改为 300ms(目标上限)。
// 注意:700ms 是「禁止超过」的硬上限(CONTEXT.md L58),不是目标值。
// 入场时长默认值:CONTEXT.md「动效设计四原则 · Fast」规定入场 180–280ms
// (即 --transition-fast … --transition-normal),另规定「禁止超过 700ms 的入场动效」。
// 原值 0.4 / 0.3 均超出区间,改为区间上限 0.28。
// 本默认值被 22 个文件消费,改动影响面大,需视觉回归。
duration = 0.3,
duration = 0.28,
once = true,
amount = 0,
}: ScrollRevealProps) {
@@ -96,6 +96,7 @@ export function ScrollReveal({
interface StaggerRevealProps {
children: ReactNode;
className?: string;
role?: string;
staggerDelay?: number;
delayChildren?: number;
variant?: RevealVariant;
@@ -108,6 +109,7 @@ interface StaggerRevealProps {
export function StaggerReveal({
children,
className = '',
role,
staggerDelay = 0.05,
delayChildren = 0.05,
variant = 'fadeIn',
@@ -136,6 +138,7 @@ export function StaggerReveal({
return (
<motion.div
className={className}
role={role}
initial="hidden"
whileInView="visible"
viewport={{ once, margin }}
-136
View File
@@ -1,136 +0,0 @@
// @ts-nocheck
import { describe, it, expect } from '@jest/globals';
import { render, screen } from '@testing-library/react';
import '@testing-library/jest-dom';
import {
Select,
SelectTrigger,
SelectContent,
SelectItem,
SelectValue,
} from './select';
describe('Select Components', () => {
describe('SelectTrigger', () => {
it('should render trigger with placeholder', () => {
render(
<Select>
<SelectTrigger>
<SelectValue placeholder="请选择" />
</SelectTrigger>
</Select>
);
expect(screen.getByText('请选择')).toBeInTheDocument();
});
it('should have data-slot attribute', () => {
render(
<Select>
<SelectTrigger data-testid="trigger">
<SelectValue placeholder="选择" />
</SelectTrigger>
</Select>
);
expect(screen.getByTestId('trigger')).toHaveAttribute('data-slot', 'select-trigger');
});
it('should apply custom className', () => {
render(
<Select>
<SelectTrigger className="custom-trigger" data-testid="trigger">
<SelectValue placeholder="选择" />
</SelectTrigger>
</Select>
);
expect(screen.getByTestId('trigger')).toHaveClass('custom-trigger');
});
it('should render with selected value', () => {
render(
<Select value="option1">
<SelectTrigger>
<SelectValue />
</SelectTrigger>
<SelectContent>
<SelectItem value="option1">选项一</SelectItem>
</SelectContent>
</Select>
);
expect(screen.getByText('选项一')).toBeInTheDocument();
});
});
describe('SelectContent', () => {
it('should render content with items when open', () => {
render(
<Select open>
<SelectContent>
<SelectItem value="option1">选项一</SelectItem>
<SelectItem value="option2">选项二</SelectItem>
</SelectContent>
</Select>
);
const items = screen.getAllByRole('option');
expect(items).toHaveLength(2);
expect(items[0]).toHaveTextContent('选项一');
expect(items[1]).toHaveTextContent('选项二');
});
});
describe('SelectItem', () => {
it('should render item text', () => {
render(
<Select open>
<SelectContent>
<SelectItem value="option1">选项一</SelectItem>
</SelectContent>
</Select>
);
const item = screen.getByRole('option');
expect(item).toHaveTextContent('选项一');
});
it('should have data-slot attribute', () => {
render(
<Select open>
<SelectContent>
<SelectItem value="opt1" data-testid="item">Item</SelectItem>
</SelectContent>
</Select>
);
expect(screen.getByTestId('item')).toHaveAttribute('data-slot', 'select-item');
});
it('should apply custom className', () => {
render(
<Select open>
<SelectContent>
<SelectItem value="opt1" className="custom-item" data-testid="item">Item</SelectItem>
</SelectContent>
</Select>
);
expect(screen.getByTestId('item')).toHaveClass('custom-item');
});
});
describe('Select Composition', () => {
it('should render complete select structure', () => {
render(
<Select open>
<SelectTrigger>
<SelectValue placeholder="请选择" />
</SelectTrigger>
<SelectContent>
<SelectItem value="cn">中文</SelectItem>
<SelectItem value="en">英文</SelectItem>
<SelectItem value="jp">日文</SelectItem>
</SelectContent>
</Select>
);
expect(screen.getByText('中文')).toBeInTheDocument();
expect(screen.getByText('英文')).toBeInTheDocument();
expect(screen.getByText('日文')).toBeInTheDocument();
});
});
});
-168
View File
@@ -1,168 +0,0 @@
'use client';
import * as React from 'react';
import * as SelectPrimitive from '@radix-ui/react-select';
import { Check, ChevronDown, ChevronUp } from 'lucide-react';
import { cn } from '@/lib/utils';
/**
* 标准 shadcn/ui Select 组件
* 基于 @radix-ui/react-select
*/
const Select = SelectPrimitive.Root;
const SelectGroup = SelectPrimitive.Group;
const SelectValue = SelectPrimitive.Value;
const SelectTrigger = React.forwardRef<
React.ElementRef<typeof SelectPrimitive.Trigger>,
React.ComponentPropsWithoutRef<typeof SelectPrimitive.Trigger>
>(({ className, children, ...props }, ref) => (
<SelectPrimitive.Trigger
ref={ref}
data-slot="select-trigger"
className={cn(
'flex h-11 w-full items-center justify-between rounded-md border border-border-primary bg-bg-primary px-3 py-2 text-sm shadow-sm',
'placeholder:text-text-placeholder',
'focus:outline-none focus-visible:ring-2 focus-visible:ring-brand focus-visible:ring-offset-2',
'disabled:cursor-not-allowed disabled:opacity-50',
'data-[placeholder]:text-text-placeholder',
'transition-colors duration-fast hover:border-border-secondary',
'[&>span]:line-clamp-1',
className
)}
{...props}
>
{children}
<SelectPrimitive.Icon asChild>
<ChevronDown className="size-4 opacity-50" />
</SelectPrimitive.Icon>
</SelectPrimitive.Trigger>
));
SelectTrigger.displayName = SelectPrimitive.Trigger.displayName;
const SelectScrollUpButton = React.forwardRef<
React.ElementRef<typeof SelectPrimitive.ScrollUpButton>,
React.ComponentPropsWithoutRef<typeof SelectPrimitive.ScrollUpButton>
>(({ className, ...props }, ref) => (
<SelectPrimitive.ScrollUpButton
ref={ref}
data-slot="select-scroll-up-button"
className={cn('flex cursor-default items-center justify-center py-1', className)}
{...props}
>
<ChevronUp className="size-4" />
</SelectPrimitive.ScrollUpButton>
));
SelectScrollUpButton.displayName = SelectPrimitive.ScrollUpButton.displayName;
const SelectScrollDownButton = React.forwardRef<
React.ElementRef<typeof SelectPrimitive.ScrollDownButton>,
React.ComponentPropsWithoutRef<typeof SelectPrimitive.ScrollDownButton>
>(({ className, ...props }, ref) => (
<SelectPrimitive.ScrollDownButton
ref={ref}
data-slot="select-scroll-down-button"
className={cn('flex cursor-default items-center justify-center py-1', className)}
{...props}
>
<ChevronDown className="size-4" />
</SelectPrimitive.ScrollDownButton>
));
SelectScrollDownButton.displayName = SelectPrimitive.ScrollDownButton.displayName;
const SelectContent = React.forwardRef<
React.ElementRef<typeof SelectPrimitive.Content>,
React.ComponentPropsWithoutRef<typeof SelectPrimitive.Content>
>(({ className, children, position = 'popper', ...props }, ref) => (
<SelectPrimitive.Portal>
<SelectPrimitive.Content
ref={ref}
data-slot="select-content"
className={cn(
'relative z-50 max-h-96 min-w-[8rem] overflow-hidden rounded-md border border-border-primary bg-bg-primary text-text-primary shadow-md',
'data-[state=open]:animate-in data-[state=closed]:animate-out data-[state=closed]:fade-out-0 data-[state=open]:fade-in-0 data-[state=closed]:zoom-out-95 data-[state=open]:zoom-in-95',
'data-[side=bottom]:slide-in-from-top-2 data-[side=left]:slide-in-from-right-2 data-[side=right]:slide-in-from-left-2 data-[side=top]:slide-in-from-bottom-2',
position === 'popper' && 'data-[side=bottom]:translate-y-1 data-[side=left]:-translate-x-1 data-[side=right]:translate-x-1 data-[side=top]:-translate-y-1',
className
)}
position={position}
{...props}
>
<SelectScrollUpButton />
<SelectPrimitive.Viewport
className={cn(
'p-1',
position === 'popper' && 'h-[var(--radix-select-trigger-height)] w-full min-w-[var(--radix-select-trigger-width)]'
)}
>
{children}
</SelectPrimitive.Viewport>
<SelectScrollDownButton />
</SelectPrimitive.Content>
</SelectPrimitive.Portal>
));
SelectContent.displayName = SelectPrimitive.Content.displayName;
const SelectLabel = React.forwardRef<
React.ElementRef<typeof SelectPrimitive.Label>,
React.ComponentPropsWithoutRef<typeof SelectPrimitive.Label>
>(({ className, ...props }, ref) => (
<SelectPrimitive.Label
ref={ref}
data-slot="select-label"
className={cn('px-2 py-1.5 text-xs font-medium text-text-muted', className)}
{...props}
/>
));
SelectLabel.displayName = SelectPrimitive.Label.displayName;
const SelectItem = React.forwardRef<
React.ElementRef<typeof SelectPrimitive.Item>,
React.ComponentPropsWithoutRef<typeof SelectPrimitive.Item>
>(({ className, children, ...props }, ref) => (
<SelectPrimitive.Item
ref={ref}
data-slot="select-item"
className={cn(
'relative flex w-full cursor-default select-none items-center rounded-sm py-1.5 pl-2 pr-8 text-sm outline-none',
'focus:bg-bg-secondary focus:text-text-primary',
'data-[disabled]:pointer-events-none data-[disabled]:opacity-50',
className
)}
{...props}
>
<span className="absolute right-2 flex size-3.5 items-center justify-center">
<SelectPrimitive.ItemIndicator>
<Check className="size-4 text-brand-ink" />
</SelectPrimitive.ItemIndicator>
</span>
<SelectPrimitive.ItemText>{children}</SelectPrimitive.ItemText>
</SelectPrimitive.Item>
));
SelectItem.displayName = SelectPrimitive.Item.displayName;
const SelectSeparator = React.forwardRef<
React.ElementRef<typeof SelectPrimitive.Separator>,
React.ComponentPropsWithoutRef<typeof SelectPrimitive.Separator>
>(({ className, ...props }, ref) => (
<SelectPrimitive.Separator
ref={ref}
data-slot="select-separator"
className={cn('-mx-1 my-1 h-px bg-border-primary', className)}
{...props}
/>
));
SelectSeparator.displayName = SelectPrimitive.Separator.displayName;
export {
Select,
SelectGroup,
SelectValue,
SelectTrigger,
SelectContent,
SelectLabel,
SelectItem,
SelectSeparator,
SelectScrollUpButton,
SelectScrollDownButton,
};
-142
View File
@@ -1,142 +0,0 @@
'use client';
import { useRef, useState, useEffect } from 'react';
import { AnimatedCounter } from '@/components/ui/animated-counter';
import { cn } from '@/lib/utils';
interface StatShowcaseItem {
value: number;
prefix?: string;
suffix?: string;
decimals?: number;
label: string;
description?: string;
accent?: string;
}
interface StatsShowcaseProps {
items: StatShowcaseItem[];
columns?: 2 | 3 | 4;
variant?: 'default' | 'dark' | 'minimal';
className?: string;
}
export function StatsShowcase({
items,
columns = 4,
variant = 'default',
className,
}: StatsShowcaseProps) {
const sectionRef = useRef<HTMLDivElement>(null);
const [inView, setInView] = useState(false);
useEffect(() => {
const el = sectionRef.current;
if (!el) return;
const observer = new IntersectionObserver(
([entry]) => {
if (entry?.isIntersecting) {
setInView(true);
observer.disconnect();
}
},
{ threshold: 0.2 },
);
observer.observe(el);
return () => observer.disconnect();
}, []);
const gridCols = {
2: 'grid-cols-1 sm:grid-cols-2',
3: 'grid-cols-1 sm:grid-cols-2 lg:grid-cols-3',
4: 'grid-cols-2 sm:grid-cols-2 lg:grid-cols-4',
};
const isDark = variant === 'dark';
return (
<div
ref={sectionRef}
className={cn(
'grid gap-px overflow-hidden rounded-sm',
gridCols[columns],
isDark
? 'bg-white/5'
: 'bg-border-primary',
className
)}
>
{items.map((item, i) => (
<div
key={i}
className={cn(
'relative p-8 sm:p-10 md:p-12 text-center transition-all duration-300 group',
isDark ? 'bg-dark-bg hover:bg-dark-bg-secondary' : 'bg-bg-primary hover:bg-bg-hover'
)}
>
<div className="relative z-10">
<div
className={cn(
'font-sans text-[clamp(40px,9vw,72px)] font-bold leading-none mb-3 tracking-tight',
isDark ? 'text-white' : 'text-text-primary'
)}
style={{
opacity: inView ? 1 : 0,
transform: inView ? 'translateY(0)' : 'translateY(12px)',
transition: `all 0.7s cubic-bezier(0.22, 1, 0.36, 1) ${i * 100}ms`,
}}
>
<AnimatedCounter
value={item.value}
decimals={item.decimals || 0}
prefix={item.prefix}
suffix={item.suffix}
startOnView={false}
duration={1800}
/>
</div>
<div
className={cn(
'text-xs sm:text-sm font-medium tracking-[0.15em] uppercase mb-3',
isDark ? 'text-white/60' : 'text-text-muted'
)}
style={{
opacity: inView ? 1 : 0,
transform: inView ? 'translateY(0)' : 'translateY(8px)',
transition: `all 0.6s cubic-bezier(0.22, 1, 0.36, 1) ${i * 100 + 150}ms`,
}}
>
{item.label}
</div>
{item.description && (
<div
className={cn(
'text-xs sm:text-sm leading-relaxed max-w-[200px] mx-auto',
isDark ? 'text-white/40' : 'text-text-subtle'
)}
style={{
opacity: inView ? 1 : 0,
transform: inView ? 'translateY(0)' : 'translateY(6px)',
transition: `all 0.6s cubic-bezier(0.22, 1, 0.36, 1) ${i * 100 + 250}ms`,
}}
>
{item.description}
</div>
)}
</div>
{item.accent && (
<div
className="absolute top-0 left-1/2 -translate-x-1/2 w-12 h-0.5 opacity-0 group-hover:opacity-100 transition-opacity duration-150"
style={{ backgroundColor: item.accent }}
/>
)}
</div>
))}
</div>
);
}
-148
View File
@@ -1,148 +0,0 @@
// @ts-nocheck
import { describe, it, expect } from '@jest/globals';
import { render, screen } from '@testing-library/react';
import '@testing-library/jest-dom';
import { Tabs, TabsList, TabsTrigger, TabsContent } from './tabs';
describe('Tabs Components', () => {
describe('TabsList', () => {
it('should render list with children', () => {
render(
<Tabs defaultValue="tab1">
<TabsList>
<TabsTrigger value="tab1">Tab 1</TabsTrigger>
</TabsList>
</Tabs>
);
expect(screen.getByText('Tab 1')).toBeInTheDocument();
});
it('should have data-slot attribute', () => {
render(
<Tabs defaultValue="tab1">
<TabsList data-testid="list">List</TabsList>
</Tabs>
);
expect(screen.getByTestId('list')).toHaveAttribute('data-slot', 'tabs-list');
});
it('should apply custom className', () => {
render(
<Tabs defaultValue="tab1">
<TabsList className="custom-list">List</TabsList>
</Tabs>
);
expect(screen.getByText('List')).toHaveClass('custom-list');
});
});
describe('TabsTrigger', () => {
it('should render trigger text', () => {
render(
<Tabs defaultValue="tab1">
<TabsList>
<TabsTrigger value="tab1">标签一</TabsTrigger>
</TabsList>
</Tabs>
);
expect(screen.getByText('标签一')).toBeInTheDocument();
});
it('should have data-slot attribute', () => {
render(
<Tabs defaultValue="tab1">
<TabsList>
<TabsTrigger value="tab1" data-testid="trigger">Trigger</TabsTrigger>
</TabsList>
</Tabs>
);
expect(screen.getByTestId('trigger')).toHaveAttribute('data-slot', 'tabs-trigger');
});
it('should apply custom className', () => {
render(
<Tabs defaultValue="tab1">
<TabsList>
<TabsTrigger value="tab1" className="custom-trigger">Trigger</TabsTrigger>
</TabsList>
</Tabs>
);
expect(screen.getByText('Trigger')).toHaveClass('custom-trigger');
});
it('should handle disabled state', () => {
render(
<Tabs defaultValue="tab1">
<TabsList>
<TabsTrigger value="tab1" disabled>Disabled</TabsTrigger>
</TabsList>
</Tabs>
);
expect(screen.getByText('Disabled')).toBeDisabled();
});
});
describe('TabsContent', () => {
it('should render content when value matches', () => {
render(
<Tabs defaultValue="tab1">
<TabsContent value="tab1">内容一</TabsContent>
</Tabs>
);
expect(screen.getByText('内容一')).toBeInTheDocument();
});
it('should have data-slot attribute', () => {
render(
<Tabs defaultValue="tab1">
<TabsContent value="tab1" data-testid="content">Content</TabsContent>
</Tabs>
);
expect(screen.getByTestId('content')).toHaveAttribute('data-slot', 'tabs-content');
});
it('should apply custom className', () => {
render(
<Tabs defaultValue="tab1">
<TabsContent value="tab1" className="custom-content">Content</TabsContent>
</Tabs>
);
expect(screen.getByText('Content')).toHaveClass('custom-content');
});
});
describe('Tabs Composition', () => {
it('should render complete tabs structure', () => {
render(
<Tabs defaultValue="tab1">
<TabsList>
<TabsTrigger value="tab1">标签一</TabsTrigger>
<TabsTrigger value="tab2">标签二</TabsTrigger>
</TabsList>
<TabsContent value="tab1">内容一</TabsContent>
<TabsContent value="tab2">内容二</TabsContent>
</Tabs>
);
expect(screen.getByText('标签一')).toBeInTheDocument();
expect(screen.getByText('标签二')).toBeInTheDocument();
expect(screen.getByText('内容一')).toBeInTheDocument();
});
it('should not show content for non-matching tab', () => {
render(
<Tabs defaultValue="tab1">
<TabsList>
<TabsTrigger value="tab1">Tab 1</TabsTrigger>
<TabsTrigger value="tab2">Tab 2</TabsTrigger>
</TabsList>
<TabsContent value="tab1">Content 1</TabsContent>
<TabsContent value="tab2">Content 2</TabsContent>
</Tabs>
);
expect(screen.getByText('Content 1')).toBeInTheDocument();
expect(screen.queryByText('Content 2')).not.toBeInTheDocument();
});
});
});
-65
View File
@@ -1,65 +0,0 @@
'use client';
import * as React from 'react';
import * as TabsPrimitive from '@radix-ui/react-tabs';
import { cn } from '@/lib/utils';
/**
* 标准 shadcn/ui Tabs 组件
* 基于 @radix-ui/react-tabs
*/
const Tabs = TabsPrimitive.Root;
const TabsList = React.forwardRef<
React.ElementRef<typeof TabsPrimitive.List>,
React.ComponentPropsWithoutRef<typeof TabsPrimitive.List>
>(({ className, ...props }, ref) => (
<TabsPrimitive.List
ref={ref}
data-slot="tabs-list"
className={cn(
'inline-flex h-10 items-center justify-center rounded-md bg-bg-tertiary p-1 text-text-muted',
className
)}
{...props}
/>
));
TabsList.displayName = TabsPrimitive.List.displayName;
const TabsTrigger = React.forwardRef<
React.ElementRef<typeof TabsPrimitive.Trigger>,
React.ComponentPropsWithoutRef<typeof TabsPrimitive.Trigger>
>(({ className, ...props }, ref) => (
<TabsPrimitive.Trigger
ref={ref}
data-slot="tabs-trigger"
className={cn(
'inline-flex items-center justify-center whitespace-nowrap rounded-sm px-3 py-1.5 text-sm font-medium',
'ring-offset-background transition-all duration-fast',
'focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-brand focus-visible:ring-offset-2',
'disabled:pointer-events-none disabled:opacity-50',
'data-[state=active]:bg-bg-primary data-[state=active]:text-text-primary data-[state=active]:shadow-sm',
className
)}
{...props}
/>
));
TabsTrigger.displayName = TabsPrimitive.Trigger.displayName;
const TabsContent = React.forwardRef<
React.ElementRef<typeof TabsPrimitive.Content>,
React.ComponentPropsWithoutRef<typeof TabsPrimitive.Content>
>(({ className, ...props }, ref) => (
<TabsPrimitive.Content
ref={ref}
data-slot="tabs-content"
className={cn(
'mt-2 ring-offset-background focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-brand focus-visible:ring-offset-2',
className
)}
{...props}
/>
));
TabsContent.displayName = TabsPrimitive.Content.displayName;
export { Tabs, TabsList, TabsTrigger, TabsContent };