sms
All checks were successful
Deploy to Server / deploy (push) Successful in 25s

This commit is contained in:
jeremygan2021
2026-02-16 20:15:26 +08:00
parent 91d82b78b5
commit b2f9545fdd
39 changed files with 5481 additions and 0 deletions

View File

@@ -0,0 +1,281 @@
import React, { useState, useEffect } from 'react';
import { Modal, Form, Input, Button, message, Upload, Select } from 'antd';
import { UploadOutlined } from '@ant-design/icons';
import { createTopic, updateTopic, uploadMedia, getMyPaidItems } from '../api';
import MDEditor from '@uiw/react-md-editor';
import rehypeKatex from 'rehype-katex';
import remarkMath from 'remark-math';
import 'katex/dist/katex.css';
const { Option } = Select;
const CreateTopicModal = ({ visible, onClose, onSuccess, initialValues, isEditMode, topicId }) => {
const [form] = Form.useForm();
const [loading, setLoading] = useState(false);
const [paidItems, setPaidItems] = useState({ configs: [], courses: [], services: [] });
const [uploading, setUploading] = useState(false);
const [mediaIds, setMediaIds] = useState([]);
// eslint-disable-next-line no-unused-vars
const [mediaList, setMediaList] = useState([]); // Store uploaded media details for preview
const [content, setContent] = useState("");
useEffect(() => {
if (visible) {
fetchPaidItems();
if (isEditMode && initialValues) {
// Edit Mode: Populate form with initial values
form.setFieldsValue({
title: initialValues.title,
category: initialValues.category,
});
setContent(initialValues.content);
form.setFieldValue('content', initialValues.content);
// Handle related item
let relatedVal = null;
if (initialValues.related_product) relatedVal = `config_${initialValues.related_product.id || initialValues.related_product}`;
else if (initialValues.related_course) relatedVal = `course_${initialValues.related_course.id || initialValues.related_course}`;
else if (initialValues.related_service) relatedVal = `service_${initialValues.related_service.id || initialValues.related_service}`;
if (relatedVal) form.setFieldValue('related_item', relatedVal);
// Note: We start with empty *new* media IDs.
// Existing media is embedded in content or stored in DB, we don't need to re-upload or track them here unless we want to delete them (which is complex).
// For now, we just allow adding NEW media.
setMediaIds([]);
setMediaList([]);
} else {
// Create Mode: Reset form
setMediaIds([]);
setMediaList([]);
setContent("");
form.resetFields();
form.setFieldsValue({ content: "", category: 'discussion' });
}
}
}, [visible, isEditMode, initialValues, form]);
const fetchPaidItems = async () => {
try {
const res = await getMyPaidItems();
setPaidItems(res.data);
} catch (error) {
console.error("Failed to fetch paid items", error);
}
};
const handleUpload = async (file) => {
const formData = new FormData();
formData.append('file', file);
// 默认为 image如果需要支持视频需根据 file.type 判断
formData.append('media_type', file.type.startsWith('video') ? 'video' : 'image');
setUploading(true);
try {
const res = await uploadMedia(formData);
// 记录上传的媒体 ID
if (res.data.id) {
setMediaIds(prev => [...prev, res.data.id]);
}
// 确保 URL 是完整的
// 由于后端现在是转发到外部OSS返回的URL通常是完整的但也可能是相对的这里统一处理
let url = res.data.file;
// 处理反斜杠问题(防止 Windows 路径风格影响 URL
if (url) {
url = url.replace(/\\/g, '/');
}
if (url && !url.startsWith('http')) {
// 如果返回的是相对路径,拼接 API URL 或 Base URL
const baseURL = import.meta.env.VITE_API_URL || 'http://localhost:8000';
// 移除 baseURL 末尾的 /api 或 /
const host = baseURL.replace(/\/api\/?$/, '');
// 确保 url 以 / 开头
if (!url.startsWith('/')) url = '/' + url;
url = `${host}${url}`;
}
// 清理 URL 中的双斜杠 (除协议头外)
url = url.replace(/([^:]\/)\/+/g, '$1');
// Add to media list for preview
setMediaList(prev => [...prev, {
id: res.data.id,
url: url,
type: file.type.startsWith('video') ? 'video' : 'image',
name: file.name
}]);
// 插入到编辑器
const insertText = file.type.startsWith('video')
? `\n<video src="${url}" controls width="100%"></video>\n`
: `\n![${file.name}](${url})\n`;
const newContent = content + insertText;
setContent(newContent);
form.setFieldsValue({ content: newContent });
message.success('上传成功');
} catch (error) {
console.error(error);
message.error('上传失败');
} finally {
setUploading(false);
}
return false; // 阻止默认上传行为
};
const handleSubmit = async (values) => {
setLoading(true);
try {
// 处理关联项目 ID (select value format: "type_id")
const relatedValue = values.related_item;
// Use content state instead of form value to ensure consistency
const payload = { ...values, content: content, media_ids: mediaIds };
delete payload.related_item;
if (relatedValue) {
const [type, id] = relatedValue.split('_');
if (type === 'config') payload.related_product = id;
if (type === 'course') payload.related_course = id;
if (type === 'service') payload.related_service = id;
} else {
// If cleared, set to null
payload.related_product = null;
payload.related_course = null;
payload.related_service = null;
}
if (isEditMode && topicId) {
await updateTopic(topicId, payload);
message.success('修改成功');
} else {
await createTopic(payload);
message.success('发布成功');
}
form.resetFields();
if (onSuccess) onSuccess();
onClose();
} catch (error) {
console.error(error);
message.error((isEditMode ? '修改' : '发布') + '失败: ' + (error.response?.data?.detail || '网络错误'));
} finally {
setLoading(false);
}
};
return (
<Modal
title={isEditMode ? "编辑帖子" : "发布新帖"}
open={visible}
onCancel={onClose}
footer={null}
destroyOnHidden
width={1000}
centered
maskClosable={false}
>
<Form
form={form}
layout="vertical"
onFinish={handleSubmit}
initialValues={{ category: 'discussion' }}
>
<Form.Item
name="title"
label="标题"
rules={[{ required: true, message: '请输入标题' }, { max: 100, message: '标题最多100字' }]}
>
<Input placeholder="请输入清晰的问题或讨论标题" size="large" />
</Form.Item>
<div style={{ display: 'flex', gap: 20 }}>
<Form.Item
name="category"
label="分类"
style={{ width: 200 }}
rules={[{ required: true, message: '请选择分类' }]}
>
<Select>
<Option value="discussion">技术讨论</Option>
<Option value="help">求助问答</Option>
<Option value="share">经验分享</Option>
</Select>
</Form.Item>
<Form.Item
name="related_item"
label="关联已购项目 (可选)"
style={{ flex: 1 }}
tooltip="关联已购项目可获得“认证用户”标识"
>
<Select placeholder="选择关联项目..." allowClear>
<Select.OptGroup label="硬件产品">
{paidItems.configs.map(i => (
<Option key={`config_${i.id}`} value={`config_${i.id}`}>{i.name}</Option>
))}
</Select.OptGroup>
<Select.OptGroup label="VC 课程">
{paidItems.courses.map(i => (
<Option key={`course_${i.id}`} value={`course_${i.id}`}>{i.title}</Option>
))}
</Select.OptGroup>
<Select.OptGroup label="AI 服务">
{paidItems.services.map(i => (
<Option key={`service_${i.id}`} value={`service_${i.id}`}>{i.title}</Option>
))}
</Select.OptGroup>
</Select>
</Form.Item>
</div>
<Form.Item
name="content"
label="内容 (支持 Markdown 与 LaTeX 公式)"
rules={[{ required: true, message: '请输入内容' }]}
>
<div data-color-mode="light">
<div style={{ marginBottom: 10 }}>
<Upload
beforeUpload={handleUpload}
showUploadList={false}
accept="image/*,video/*"
>
<Button icon={<UploadOutlined />} loading={uploading} size="small">
插入图片/视频
</Button>
</Upload>
</div>
<MDEditor
value={content}
onChange={(val) => {
setContent(val);
form.setFieldsValue({ content: val });
}}
height={400}
previewOptions={{
rehypePlugins: [[rehypeKatex]],
remarkPlugins: [[remarkMath]],
}}
/>
</div>
</Form.Item>
<Form.Item>
<div style={{ display: 'flex', justifyContent: 'flex-end', gap: 10 }}>
<Button onClick={onClose}>取消</Button>
<Button type="primary" htmlType="submit" loading={loading} size="large">
{isEditMode ? "保存修改" : "立即发布"}
</Button>
</div>
</Form.Item>
</Form>
</Modal>
);
};
export default CreateTopicModal;

View File

@@ -0,0 +1,278 @@
import React, { useState, useEffect } from 'react';
import { Layout as AntLayout, Menu, ConfigProvider, theme, Drawer, Button, Avatar, Dropdown } from 'antd';
import { RobotOutlined, MenuOutlined, AppstoreOutlined, EyeOutlined, SearchOutlined, UserOutlined, LogoutOutlined, WechatOutlined, TeamOutlined } from '@ant-design/icons';
import { useNavigate, useLocation, useSearchParams } from 'react-router-dom';
import ParticleBackground from './ParticleBackground';
import LoginModal from './LoginModal';
import ProfileModal from './ProfileModal';
import { motion, AnimatePresence } from 'framer-motion';
import { useAuth } from '../context/AuthContext';
const { Header, Content, Footer } = AntLayout;
const Layout = ({ children }) => {
const navigate = useNavigate();
const location = useLocation();
const [searchParams] = useSearchParams();
const [mobileMenuOpen, setMobileMenuOpen] = useState(false);
const [loginVisible, setLoginVisible] = useState(false);
const [profileVisible, setProfileVisible] = useState(false);
const { user, login, logout } = useAuth();
// 全局监听并持久化 ref 参数
useEffect(() => {
const ref = searchParams.get('ref');
if (ref) {
console.log('[Layout] Capturing sales ref code:', ref);
localStorage.setItem('ref_code', ref);
}
}, [searchParams]);
const handleLogout = () => {
logout();
navigate('/');
};
const userMenu = {
items: [
{
key: 'profile',
label: '个人设置',
icon: <UserOutlined />,
onClick: () => setProfileVisible(true)
},
{
key: 'logout',
label: '退出登录',
icon: <LogoutOutlined />,
onClick: handleLogout
}
]
};
const items = [
{
key: '/',
icon: <RobotOutlined />,
label: 'AI 硬件',
},
{
key: '/forum',
icon: <TeamOutlined />,
label: '技术论坛',
},
{
key: '/services',
icon: <AppstoreOutlined />,
label: 'AI 服务',
},
{
key: '/courses',
icon: <EyeOutlined />,
label: 'VC 课程',
},
{
key: '/my-orders',
icon: <SearchOutlined />,
label: '我的订单',
},
];
const handleMenuClick = (key) => {
navigate(key);
setMobileMenuOpen(false);
};
return (
<ConfigProvider
theme={{
algorithm: theme.darkAlgorithm,
token: {
colorPrimary: '#00b96b',
colorBgContainer: 'transparent',
colorBgLayout: 'transparent',
fontFamily: "'Orbitron', sans-serif",
},
}}
>
<ParticleBackground />
<AntLayout style={{ minHeight: '100vh', background: 'transparent' }}>
<Header
style={{
position: 'fixed',
top: 0,
left: 0,
zIndex: 1000,
width: '100%',
padding: 0,
background: 'rgba(0, 0, 0, 0.7)',
backdropFilter: 'blur(20px)',
borderBottom: '1px solid rgba(255, 255, 255, 0.1)',
display: 'flex',
height: '72px',
lineHeight: '72px',
boxShadow: '0 4px 30px rgba(0, 0, 0, 0.5)'
}}
>
<div style={{
width: '100%',
padding: '0 40px',
display: 'flex',
alignItems: 'center',
justifyContent: 'space-between',
height: '100%'
}}>
<motion.div
initial={{ opacity: 0, x: -20 }}
animate={{ opacity: 1, x: 0 }}
transition={{ duration: 0.5 }}
style={{
color: '#fff',
fontSize: '20px',
fontWeight: 'bold',
display: 'flex',
alignItems: 'center',
cursor: 'pointer'
}}
onClick={() => navigate('/')}
>
<img src="/liangji_logo.svg" alt="Quant Speed Logo" style={{ height: '40px', filter: 'invert(1) brightness(2)' }} />
</motion.div>
{/* Desktop Menu */}
<div className="desktop-menu" style={{ display: 'none', flex: 1, justifyContent: 'flex-end', alignItems: 'center' }}>
<Menu
theme="dark"
mode="horizontal"
selectedKeys={[location.pathname]}
items={items}
onClick={(e) => handleMenuClick(e.key)}
style={{
background: 'transparent',
borderBottom: 'none',
display: 'flex',
justifyContent: 'flex-end',
minWidth: '400px',
marginRight: '20px'
}}
/>
{user ? (
<div style={{ display: 'flex', alignItems: 'center', gap: 15 }}>
{/* 小程序图标状态 */}
<WechatOutlined
style={{
fontSize: 24,
color: user.openid && !user.openid.startsWith('web_') ? '#07c160' : '#666',
cursor: 'help'
}}
title={user.openid && !user.openid.startsWith('web_') ? '已绑定微信小程序' : '未绑定微信小程序'}
/>
<Dropdown menu={userMenu}>
<div style={{ display: 'flex', alignItems: 'center', cursor: 'pointer', color: '#fff' }}>
<Avatar src={user.avatar_url} icon={<UserOutlined />} style={{ marginRight: 8 }} />
<span>{user.nickname}</span>
</div>
</Dropdown>
</div>
) : (
<Button type="primary" onClick={() => setLoginVisible(true)}>登录</Button>
)}
</div>
<style>{`
@media (min-width: 768px) {
.desktop-menu { display: flex !important; }
.mobile-menu-btn { display: none !important; }
}
`}</style>
{/* Mobile Menu Button */}
<Button
className="mobile-menu-btn"
type="text"
icon={<MenuOutlined style={{ color: '#fff', fontSize: 20 }} />}
onClick={() => setMobileMenuOpen(true)}
/>
</div>
</Header>
{/* Mobile Drawer Menu */}
<Drawer
title={<span style={{ color: '#00b96b' }}>导航菜单</span>}
placement="right"
onClose={() => setMobileMenuOpen(false)}
open={mobileMenuOpen}
styles={{ body: { padding: 0, background: '#111' }, header: { background: '#111', borderBottom: '1px solid #333' }, wrapper: { width: 250 } }}
>
<div style={{ padding: '20px', textAlign: 'center', borderBottom: '1px solid #333' }}>
{user ? (
<div style={{ color: '#fff' }}>
<Avatar
src={user.avatar_url}
icon={<UserOutlined />}
size="large"
style={{ marginBottom: 10, cursor: 'pointer' }}
onClick={() => { setProfileVisible(true); setMobileMenuOpen(false); }}
/>
<div onClick={() => { setProfileVisible(true); setMobileMenuOpen(false); }} style={{ cursor: 'pointer' }}>
{user.nickname}
</div>
<Button type="link" danger onClick={handleLogout} style={{ marginTop: 10 }}>退出登录</Button>
</div>
) : (
<Button type="primary" block onClick={() => { setLoginVisible(true); setMobileMenuOpen(false); }}>登录 / 注册</Button>
)}
</div>
<Menu
theme="dark"
mode="vertical"
selectedKeys={[location.pathname]}
items={items}
onClick={(e) => handleMenuClick(e.key)}
style={{ background: 'transparent', borderRight: 'none' }}
/>
</Drawer>
<LoginModal
visible={loginVisible}
onClose={() => setLoginVisible(false)}
onLoginSuccess={(userData) => login(userData)}
/>
<ProfileModal
visible={profileVisible}
onClose={() => setProfileVisible(false)}
/>
<Content style={{ marginTop: 72, padding: '40px 20px', overflowX: 'hidden' }}>
<div style={{
maxWidth: '1200px',
margin: '0 auto',
width: '100%',
minHeight: 'calc(100vh - 128px)'
}}>
<AnimatePresence mode="wait">
<motion.div
key={location.pathname}
initial={{ opacity: 0, y: 20, filter: 'blur(10px)' }}
animate={{ opacity: 1, y: 0, filter: 'blur(0px)' }}
exit={{ opacity: 0, y: -20, filter: 'blur(10px)' }}
transition={{ duration: 0.3 }}
>
{children}
</motion.div>
</AnimatePresence>
</div>
</Content>
<Footer style={{ textAlign: 'center', background: 'rgba(0,0,0,0.5)', color: '#666', backdropFilter: 'blur(5px)' }}>
Quant Speed AI Hardware ©{new Date().getFullYear()} Created by Quant Speed Tech
</Footer>
</AntLayout>
</ConfigProvider>
);
};
export default Layout;

View File

@@ -0,0 +1,123 @@
import React, { useState } from 'react';
import { Modal, Form, Input, Button, message } from 'antd';
import { UserOutlined, LockOutlined, MobileOutlined } from '@ant-design/icons';
import { sendSms, phoneLogin } from '../api';
const LoginModal = ({ visible, onClose, onLoginSuccess }) => {
const [form] = Form.useForm();
const [loading, setLoading] = useState(false);
const [countdown, setCountdown] = useState(0);
const handleSendCode = async () => {
try {
const phone = form.getFieldValue('phone_number');
if (!phone) {
message.error('请输入手机号');
return;
}
// 简单的手机号校验
if (!/^1[3-9]\d{9}$/.test(phone)) {
message.error('请输入有效的手机号');
return;
}
//
await sendSms({ phone_number: phone });
message.success('验证码已发送');
setCountdown(60);
const timer = setInterval(() => {
setCountdown((prev) => {
if (prev <= 1) {
clearInterval(timer);
return 0;
}
return prev - 1;
});
}, 1000);
} catch (error) {
console.error(error);
message.error('发送失败: ' + (error.response?.data?.error || '网络错误'));
}
};
const handleSubmit = async (values) => {
setLoading(true);
try {
const res = await phoneLogin(values);
message.success('登录成功');
onLoginSuccess(res.data);
onClose();
} catch (error) {
console.error(error);
message.error('登录失败: ' + (error.response?.data?.error || '网络错误'));
} finally {
setLoading(false);
}
};
return (
<Modal
title="用户登录 / 注册"
open={visible}
onCancel={onClose}
footer={null}
destroyOnHidden
centered
>
<Form
form={form}
name="login_form"
onFinish={handleSubmit}
layout="vertical"
style={{ marginTop: 20 }}
>
<Form.Item
name="phone_number"
rules={[{ required: true, message: '请输入手机号' }]}
>
<Input
prefix={<MobileOutlined />}
placeholder="手机号码"
size="large"
/>
</Form.Item>
<Form.Item
name="code"
rules={[{ required: true, message: '请输入验证码' }]}
>
<div style={{ display: 'flex', gap: 10 }}>
<Input
prefix={<LockOutlined />}
placeholder="验证码"
size="large"
/>
<Button
size="large"
onClick={handleSendCode}
disabled={countdown > 0}
>
{countdown > 0 ? `${countdown}s` : '获取验证码'}
</Button>
</div>
</Form.Item>
<Form.Item>
<Button type="primary" htmlType="submit" block size="large" loading={loading}>
登录
</Button>
</Form.Item>
<div style={{ textAlign: 'center', color: '#999', fontSize: 12 }}>
未注册的手机号验证后将自动创建账号<br/>
已在小程序绑定的手机号将自动同步身份
</div>
</Form>
</Modal>
);
};
export default LoginModal;

View File

@@ -0,0 +1,218 @@
import React, { Suspense, useState, useEffect } from 'react';
import { Canvas, useLoader } from '@react-three/fiber';
import { OBJLoader } from 'three/examples/jsm/loaders/OBJLoader';
import { MTLLoader } from 'three/examples/jsm/loaders/MTLLoader';
import { OrbitControls, Stage, useProgress, Environment, ContactShadows } from '@react-three/drei';
import { Spin } from 'antd';
import JSZip from 'jszip';
import * as THREE from 'three';
class ErrorBoundary extends React.Component {
constructor(props) {
super(props);
this.state = { hasError: false };
}
static getDerivedStateFromError(error) {
return { hasError: true };
}
componentDidCatch(error, errorInfo) {
console.error("3D Model Viewer Error:", error, errorInfo);
}
render() {
if (this.state.hasError) {
return (
<div style={{
display: 'flex',
alignItems: 'center',
justifyContent: 'center',
height: '100%',
color: '#888',
padding: 20,
textAlign: 'center',
fontSize: '14px'
}}>
3D 模型加载失败
</div>
);
}
return this.props.children;
}
}
const Model = ({ objPath, mtlPath, scale = 1 }) => {
// If mtlPath is provided, load materials first
const materials = mtlPath ? useLoader(MTLLoader, mtlPath) : null;
const obj = useLoader(OBJLoader, objPath, (loader) => {
if (materials) {
materials.preload();
loader.setMaterials(materials);
}
});
const clone = obj.clone();
return <primitive object={clone} scale={scale} />;
};
const LoadingOverlay = () => {
const { progress, active } = useProgress();
if (!active) return null;
return (
<div style={{
position: 'absolute',
top: 0,
left: 0,
width: '100%',
height: '100%',
display: 'flex',
alignItems: 'center',
justifyContent: 'center',
background: 'rgba(0,0,0,0.5)',
zIndex: 10,
pointerEvents: 'none'
}}>
<div style={{ textAlign: 'center' }}>
<Spin size="large" />
<div style={{ color: '#00b96b', marginTop: 10, fontWeight: 'bold' }}>
{progress.toFixed(0)}% Loading
</div>
</div>
</div>
);
};
const ModelViewer = ({ objPath, mtlPath, scale = 1, autoRotate = true }) => {
const [paths, setPaths] = useState(null);
const [unzipping, setUnzipping] = useState(false);
const [error, setError] = useState(null);
useEffect(() => {
let isMounted = true;
const blobUrls = [];
const loadPaths = async () => {
if (!objPath) return;
// 如果是 zip 文件
if (objPath.toLowerCase().endsWith('.zip')) {
setUnzipping(true);
setError(null);
try {
const response = await fetch(objPath);
const arrayBuffer = await response.arrayBuffer();
const zip = await JSZip.loadAsync(arrayBuffer);
let extractedObj = null;
let extractedMtl = null;
const fileMap = {};
// 1. 提取所有文件并创建 Blob URL 映射
for (const [filename, file] of Object.entries(zip.files)) {
if (file.dir) continue;
const content = await file.async('blob');
const url = URL.createObjectURL(content);
blobUrls.push(url);
// 记录文件名到 URL 的映射,用于后续材质引用图片等情况
const baseName = filename.split('/').pop();
fileMap[baseName] = url;
if (filename.toLowerCase().endsWith('.obj')) {
extractedObj = url;
} else if (filename.toLowerCase().endsWith('.mtl')) {
extractedMtl = url;
}
}
if (isMounted) {
if (extractedObj) {
setPaths({ obj: extractedObj, mtl: extractedMtl });
} else {
setError('压缩包内未找到 .obj 模型文件');
}
}
} catch (err) {
console.error('Error unzipping model:', err);
if (isMounted) setError('加载压缩包失败');
} finally {
if (isMounted) setUnzipping(false);
}
} else {
// 普通路径
setPaths({ obj: objPath, mtl: mtlPath });
}
};
loadPaths();
return () => {
isMounted = false;
// 清理 Blob URL 释放内存
blobUrls.forEach(url => URL.revokeObjectURL(url));
};
}, [objPath, mtlPath]);
if (unzipping) {
return (
<div style={{
display: 'flex',
flexDirection: 'column',
alignItems: 'center',
justifyContent: 'center',
height: '100%',
background: 'rgba(0,0,0,0.1)'
}}>
<Spin size="large" />
<div style={{ color: '#00b96b', marginTop: 15, fontWeight: '500' }}>正在解压 3D 资源...</div>
</div>
);
}
if (error) {
return (
<div style={{
display: 'flex',
alignItems: 'center',
justifyContent: 'center',
height: '100%',
color: '#ff4d4f',
padding: 20,
textAlign: 'center'
}}>
{error}
</div>
);
}
if (!paths) return null;
return (
<div style={{ position: 'relative', width: '100%', height: '100%' }}>
<ErrorBoundary>
<LoadingOverlay />
<Canvas shadows dpr={[1, 2]} camera={{ fov: 45, position: [0, 0, 5] }} style={{ height: '100%', width: '100%' }}>
<ambientLight intensity={0.7} />
<pointLight position={[10, 10, 10]} intensity={1} />
<spotLight position={[-10, 10, 10]} angle={0.15} penumbra={1} intensity={1} />
<Suspense fallback={null}>
<Stage environment="city" intensity={0.6} adjustCamera={true}>
<Model objPath={paths.obj} mtlPath={paths.mtl} scale={scale} />
</Stage>
<Environment preset="city" />
<ContactShadows position={[0, -0.8, 0]} opacity={0.4} scale={10} blur={2} far={0.8} />
</Suspense>
<OrbitControls autoRotate={autoRotate} makeDefault />
</Canvas>
</ErrorBoundary>
</div>
);
};
export default ModelViewer;

View File

@@ -0,0 +1,174 @@
import React, { useEffect, useRef } from 'react';
const ParticleBackground = () => {
const canvasRef = useRef(null);
useEffect(() => {
const canvas = canvasRef.current;
const ctx = canvas.getContext('2d');
let animationFrameId;
const resizeCanvas = () => {
canvas.width = window.innerWidth;
canvas.height = window.innerHeight;
};
window.addEventListener('resize', resizeCanvas);
resizeCanvas();
const particles = [];
const particleCount = 100;
const meteors = [];
const meteorCount = 8;
class Particle {
constructor() {
this.x = Math.random() * canvas.width;
this.y = Math.random() * canvas.height;
this.vx = (Math.random() - 0.5) * 0.5;
this.vy = (Math.random() - 0.5) * 0.5;
this.size = Math.random() * 2;
this.color = Math.random() > 0.5 ? 'rgba(0, 185, 107, ' : 'rgba(0, 240, 255, '; // Green or Blue
}
update() {
this.x += this.vx;
this.y += this.vy;
if (this.x < 0 || this.x > canvas.width) this.vx *= -1;
if (this.y < 0 || this.y > canvas.height) this.vy *= -1;
}
draw() {
ctx.beginPath();
ctx.arc(this.x, this.y, this.size, 0, Math.PI * 2);
ctx.fillStyle = this.color + Math.random() * 0.5 + ')';
ctx.fill();
}
}
class Meteor {
constructor() {
this.reset();
}
reset() {
this.x = Math.random() * canvas.width * 1.5; // Start further right
this.y = Math.random() * -canvas.height; // Start further above
this.vx = -(Math.random() * 5 + 5); // Faster
this.vy = Math.random() * 5 + 5; // Faster
this.len = Math.random() * 150 + 150; // Longer trail
this.color = Math.random() > 0.5 ? 'rgba(0, 185, 107, ' : 'rgba(0, 240, 255, ';
this.opacity = 0;
this.maxOpacity = Math.random() * 0.5 + 0.2;
this.wait = Math.random() * 300; // Random delay before showing up
}
update() {
if (this.wait > 0) {
this.wait--;
return;
}
this.x += this.vx;
this.y += this.vy;
if (this.opacity < this.maxOpacity) {
this.opacity += 0.02;
}
if (this.x < -this.len || this.y > canvas.height + this.len) {
this.reset();
}
}
draw() {
if (this.wait > 0) return;
const tailX = this.x - this.vx * (this.len / 15);
const tailY = this.y - this.vy * (this.len / 15);
const gradient = ctx.createLinearGradient(this.x, this.y, tailX, tailY);
gradient.addColorStop(0, this.color + this.opacity + ')');
gradient.addColorStop(0.1, this.color + (this.opacity * 0.5) + ')');
gradient.addColorStop(1, this.color + '0)');
ctx.save();
// Add glow effect
ctx.shadowBlur = 8;
ctx.shadowColor = this.color.replace('rgba', 'rgb').replace(', ', ')');
ctx.beginPath();
ctx.strokeStyle = gradient;
ctx.lineWidth = 2;
ctx.lineCap = 'round';
ctx.moveTo(this.x, this.y);
ctx.lineTo(tailX, tailY);
ctx.stroke();
// Add a bright head
ctx.beginPath();
ctx.fillStyle = '#fff';
ctx.arc(this.x, this.y, 1, 0, Math.PI * 2);
ctx.fill();
ctx.restore();
}
}
for (let i = 0; i < particleCount; i++) {
particles.push(new Particle());
}
for (let i = 0; i < meteorCount; i++) {
meteors.push(new Meteor());
}
const animate = () => {
ctx.clearRect(0, 0, canvas.width, canvas.height);
// Draw meteors first (in background)
meteors.forEach(m => {
m.update();
m.draw();
});
// Draw connecting lines
ctx.lineWidth = 0.5;
for (let i = 0; i < particleCount; i++) {
for (let j = i; j < particleCount; j++) {
const dx = particles[i].x - particles[j].x;
const dy = particles[i].y - particles[j].y;
const distance = Math.sqrt(dx * dx + dy * dy);
if (distance < 100) {
ctx.beginPath();
ctx.strokeStyle = `rgba(100, 255, 218, ${1 - distance / 100})`;
ctx.moveTo(particles[i].x, particles[i].y);
ctx.lineTo(particles[j].x, particles[j].y);
ctx.stroke();
}
}
}
particles.forEach(p => {
p.update();
p.draw();
});
animationFrameId = requestAnimationFrame(animate);
};
animate();
return () => {
window.removeEventListener('resize', resizeCanvas);
cancelAnimationFrame(animationFrameId);
};
}, []);
return <canvas ref={canvasRef} id="particle-canvas" />;
};
export default ParticleBackground;

View File

@@ -0,0 +1,124 @@
import React, { useState, useEffect } from 'react';
import { Modal, Form, Input, Upload, Button, message, Avatar } from 'antd';
import { UserOutlined, UploadOutlined, LoadingOutlined } from '@ant-design/icons';
import { useAuth } from '../context/AuthContext';
import { updateUserInfo, uploadUserAvatar } from '../api';
const ProfileModal = ({ visible, onClose }) => {
const { user, updateUser } = useAuth();
const [form] = Form.useForm();
const [loading, setLoading] = useState(false);
const [uploading, setUploading] = useState(false);
const [avatarUrl, setAvatarUrl] = useState('');
useEffect(() => {
if (visible && user) {
form.setFieldsValue({
nickname: user.nickname,
});
setAvatarUrl(user.avatar_url);
}
}, [visible, user, form]);
const handleUpload = async (file) => {
const isJpgOrPng = file.type === 'image/jpeg' || file.type === 'image/png';
if (!isJpgOrPng) {
message.error('You can only upload JPG/PNG file!');
return Upload.LIST_IGNORE;
}
const isLt2M = file.size / 1024 / 1024 < 2;
if (!isLt2M) {
message.error('Image must smaller than 2MB!');
return Upload.LIST_IGNORE;
}
const formData = new FormData();
formData.append('file', file);
setUploading(true);
try {
const res = await uploadUserAvatar(formData);
if (res.data.success) {
setAvatarUrl(res.data.file_url);
message.success('头像上传成功');
} else {
message.error('头像上传失败: ' + (res.data.message || '未知错误'));
}
} catch (error) {
console.error('Upload failed:', error);
message.error('头像上传失败');
} finally {
setUploading(false);
}
return false; // Prevent default auto upload
};
const handleOk = async () => {
try {
const values = await form.validateFields();
setLoading(true);
const updateData = {
nickname: values.nickname,
avatar_url: avatarUrl
};
const res = await updateUserInfo(updateData);
updateUser(res.data);
message.success('个人信息更新成功');
onClose();
} catch (error) {
console.error('Update failed:', error);
message.error('更新失败');
} finally {
setLoading(false);
}
};
return (
<Modal
title="个人设置"
open={visible}
onOk={handleOk}
onCancel={onClose}
confirmLoading={loading}
centered
>
<Form
form={form}
layout="vertical"
style={{ marginTop: 20 }}
>
<Form.Item label="头像" style={{ textAlign: 'center' }}>
<div style={{ display: 'flex', flexDirection: 'column', alignItems: 'center', gap: 15 }}>
<Avatar
size={100}
src={avatarUrl}
icon={<UserOutlined />}
/>
<Upload
name="avatar"
showUploadList={false}
beforeUpload={handleUpload}
accept="image/*"
>
<Button icon={uploading ? <LoadingOutlined /> : <UploadOutlined />} loading={uploading}>
{uploading ? '上传中...' : '更换头像'}
</Button>
</Upload>
</div>
</Form.Item>
<Form.Item
name="nickname"
label="昵称"
rules={[{ required: true, message: '请输入昵称' }]}
>
<Input placeholder="请输入昵称" maxLength={20} />
</Form.Item>
</Form>
</Modal>
);
};
export default ProfileModal;

View File

@@ -0,0 +1,101 @@
import React, { useState, useRef, useLayoutEffect } from 'react';
import { motion } from 'framer-motion';
import { CalendarOutlined } from '@ant-design/icons';
import { useNavigate } from 'react-router-dom';
import styles from './activity.module.less';
import { hoverScale } from '../../animation';
const ActivityCard = ({ activity }) => {
const navigate = useNavigate();
const [isLoaded, setIsLoaded] = useState(false);
const [hasError, setHasError] = useState(false);
const imgRef = useRef(null);
const handleCardClick = () => {
navigate(`/activity/${activity.id}`);
};
const getStatus = (startTime) => {
const now = new Date();
const start = new Date(startTime);
if (now < start) return '即将开始';
return '报名中';
};
const formatDate = (dateStr) => {
if (!dateStr) return 'TBD';
const date = new Date(dateStr);
return date.toLocaleDateString('zh-CN', { month: 'long', day: 'numeric' });
};
const imgSrc = hasError
? 'https://via.placeholder.com/600x400?text=No+Image'
: (activity.display_banner_url || activity.banner_url || activity.cover_image || 'https://via.placeholder.com/600x400');
// Check if image is already loaded (cached) to prevent flashing
useLayoutEffect(() => {
if (imgRef.current && imgRef.current.complete) {
setIsLoaded(true);
}
}, [imgSrc]);
return (
<motion.div
className={styles.activityCard}
variants={hoverScale}
whileHover="hover"
onClick={handleCardClick}
layoutId={`activity-card-${activity.id}`}
style={{ willChange: 'transform' }}
>
<div className={styles.imageContainer}>
{/* Placeholder Background - Always visible behind the image */}
<div
style={{
position: 'absolute',
top: 0,
left: 0,
width: '100%',
height: '100%',
backgroundColor: '#f5f5f5',
zIndex: 0,
}}
/>
<img
ref={imgRef}
src={imgSrc}
alt={activity.title}
style={{
position: 'relative',
zIndex: 1,
width: '100%',
height: '100%',
objectFit: 'cover',
opacity: isLoaded ? 1 : 0,
transition: 'opacity 0.3s ease-out'
}}
onLoad={() => setIsLoaded(true)}
onError={() => {
setHasError(true);
setIsLoaded(true);
}}
loading="lazy"
/>
<div className={styles.overlay} style={{ zIndex: 2 }}>
<div className={styles.statusTag}>
{activity.status || getStatus(activity.start_time)}
</div>
<h3 className={styles.title}>{activity.title}</h3>
<div className={styles.time}>
<CalendarOutlined />
<span>{formatDate(activity.start_time)}</span>
</div>
</div>
</div>
</motion.div>
);
};
export default ActivityCard;

View File

@@ -0,0 +1,67 @@
import React from 'react';
import { MemoryRouter } from 'react-router-dom';
import ActivityCard from './ActivityCard';
import '../../index.css'; // Global styles
import '../../App.css';
export default {
title: 'Components/Activity/ActivityCard',
component: ActivityCard,
decorators: [
(Story) => (
<MemoryRouter>
<div style={{ maxWidth: '400px', padding: '20px' }}>
<Story />
</div>
</MemoryRouter>
),
],
tags: ['autodocs'],
};
const Template = (args) => <ActivityCard {...args} />;
export const NotStarted = Template.bind({});
NotStarted.args = {
activity: {
id: 1,
title: 'Future AI Hardware Summit 2026',
start_time: '2026-12-01T09:00:00',
status: '即将开始',
cover_image: 'https://images.unsplash.com/photo-1485827404703-89b55fcc595e?auto=format&fit=crop&q=80',
},
};
export const Ongoing = Template.bind({});
Ongoing.args = {
activity: {
id: 2,
title: 'Edge Computing Hackathon',
start_time: '2025-10-20T10:00:00',
status: '报名中',
cover_image: 'https://images.unsplash.com/photo-1550751827-4bd374c3f58b?auto=format&fit=crop&q=80',
},
};
export const Ended = Template.bind({});
Ended.args = {
activity: {
id: 3,
title: 'Deep Learning Workshop',
start_time: '2023-05-15T14:00:00',
status: '已结束',
cover_image: 'https://images.unsplash.com/photo-1518770660439-4636190af475?auto=format&fit=crop&q=80',
},
};
export const SignedUp = Template.bind({});
SignedUp.args = {
activity: {
id: 4,
title: 'Exclusive Developer Meetup',
start_time: '2025-11-11T18:00:00',
status: '已报名',
cover_image: 'https://images.unsplash.com/photo-1522071820081-009f0129c71c?auto=format&fit=crop&q=80',
},
};

View File

@@ -0,0 +1,110 @@
import React, { useState, useEffect } from 'react';
import { useQuery } from '@tanstack/react-query';
import { motion, AnimatePresence } from 'framer-motion';
import { RightOutlined, LeftOutlined } from '@ant-design/icons';
import { getActivities } from '../../api';
import ActivityCard from './ActivityCard';
import styles from './activity.module.less';
import { fadeInUp, staggerContainer } from '../../animation';
const ActivityList = () => {
const { data: activities, isLoading, error } = useQuery({
queryKey: ['activities'],
queryFn: async () => {
const res = await getActivities();
// Handle different response structures
return Array.isArray(res.data) ? res.data : (res.data?.results || []);
},
staleTime: 5 * 60 * 1000, // 5 minutes cache
});
const [currentIndex, setCurrentIndex] = useState(0);
// Auto-play for desktop carousel
useEffect(() => {
if (!activities || activities.length <= 1) return;
const interval = setInterval(() => {
setCurrentIndex((prev) => (prev + 1) % activities.length);
}, 5000);
return () => clearInterval(interval);
}, [activities]);
const nextSlide = () => {
if (!activities) return;
setCurrentIndex((prev) => (prev + 1) % activities.length);
};
const prevSlide = () => {
if (!activities) return;
setCurrentIndex((prev) => (prev - 1 + activities.length) % activities.length);
};
if (isLoading) return <div className={styles.loading}>Loading activities...</div>;
if (error) return null; // Or error state
if (!activities || activities.length === 0) return null;
return (
<motion.div
className={styles.activitySection}
initial="hidden"
whileInView="visible"
viewport={{ once: true, amount: 0.2 }}
variants={staggerContainer}
>
<div className={styles.header}>
<h2 className={styles.sectionTitle}>
近期活动 / EVENTS
</h2>
<div className={styles.controls}>
<button onClick={prevSlide} className={styles.navBtn}><LeftOutlined /></button>
<button onClick={nextSlide} className={styles.navBtn}><RightOutlined /></button>
</div>
</div>
{/* Desktop: Carousel (Show one prominent, but allows list structure if needed)
User said: "Activity only shows one, and in the form of a sliding page"
*/}
<div className={styles.desktopCarousel}>
<AnimatePresence>
<motion.div
key={currentIndex}
initial={{ x: '100%' }}
animate={{ x: 0, zIndex: 1 }}
exit={{ x: '-100%', zIndex: 0 }}
transition={{ duration: 0.5, ease: "easeInOut" }}
style={{
width: '100%',
position: 'absolute',
top: 0,
left: 0,
}}
>
<ActivityCard activity={activities[currentIndex]} />
</motion.div>
</AnimatePresence>
<div className={styles.dots} style={{ position: 'absolute', bottom: '10px', width: '100%', zIndex: 10 }}>
{activities.map((_, idx) => (
<span
key={idx}
className={`${styles.dot} ${idx === currentIndex ? styles.activeDot : ''}`}
onClick={() => setCurrentIndex(idx)}
/>
))}
</div>
</div>
{/* Mobile: Vertical List/Scroll as requested "Mobile vertical scroll" */}
<div className={styles.mobileList}>
{activities.map((item, index) => (
<motion.div key={item.id} variants={fadeInUp} custom={index}>
<ActivityCard activity={item} />
</motion.div>
))}
</div>
</motion.div>
);
};
export default ActivityList;

View File

@@ -0,0 +1,266 @@
@import '../../theme.module.less';
.activitySection {
padding: var(--spacing-lg) 0;
width: 100%;
}
.header {
display: flex;
justify-content: space-between;
align-items: center;
margin-bottom: var(--spacing-md);
}
.sectionTitle {
font-size: 24px;
font-weight: 700;
color: var(--text-primary);
display: flex;
align-items: center;
gap: 8px;
&::before {
content: '';
display: block;
width: 4px;
height: 24px;
background: var(--primary-color);
border-radius: 2px;
}
}
.controls {
display: flex;
gap: var(--spacing-sm);
@media (max-width: 768px) {
display: none; /* Hide carousel controls on mobile */
}
}
.navBtn {
background: rgba(255, 255, 255, 0.1);
border: 1px solid rgba(255, 255, 255, 0.2);
color: var(--text-primary);
width: 32px;
height: 32px;
border-radius: 50%;
display: flex;
align-items: center;
justify-content: center;
cursor: pointer;
transition: all 0.3s;
&:hover {
background: var(--primary-color);
border-color: var(--primary-color);
}
}
/* Desktop Carousel */
.desktopCarousel {
position: relative;
width: 100%;
height: 440px; /* 400px card + space for dots */
overflow: hidden;
@media (max-width: 768px) {
display: none;
}
}
.dots {
display: flex;
justify-content: center;
gap: 8px;
margin-top: var(--spacing-md);
}
.dot {
width: 8px;
height: 8px;
background: rgba(255, 255, 255, 0.2);
border-radius: 50%;
cursor: pointer;
transition: all 0.3s;
&.activeDot {
background: var(--primary-color);
transform: scale(1.2);
}
}
/* Mobile List */
.mobileList {
display: none;
flex-direction: column;
gap: var(--spacing-md);
@media (max-width: 768px) {
display: flex;
}
}
/* --- Card Styles --- */
.activityCard {
position: relative;
width: 100%;
height: 400px;
border-radius: var(--border-radius-lg);
overflow: hidden;
cursor: pointer;
background: var(--background-card);
box-shadow: var(--box-shadow-base);
transition: all 0.3s ease;
@media (max-width: 768px) {
height: 300px;
}
}
.imageContainer {
width: 100%;
height: 100%;
position: relative;
img {
width: 100%;
height: 100%;
object-fit: cover;
transition: transform 0.5s ease;
}
}
.overlay {
position: absolute;
bottom: 0;
left: 0;
width: 100%;
height: 60%;
background: linear-gradient(to top, rgba(0,0,0,0.9), transparent);
display: flex;
flex-direction: column;
justify-content: flex-end;
padding: var(--spacing-lg);
box-sizing: border-box;
}
.statusTag {
display: inline-block;
background: var(--primary-color);
color: #fff;
padding: 4px 12px;
border-radius: 4px;
font-size: 12px;
font-weight: 600;
margin-bottom: var(--spacing-sm);
width: fit-content;
text-transform: uppercase;
}
.title {
color: var(--text-primary);
font-size: 24px;
font-weight: 700;
margin-bottom: var(--spacing-xs);
line-height: 1.3;
text-shadow: 0 2px 4px rgba(0,0,0,0.5);
@media (max-width: 768px) {
font-size: 18px;
}
}
.time {
color: var(--text-secondary);
font-size: 14px;
display: flex;
align-items: center;
gap: 6px;
}
/* Detail Page Styles */
.detailHeader {
position: relative;
height: 50vh;
min-height: 300px;
width: 100%;
overflow: hidden;
}
.detailImage {
width: 100%;
height: 100%;
object-fit: cover;
}
.detailContent {
max-width: 800px;
margin: -60px auto 0;
position: relative;
z-index: 10;
padding: 0 var(--spacing-lg) 100px; /* Bottom padding for fixed footer */
}
.infoCard {
background: var(--background-card);
padding: var(--spacing-lg);
border-radius: var(--border-radius-lg);
box-shadow: var(--box-shadow-base);
margin-bottom: var(--spacing-lg);
border: 1px solid var(--border-color);
}
.richText {
color: var(--text-secondary);
line-height: 1.8;
font-size: 16px;
img {
max-width: 100%;
border-radius: var(--border-radius-base);
margin: var(--spacing-md) 0;
}
h1, h2, h3 {
color: var(--text-primary);
margin-top: var(--spacing-lg);
}
}
.fixedFooter {
position: fixed;
bottom: 0;
left: 0;
width: 100%;
background: rgba(31, 31, 31, 0.95);
backdrop-filter: blur(10px);
padding: var(--spacing-md) var(--spacing-lg);
border-top: 1px solid var(--border-color);
display: flex;
justify-content: space-between;
align-items: center;
z-index: 100;
box-shadow: 0 -4px 12px rgba(0,0,0,0.2);
}
.actionBtn {
background: var(--primary-color);
color: #fff;
border: none;
padding: 12px 32px;
border-radius: 24px;
font-size: 16px;
font-weight: 600;
cursor: pointer;
box-shadow: 0 4px 12px rgba(0, 185, 107, 0.3);
transition: all 0.3s;
&:disabled {
background: #555;
cursor: not-allowed;
box-shadow: none;
}
}