feat: add SproutWorkCollect apps

This commit is contained in:
2026-03-13 17:14:37 +08:00
parent 189baa3d59
commit 46afd3149f
54 changed files with 28126 additions and 4 deletions

View File

@@ -0,0 +1,277 @@
import React, { useState, useEffect } from 'react';
import { HashRouter as Router, Routes, Route } from 'react-router-dom';
import styled from 'styled-components';
import Header from './components/Header';
import WorkCard from './components/WorkCard';
import WorkDetail from './components/WorkDetail';
import AdminPanel from './components/AdminPanel';
import SearchBar from './components/SearchBar';
import CategoryFilter from './components/CategoryFilter';
import LoadingSpinner from './components/LoadingSpinner';
import Footer from './components/Footer';
import Pagination from './components/Pagination';
import { getWorks, getSettings, getCategories, searchWorks } from './services/api';
import { BACKGROUND_CONFIG, pickBackgroundImage } from './config/background';
const AppContainer = styled.div`
min-height: 100vh;
background: ${({ $backgroundUrl }) =>
$backgroundUrl
? `url(${$backgroundUrl}) center/cover no-repeat fixed`
: `linear-gradient(
135deg,
rgba(232, 245, 232, 0.4) 0%,
rgba(200, 230, 201, 0.4) 20%,
rgba(165, 214, 167, 0.4) 40%,
rgba(255, 255, 224, 0.3) 60%,
rgba(255, 255, 200, 0.3) 80%,
rgba(240, 255, 240, 0.4) 100%
)`};
background-size: ${({ $backgroundUrl }) => ($backgroundUrl ? 'cover' : '400% 400%')};
animation: ${({ $backgroundUrl }) => ($backgroundUrl ? 'none' : 'gentleShift 25s ease infinite')};
position: relative;
&:before {
content: '';
position: fixed;
top: 0;
left: 0;
width: 100%;
height: 100%;
background: ${({ $blurOverlayOpacity }) =>
`rgba(255, 255, 255, ${$blurOverlayOpacity})`};
backdrop-filter: ${({ $blurAmount }) => `blur(${$blurAmount})`};
pointer-events: none;
z-index: -1;
}
@keyframes gentleShift {
0% {
background-position: 0% 50%;
}
50% {
background-position: 100% 50%;
}
100% {
background-position: 0% 50%;
}
}
`;
const MainContent = styled.main`
max-width: 1440px;
margin: 0 auto;
padding: 20px;
@media (max-width: 768px) {
padding: 10px;
}
`;
const WorksGrid = styled.div`
display: grid;
grid-template-columns: repeat(4, 1fr);
gap: 20px;
margin-top: 20px;
@media (max-width: 1024px) {
grid-template-columns: repeat(2, 1fr);
}
@media (max-width: 768px) {
grid-template-columns: 1fr;
gap: 15px;
}
`;
const FilterSection = styled.div`
display: flex;
flex-direction: column;
gap: 15px;
margin-bottom: 20px;
@media (min-width: 768px) {
flex-direction: row;
align-items: center;
justify-content: space-between;
}
`;
const NoResults = styled.div`
text-align: center;
padding: 40px 20px;
color: #666;
font-size: 18px;
`;
// 首页组件
const HomePage = ({ settings }) => {
const [works, setWorks] = useState([]);
const [allWorks, setAllWorks] = useState([]); // 存储所有作品数据
const [categories, setCategories] = useState([]);
const [loading, setLoading] = useState(true);
const [searchQuery, setSearchQuery] = useState('');
const [selectedCategory, setSelectedCategory] = useState('');
const [currentPage, setCurrentPage] = useState(1);
// 从设置中获取每页作品数量默认12三行四列
const itemsPerPage = settings['每页作品数量'] || 12;
useEffect(() => {
loadInitialData();
}, []);
const loadInitialData = async () => {
try {
setLoading(true);
const [worksData, categoriesData] = await Promise.all([
getWorks(),
getCategories()
]);
const allWorksData = worksData.data || [];
setAllWorks(allWorksData);
setWorks(allWorksData);
setCategories(categoriesData.data || []);
setCurrentPage(1); // 重置到第一页
} catch (error) {
console.error('加载数据失败:', error);
} finally {
setLoading(false);
}
};
const handleSearch = async (query) => {
setSearchQuery(query);
await performSearch(query, selectedCategory);
};
const handleCategoryChange = async (category) => {
setSelectedCategory(category);
await performSearch(searchQuery, category);
};
const performSearch = async (query, category) => {
try {
setLoading(true);
if (query || category) {
const searchData = await searchWorks(query, category);
setAllWorks(searchData.data || []);
setWorks(searchData.data || []);
} else {
const worksData = await getWorks();
setAllWorks(worksData.data || []);
setWorks(worksData.data || []);
}
setCurrentPage(1); // 搜索后重置到第一页
} catch (error) {
console.error('搜索失败:', error);
} finally {
setLoading(false);
}
};
// 分页相关的计算
const totalPages = Math.ceil(works.length / itemsPerPage);
const startIndex = (currentPage - 1) * itemsPerPage;
const endIndex = startIndex + itemsPerPage;
const currentWorks = works.slice(startIndex, endIndex);
// 处理页面变化
const handlePageChange = (page) => {
setCurrentPage(page);
// 滚动到顶部
window.scrollTo({ top: 0, behavior: 'smooth' });
};
return (
<MainContent>
<FilterSection>
<SearchBar onSearch={handleSearch} />
<CategoryFilter
categories={categories}
selectedCategory={selectedCategory}
onCategoryChange={handleCategoryChange}
/>
</FilterSection>
{loading ? (
<LoadingSpinner />
) : works.length > 0 ? (
<>
<WorksGrid>
{currentWorks.map((work) => (
<WorkCard key={work.作品ID} work={work} />
))}
</WorksGrid>
<Pagination
currentPage={currentPage}
totalPages={totalPages}
totalItems={works.length}
itemsPerPage={itemsPerPage}
onPageChange={handlePageChange}
/>
</>
) : (
<NoResults>
{searchQuery || selectedCategory ? '🔍 没有找到匹配的作品' : '📝 暂无作品'}
</NoResults>
)}
</MainContent>
);
};
function App() {
const [settings, setSettings] = useState({});
const [backgroundUrl, setBackgroundUrl] = useState(null);
const [blurConfig] = useState(BACKGROUND_CONFIG.blur || { enabled: true, amount: '6px', overlayOpacity: 0.35 });
useEffect(() => {
loadSettings();
}, []);
// 将后端 settings.json 中的「网站名字」同步到浏览器标签页标题
useEffect(() => {
if (settings['网站名字']) {
document.title = settings['网站名字'];
}
}, [settings]);
// 页面初始化时,根据设备类型随机选择一张背景图
useEffect(() => {
const isMobile = window.innerWidth <= 768;
const url = pickBackgroundImage(isMobile);
if (url) {
setBackgroundUrl(url);
}
}, []);
const loadSettings = async () => {
try {
const settingsData = await getSettings();
setSettings(settingsData);
} catch (error) {
console.error('加载设置失败:', error);
}
};
return (
<Router>
<AppContainer
$backgroundUrl={backgroundUrl}
$blurAmount={blurConfig.enabled ? blurConfig.amount : '0px'}
$blurOverlayOpacity={blurConfig.enabled ? blurConfig.overlayOpacity : 0}
>
<Header settings={settings} />
<Routes>
<Route path="/" element={<HomePage settings={settings} />} />
<Route path="/work/:workId" element={<WorkDetail />} />
<Route path="/admin" element={<AdminPanel />} />
</Routes>
<Footer settings={settings} />
</AppContainer>
</Router>
);
}
export default App;

View File

@@ -0,0 +1,324 @@
import React, { useState, useEffect } from 'react';
import { useSearchParams, useNavigate } from 'react-router-dom';
import styled from 'styled-components';
import LoadingSpinner from './LoadingSpinner';
import WorkEditor from './WorkEditor';
import { setAdminToken, adminGetWorks, adminDeleteWork, getAdminToken } from '../services/adminApi';
const AdminContainer = styled.div`
max-width: 1200px;
margin: 0 auto;
padding: 20px;
@media (max-width: 768px) {
padding: 10px;
}
`;
const AdminHeader = styled.div`
background: white;
border-radius: 15px;
padding: 20px;
margin-bottom: 20px;
box-shadow: 0 4px 20px rgba(0, 0, 0, 0.1);
display: flex;
justify-content: space-between;
align-items: center;
@media (max-width: 768px) {
flex-direction: column;
gap: 15px;
text-align: center;
}
`;
const AdminTitle = styled.h1`
color: #2e7d32;
font-size: 1.8rem;
margin: 0;
@media (max-width: 768px) {
font-size: 1.5rem;
}
`;
const ButtonGroup = styled.div`
display: flex;
gap: 10px;
@media (max-width: 768px) {
flex-direction: column;
width: 100%;
}
`;
const Button = styled.button`
background: ${props => props.variant === 'danger' ? '#f44336' : '#81c784'};
color: white;
border: none;
padding: 10px 20px;
border-radius: 8px;
cursor: pointer;
font-size: 14px;
transition: background 0.3s ease;
&:hover {
background: ${props => props.variant === 'danger' ? '#d32f2f' : '#66bb6a'};
}
&:disabled {
background: #ccc;
cursor: not-allowed;
}
@media (max-width: 768px) {
padding: 12px 16px;
width: 100%;
}
`;
const WorksList = styled.div`
background: white;
border-radius: 15px;
padding: 20px;
box-shadow: 0 4px 20px rgba(0, 0, 0, 0.1);
@media (max-width: 768px) {
padding: 15px;
}
`;
const WorkItem = styled.div`
display: flex;
justify-content: space-between;
align-items: center;
padding: 15px;
border: 1px solid #eee;
border-radius: 8px;
margin-bottom: 10px;
transition: background 0.3s ease;
&:hover {
background: #f8f9fa;
}
@media (max-width: 768px) {
flex-direction: column;
align-items: stretch;
gap: 10px;
}
`;
const WorkInfo = styled.div`
flex: 1;
@media (max-width: 768px) {
text-align: center;
}
`;
const WorkTitle = styled.h3`
color: #2e7d32;
margin: 0 0 5px 0;
font-size: 1.1rem;
`;
const WorkMeta = styled.p`
color: #666;
margin: 0;
font-size: 0.9rem;
`;
const WorkActions = styled.div`
display: flex;
gap: 8px;
@media (max-width: 768px) {
justify-content: center;
}
`;
const SmallButton = styled.button`
background: ${props => {
if (props.variant === 'danger') return '#f44336';
if (props.variant === 'secondary') return '#757575';
return '#81c784';
}};
color: white;
border: none;
padding: 6px 12px;
border-radius: 6px;
cursor: pointer;
font-size: 12px;
transition: background 0.3s ease;
&:hover {
background: ${props => {
if (props.variant === 'danger') return '#d32f2f';
if (props.variant === 'secondary') return '#616161';
return '#66bb6a';
}};
}
`;
const ErrorMessage = styled.div`
background: #ffebee;
color: #c62828;
padding: 15px;
border-radius: 8px;
margin-bottom: 20px;
text-align: center;
`;
const AdminPanel = () => {
const [searchParams] = useSearchParams();
const navigate = useNavigate();
const [works, setWorks] = useState([]);
const [loading, setLoading] = useState(true);
const [error, setError] = useState(null);
const [showEditor, setShowEditor] = useState(false);
const [editingWork, setEditingWork] = useState(null);
useEffect(() => {
const urlToken = searchParams.get('token');
const currentToken = getAdminToken();
// 如果没有 URL token 且也没有之前设置的 token则认为未授权返回首页
if (!urlToken && !currentToken) {
navigate('/');
return;
}
// URL 上有 token 时,更新全局 admin token
if (urlToken && urlToken !== currentToken) {
setAdminToken(urlToken);
}
loadWorks();
}, [searchParams, navigate]);
const loadWorks = async () => {
try {
setLoading(true);
setError(null);
const response = await adminGetWorks();
if (response.success) {
setWorks(response.data);
} else {
setError(response.message);
}
} catch (error) {
console.error('加载作品失败:', error);
setError('加载作品失败,请检查网络连接');
} finally {
setLoading(false);
}
};
const handleCreateWork = () => {
setEditingWork(null);
setShowEditor(true);
};
const handleEditWork = (work) => {
setEditingWork(work);
setShowEditor(true);
};
const handleDeleteWork = async (workId) => {
if (!window.confirm('确定要删除这个作品吗?此操作不可恢复!')) {
return;
}
try {
const response = await adminDeleteWork(workId);
if (response.success) {
alert('删除成功!');
loadWorks();
} else {
alert(`删除失败:${response.message}`);
}
} catch (error) {
console.error('删除作品失败:', error);
alert('删除失败,请稍后重试');
}
};
const handleEditorClose = () => {
setShowEditor(false);
setEditingWork(null);
loadWorks();
};
const handleBackToHome = () => {
navigate('/');
};
if (showEditor) {
return (
<WorkEditor
work={editingWork}
onClose={handleEditorClose}
/>
);
}
return (
<AdminContainer>
<AdminHeader>
<AdminTitle>管理员面板</AdminTitle>
<ButtonGroup>
<Button onClick={handleCreateWork}>
+ 添加新作品
</Button>
<Button variant="secondary" onClick={handleBackToHome}>
返回首页
</Button>
</ButtonGroup>
</AdminHeader>
{error && <ErrorMessage>{error}</ErrorMessage>}
{loading ? (
<LoadingSpinner text="加载作品列表中..." />
) : (
<WorksList>
<h2 style={{ color: '#2e7d32', marginBottom: '20px' }}>
作品列表 ({works.length})
</h2>
{works.length === 0 ? (
<div style={{ textAlign: 'center', color: '#666', padding: '40px' }}>
暂无作品点击上方按钮添加新作品
</div>
) : (
works.map((work) => (
<WorkItem key={work.作品ID}>
<WorkInfo>
<WorkTitle>{work.作品作品}</WorkTitle>
<WorkMeta>
ID: {work.作品ID} | 分类: {work.作品分类} | 版本: {work.作品版本号} |
更新: {new Date(work.更新时间).toLocaleDateString('zh-CN')}
</WorkMeta>
</WorkInfo>
<WorkActions>
<SmallButton onClick={() => handleEditWork(work)}>
编辑
</SmallButton>
<SmallButton
variant="danger"
onClick={() => handleDeleteWork(work.作品ID)}
>
删除
</SmallButton>
</WorkActions>
</WorkItem>
))
)}
</WorksList>
)}
</AdminContainer>
);
};
export default AdminPanel;

View File

@@ -0,0 +1,80 @@
import React from 'react';
import styled from 'styled-components';
import { getGlassOpacity } from '../config/background';
const glassOpacity = getGlassOpacity();
const FilterContainer = styled.div`
display: flex;
align-items: center;
gap: 10px;
@media (max-width: 768px) {
flex-direction: column;
align-items: stretch;
gap: 8px;
}
`;
const FilterLabel = styled.label`
font-weight: 500;
color: #2e7d32;
white-space: nowrap;
@media (max-width: 768px) {
font-size: 14px;
}
`;
const FilterSelect = styled.select`
padding: 8px 12px;
border: 2px solid #e0e0e0;
border-radius: 8px;
font-size: 14px;
background: rgba(255, 255, 255, ${glassOpacity});
color: #333;
outline: none;
cursor: pointer;
transition: all 0.3s ease;
min-width: 120px;
&:focus {
border-color: #81c784;
box-shadow: 0 0 0 3px rgba(129, 199, 132, 0.1);
}
&:hover {
border-color: #81c784;
}
@media (max-width: 768px) {
width: 100%;
min-width: auto;
}
`;
const CategoryFilter = ({ categories, selectedCategory, onCategoryChange }) => {
const handleChange = (e) => {
onCategoryChange(e.target.value);
};
return (
<FilterContainer>
<FilterLabel htmlFor="category-filter">分类筛选:</FilterLabel>
<FilterSelect
id="category-filter"
value={selectedCategory}
onChange={handleChange}
>
<option value="">全部分类</option>
{categories.map((category) => (
<option key={category} value={category}>
{category}
</option>
))}
</FilterSelect>
</FilterContainer>
);
};
export default CategoryFilter;

View File

@@ -0,0 +1,228 @@
import React from 'react';
import styled from 'styled-components';
import { getGlassOpacity } from '../config/background';
const glassOpacity = getGlassOpacity();
const FooterContainer = styled.footer`
/* 底部整体背景完全透明,仅保留内部内容样式 */
background: transparent;
background-color: transparent;
color: #1b5e20;
padding: 35px 0 25px;
margin-top: 50px;
position: relative;
overflow: hidden;
transition: all 0.6s cubic-bezier(0.4, 0, 0.2, 1);
border-radius: 25px 25px 0 0;
box-shadow: 0 -8px 32px rgba(27, 94, 32, 0.15);
&::before {
content: '';
position: absolute;
top: 0;
left: 0;
right: 0;
height: 3px;
background: linear-gradient(90deg, #4caf50, #66bb6a, #81c784, #66bb6a, #4caf50);
background-size: 200% 100%;
animation: flowingTopBorder 3s ease-in-out infinite;
}
&::after {
content: '';
position: absolute;
top: 10px;
left: -100%;
width: 100%;
height: 100%;
background: linear-gradient(90deg, transparent, rgba(255, 255, 255, 0.1), transparent);
animation: shimmer 5s infinite;
}
@keyframes flowingTopBorder {
0%, 100% { background-position: 0% 50%; }
50% { background-position: 100% 50%; }
}
@keyframes shimmer {
0% { left: -100%; }
100% { left: 100%; }
}
&:hover {
transform: translateY(-3px);
box-shadow: 0 -12px 40px rgba(27, 94, 32, 0.2);
}
@media (max-width: 768px) {
padding: 25px 0 20px;
margin-top: 35px;
}
`;
const FooterContent = styled.div`
max-width: 1200px;
margin: 0 auto;
padding: 0 20px;
text-align: center;
animation: fadeInUp 0.8s ease-out;
@keyframes fadeInUp {
from {
opacity: 0;
transform: translateY(30px);
}
to {
opacity: 1;
transform: translateY(0);
}
}
@media (max-width: 768px) {
padding: 0 10px;
}
`;
const FooterText = styled.p`
font-size: 0.9rem;
color: rgba(255, 255, 255, 0.9);
text-shadow: 0 2px 8px rgba(27, 94, 32, 0.3);
margin-bottom: 10px;
transition: all 0.3s ease;
&:hover {
color: rgba(255, 255, 255, 1);
transform: translateY(-1px);
}
@media (max-width: 768px) {
font-size: 0.8rem;
margin-bottom: 8px;
}
`;
const ContactInfo = styled.div`
margin-bottom: 15px;
animation: slideInLeft 0.8s ease-out 0.2s both;
@keyframes slideInLeft {
from {
opacity: 0;
transform: translateX(-20px);
}
to {
opacity: 1;
transform: translateX(0);
}
}
@media (max-width: 768px) {
margin-bottom: 12px;
}
`;
const ContactLink = styled.a`
color: rgba(255, 255, 255, 0.9);
text-decoration: none;
text-shadow: 0 2px 8px rgba(27, 94, 32, 0.3);
transition: all 0.3s cubic-bezier(0.4, 0, 0.2, 1);
position: relative;
&::after {
content: '';
position: absolute;
bottom: -2px;
left: 0;
width: 0;
height: 2px;
background: linear-gradient(90deg, rgba(255, 255, 255, 0.8), rgba(255, 255, 255, 1));
transition: width 0.3s ease;
}
&:hover {
color: rgba(255, 255, 255, 1);
transform: translateY(-1px);
&::after {
width: 100%;
}
}
`;
const RecordNumber = styled.p`
font-size: 0.8rem;
color: rgba(255, 255, 255, 0.7);
text-shadow: 0 2px 8px rgba(27, 94, 32, 0.3);
margin-bottom: 5px;
animation: slideInRight 0.8s ease-out 0.4s both;
transition: all 0.3s ease;
@keyframes slideInRight {
from {
opacity: 0;
transform: translateX(20px);
}
to {
opacity: 1;
transform: translateX(0);
}
}
&:hover {
color: rgba(255, 255, 255, 0.9);
transform: translateY(-1px);
}
@media (max-width: 768px) {
font-size: 0.75rem;
}
`;
const Copyright = styled.p`
font-size: 0.8rem;
color: rgba(255, 255, 255, 0.7);
text-shadow: 0 2px 8px rgba(27, 94, 32, 0.3);
animation: fadeIn 0.8s ease-out 0.6s both;
transition: all 0.3s ease;
@keyframes fadeIn {
from { opacity: 0; }
to { opacity: 0.7; }
}
&:hover {
color: rgba(255, 255, 255, 0.9);
transform: translateY(-1px);
}
@media (max-width: 768px) {
font-size: 0.75rem;
}
`;
const Footer = ({ settings }) => {
return (
<FooterContainer>
<FooterContent>
<ContactInfo>
<FooterText>
📧 联系邮箱: <ContactLink href={`mailto:${settings.联系邮箱}`}>
{settings.联系邮箱}
</ContactLink>
</FooterText>
</ContactInfo>
{settings.备案号 && (
<RecordNumber>{settings.备案号}</RecordNumber>
)}
<Copyright>
{settings.网站页尾 || '🌱 树萌芽の作品集 | Copyright © 2025 smy ✨'}
</Copyright>
</FooterContent>
</FooterContainer>
);
};
export default Footer;

View File

@@ -0,0 +1,284 @@
import React, { useRef } from 'react';
import styled from 'styled-components';
import { getGlassOpacity } from '../config/background';
import { setAdminToken, adminGetWorks } from '../services/adminApi';
const glassOpacity = getGlassOpacity();
const HeaderContainer = styled.header`
/* 顶部整体背景完全透明,仅保留内部内容样式 */
background: transparent;
background-color: transparent;
color: #1b5e20; /* 深绿色文字 */
padding: 25px 0; /* 上下内边距 */
box-shadow: 0 8px 32px rgba(27, 94, 32, 0.15); /* 深绿色阴影效果 */
position: relative; /* 相对定位,为伪元素提供定位基准 */
overflow: hidden; /* 隐藏溢出内容,确保动画效果不会超出边界 */
transition: all 0.6s cubic-bezier(0.4, 0, 0.2, 1); /* 平滑过渡动画 */
border-radius: 0 0 25px 25px; /* 底部圆角,营造圆润效果 */
margin-bottom: 10px; /* 与下方内容的间距 */
/* 光泽动画效果:从左到右的白色光泽扫过 */
&::before {
content: '';
position: absolute;
top: 0;
left: -100%; /* 初始位置在左侧外部 */
width: 100%;
height: 100%;
/* 半透明白色渐变,中间较亮 */
background: linear-gradient(90deg, transparent, rgba(255, 255, 255, 0.15), transparent);
animation: shimmer 4s infinite; /* 4秒循环的光泽动画 */
}
/* 底部流动边框:彩色边框从左到右流动 */
&::after {
content: '';
position: absolute;
bottom: 0;
left: 0;
right: 0;
height: 3px; /* 边框高度 */
/* 绿色系渐变边框 */
background: linear-gradient(90deg,rgb(21, 221, 31),rgb(2, 233, 14),rgb(0, 161, 5),rgb(0, 25rgb(12, 221, 23)#66bb6a);
background-size: 200% 100%; /* 背景尺寸为200%,用于动画效果 */
animation: flowingBorder 3s ease-in-out infinite; /* 3秒循环的流动动画 */
}
/* 光泽扫过动画:从左侧移动到右侧 */
@keyframes shimmer {
0% { left: -100%; } /* 开始位置:左侧外部 */
100% { left: 100%; } /* 结束位置:右侧外部 */
}
/* 边框流动动画:背景位置左右移动 */
@keyframes flowingBorder {
0%, 100% { background-position: 0% 50%; } /* 起始和结束位置 */
50% { background-position: 100% 50%; } /* 中间位置 */
}
/* 悬停效果:增强阴影和轻微上移 */
&:hover {
box-shadow: 0 12px 40px rgba(27, 94, 32, 0.2); /* 更深的阴影 */
transform: translateY(-2px); /* 向上移动2像素 */
}
`;
const HeaderContent = styled.div`
max-width: 1200px; /* 最大宽度限制 */
margin: 0 auto; /* 水平居中 */
padding: 0 20px; /* 左右内边距 */
text-align: center; /* 文字居中对齐 */
display: flex; /* 弹性布局 */
flex-direction: column; /* 垂直排列 */
align-items: center; /* 子元素居中对齐 */
/* 移动端响应式:减少左右内边距 */
@media (max-width: 768px) {
padding: 0 10px;
}
`;
const LogoContainer = styled.div`
margin-bottom: 15px; /* 底部间距 */
animation: fadeInUp 0.8s ease-out; /* 淡入向上动画 */
/* Logo淡入动画从下方淡入 */
@keyframes fadeInUp {
from {
opacity: 0; /* 初始透明 */
transform: translateY(20px); /* 初始向下偏移 */
}
to {
opacity: 1; /* 最终不透明 */
transform: translateY(0); /* 最终正常位置 */
}
}
/* 移动端响应式:减少底部间距 */
@media (max-width: 768px) {
margin-bottom: 10px;
}
`;
const Logo = styled.img`
height: 80px; /* Logo高度 */
width: auto; /* 宽度自适应,保持比例 */
border-radius: 12px; /* 圆角效果 */
transition: all 0.4s cubic-bezier(0.4, 0, 0.2, 1); /* 平滑过渡动画 */
filter: drop-shadow(0 2px 8px rgba(46, 93, 49, 0.15)); /* 投影效果 */
cursor: pointer;
/* Logo悬停效果放大并轻微旋转 */
&:hover {
transform: scale(1.05) rotate(2deg); /* 放大105%并旋转2度 */
filter: drop-shadow(0 4px 12px rgba(46, 93, 49, 0.25)); /* 增强投影 */
}
/* 移动端响应式减小Logo尺寸 */
@media (max-width: 768px) {
height: 60px;
}
`;
const Title = styled.h1`
font-size: 3rem; /* 标题字体大小 */
margin-bottom: 10px; /* 底部间距 */
font-weight: 700; /* 字体粗细 */
position: relative; /* 相对定位,为伪元素提供基准 */
/* 文字颜色:纯白色,保持清晰可读 */
color: #ffffff;
/* 金色描边效果:使用-webkit-text-stroke创建外描边 */
-webkit-text-stroke: 2px #ffd700; /* 2像素金色描边 */
text-stroke: 2px #ffd700; /* 标准属性 */
/* 外围辐射金光:只在外围产生光晕,不影响文字内部 */
filter: drop-shadow(0 0 4px #ffd700)
drop-shadow(0 0 8px #ffd700)
drop-shadow(0 0 12px #ffed4e);
/* 底部立体阴影 */
text-shadow: 0 3px 6px rgba(0,0,0,0.3);
/* 淡入向上动画 + 金光闪烁效果 */
animation:
fadeInUp 0.8s ease-out 0.2s both, /* 淡入向上动画 */
goldGlow 3s ease-in-out infinite; /* 金光闪烁效果 */
/* 淡入向上动画 */
@keyframes fadeInUp {
from {
opacity: 0; /* 初始透明 */
transform: translateY(20px); /* 初始位置向下偏移 */
}
to {
opacity: 1; /* 最终不透明 */
transform: translateY(0); /* 最终位置正常 */
}
}
/* 响应式设计:移动端字体大小调整 */
@media (max-width: 768px) {
font-size: 2.5rem; /* 移动端较小字体 */
-webkit-text-stroke: 1.5px #ffd700; /* 移动端较细描边 */
/* 移动端减弱光晕效果,避免性能问题 */
filter: drop-shadow(0 0 6px #ffd700)
drop-shadow(0 0 12px #ffed4e);
}
`;
const Description = styled.p`
font-size: 1.1rem; /* 描述文字大小 */
color: rgba(255, 255, 255, 0.9); /* 半透明白色文字 */
text-shadow: 0 2px 8px rgba(27, 94, 32, 0.3); /* 绿色文字阴影 */
margin-bottom: 5px; /* 底部间距 */
animation: fadeInUp 0.8s ease-out 0.4s both; /* 延迟0.4秒的淡入动画 */
transition: all 0.3s ease; /* 平滑过渡效果 */
/* 描述文字悬停效果:变为完全不透明并上移 */
&:hover {
color: rgba(255, 255, 255, 1); /* 完全不透明的白色 */
transform: translateY(-2px); /* 向上移动2像素 */
}
/* 移动端响应式:减小字体大小 */
@media (max-width: 768px) {
font-size: 1rem;
}
`;
const Author = styled.p`
font-size: 0.9rem; /* 作者信息字体大小 */
color: rgba(255, 255, 255, 0.8); /* 更透明的白色文字 */
text-shadow: 0 2px 8px rgba(27, 94, 32, 0.3); /* 绿色文字阴影 */
animation: fadeInUp 0.8s ease-out 0.6s both; /* 延迟0.6秒的淡入动画 */
transition: all 0.3s ease; /* 平滑过渡效果 */
/* 作者信息悬停效果:变为完全不透明并上移 */
&:hover {
color: rgba(255, 255, 255, 1); /* 完全不透明的白色 */
transform: translateY(-2px); /* 向上移动2像素 */
}
`;
const DEFAULT_LOGO = `${process.env.PUBLIC_URL || ''}/assets/logo.png`;
const DEFAULT_FAVICON = `${process.env.PUBLIC_URL || ''}/assets/icon.png`;
const Header = ({ settings }) => {
// 隐藏入口:点击 Logo 5 次后触发管理员口令输入
const logoClickCountRef = useRef(0);
const lastClickTimeRef = useRef(0);
// 动态设置 favicon优先使用后端配置的网站 logo否则使用前端默认 icon
React.useEffect(() => {
const iconHref = settings.网站logo || DEFAULT_FAVICON;
const existing = document.querySelector('link[rel="icon"]');
if (existing) {
existing.href = iconHref;
} else {
const link = document.createElement('link');
link.rel = 'icon';
link.href = iconHref;
document.head.appendChild(link);
}
}, [settings.网站logo]);
const handleLogoSecretClick = () => {
const now = Date.now();
const interval = now - lastClickTimeRef.current;
// 超过 2 秒则重新计数,避免误触
if (interval > 2000) {
logoClickCountRef.current = 0;
}
lastClickTimeRef.current = now;
logoClickCountRef.current += 1;
if (logoClickCountRef.current >= 5) {
logoClickCountRef.current = 0;
const tokenInput = window.prompt('请输入管理员口令进入后台:');
if (!tokenInput) return;
const token = tokenInput.trim();
setAdminToken(token);
// 简单校验:尝试拉取一次后台作品列表
adminGetWorks()
.then(() => {
window.location.hash = '#/admin';
})
.catch(() => {
// eslint-disable-next-line no-alert
alert('口令错误或无权限,请重试。');
});
}
};
return (
<HeaderContainer>
<HeaderContent>
<LogoContainer>
<Logo
src={settings.网站logo || DEFAULT_LOGO}
alt={settings.网站名字 || '树萌芽の作品集'}
onClick={handleLogoSecretClick}
onError={(e) => {
e.target.style.display = 'none';
}}
/>
</LogoContainer>
<Title>{settings.网站名字 || '树萌芽の作品集'}</Title>
<Description>{settings.网站描述 || '展示我的创意作品和项目'}</Description>
<Author>{settings.站长 || '树萌芽'}</Author>
</HeaderContent>
</HeaderContainer>
);
};
export default Header;

View File

@@ -0,0 +1,150 @@
import React from 'react';
import styled, { keyframes } from 'styled-components';
// 背景柔和脉冲动画(亮度轻微变化)
const bgPulse = keyframes`
0%, 100% { opacity: 1; }
50% { opacity: 0.96; }
`;
// Logo 轻微上下浮动
const float = keyframes`
0%, 100% { transform: translateY(0); }
50% { transform: translateY(-8px); }
`;
// 扩散圆环动画
const ringPulse = keyframes`
0% {
transform: scale(0.8);
opacity: 0.6;
}
70% {
transform: scale(1.4);
opacity: 0;
}
100% {
transform: scale(1.4);
opacity: 0;
}
`;
// 底部三个圆点缩放动画
const dotPulse = keyframes`
0%, 80%, 100% { transform: scale(0.6); opacity: 0.4; }
40% { transform: scale(1); opacity: 1; }
`;
const SplashWrapper = styled.div`
position: fixed;
inset: 0;
z-index: 9999;
display: flex;
align-items: center;
justify-content: center;
background: radial-gradient(circle at top left, rgba(232, 245, 233, 0.9), rgba(200, 230, 201, 0.9)),
radial-gradient(circle at bottom right, rgba(255, 255, 224, 0.8), rgba(240, 255, 240, 0.9));
animation: ${bgPulse} 6s ease-in-out infinite;
`;
const SplashInner = styled.div`
position: relative;
text-align: center;
padding: 32px 40px 28px;
border-radius: 24px;
background: rgba(255, 255, 255, 0.28);
box-shadow:
0 18px 45px rgba(129, 199, 132, 0.35),
0 0 40px rgba(129, 199, 132, 0.25);
backdrop-filter: blur(12px);
`;
const LogoWrapper = styled.div`
position: relative;
width: 112px;
height: 112px;
margin: 0 auto 18px;
border-radius: 28px;
background: radial-gradient(circle at 30% 20%, #ffffff, #e8f5e9);
box-shadow:
0 10px 26px rgba(67, 160, 71, 0.35),
0 0 25px rgba(129, 199, 132, 0.45);
display: flex;
align-items: center;
justify-content: center;
animation: ${float} 3s ease-in-out infinite;
overflow: hidden;
`;
const LogoImage = styled.img`
width: 76px;
height: 76px;
border-radius: 22px;
object-fit: cover;
`;
const Ring = styled.div`
position: absolute;
inset: 0;
border-radius: 999px;
border: 2px solid rgba(129, 199, 132, 0.7);
animation: ${ringPulse} 2.6s ease-out infinite;
animation-delay: ${({ $delay }) => $delay || '0s'};
`;
const Title = styled.h2`
font-size: 1.5rem;
font-weight: 700;
color: #2e7d32;
margin-bottom: 6px;
letter-spacing: 0.06em;
text-shadow: 0 2px 6px rgba(76, 175, 80, 0.35);
`;
const Subtitle = styled.p`
font-size: 0.95rem;
color: #4caf50;
margin-bottom: 16px;
`;
const Dots = styled.div`
display: flex;
justify-content: center;
gap: 8px;
margin-top: 2px;
`;
const Dot = styled.span`
width: 8px;
height: 8px;
border-radius: 50%;
background: #66bb6a;
animation: ${dotPulse} 1.4s ease-in-out infinite;
animation-delay: ${({ $delay }) => $delay || '0s'};
`;
const LOGO_SRC = `${process.env.PUBLIC_URL || ''}/assets/icon.png`;
const LoadingSpinner = ({ text = '加载中...' }) => {
return (
<SplashWrapper>
<SplashInner>
<LogoWrapper>
<Ring $delay="0s" />
<Ring $delay="0.5s" />
<Ring $delay="1s" />
<LogoImage src={LOGO_SRC} alt="萌芽作品集 Logo" />
</LogoWrapper>
<Title> 萌芽作品集 </Title>
<Subtitle>{text}</Subtitle>
<Dots>
<Dot $delay="0s" />
<Dot $delay="0.15s" />
<Dot $delay="0.3s" />
</Dots>
</SplashInner>
</SplashWrapper>
);
};
export default LoadingSpinner;

View File

@@ -0,0 +1,161 @@
import React from 'react';
import styled from 'styled-components';
const PaginationContainer = styled.div`
display: flex;
justify-content: center;
align-items: center;
margin: 30px 0;
gap: 10px;
flex-wrap: wrap;
`;
const PaginationButton = styled.button`
padding: 8px 12px;
border: 1px solid #81c784;
background: ${props => props.active ? '#81c784' : 'rgba(255, 255, 255, 0.9)'};
color: ${props => props.active ? 'white' : '#2e7d32'};
border-radius: 8px;
cursor: pointer;
font-size: 14px;
font-weight: 500;
transition: all 0.3s ease;
min-width: 40px;
&:hover:not(:disabled) {
background: ${props => props.active ? '#66bb6a' : '#e8f5e8'};
transform: translateY(-1px);
box-shadow: 0 2px 8px rgba(129, 199, 132, 0.3);
}
&:disabled {
opacity: 0.5;
cursor: not-allowed;
transform: none;
box-shadow: none;
}
@media (max-width: 768px) {
padding: 6px 10px;
font-size: 12px;
min-width: 35px;
}
`;
const PageInfo = styled.div`
color: #666;
font-size: 14px;
margin: 0 10px;
@media (max-width: 768px) {
font-size: 12px;
margin: 0 5px;
}
`;
const Ellipsis = styled.span`
color: #666;
padding: 0 5px;
font-weight: bold;
`;
const Pagination = ({
currentPage,
totalPages,
totalItems,
itemsPerPage,
onPageChange
}) => {
if (totalPages <= 1) return null;
const getPageNumbers = () => {
const pages = [];
const maxVisiblePages = 7; // 最多显示7个页码按钮
if (totalPages <= maxVisiblePages) {
// 如果总页数小于等于最大显示页数,显示所有页码
for (let i = 1; i <= totalPages; i++) {
pages.push(i);
}
} else {
// 复杂的分页逻辑
if (currentPage <= 4) {
// 当前页在前面
for (let i = 1; i <= 5; i++) {
pages.push(i);
}
pages.push('...');
pages.push(totalPages);
} else if (currentPage >= totalPages - 3) {
// 当前页在后面
pages.push(1);
pages.push('...');
for (let i = totalPages - 4; i <= totalPages; i++) {
pages.push(i);
}
} else {
// 当前页在中间
pages.push(1);
pages.push('...');
for (let i = currentPage - 1; i <= currentPage + 1; i++) {
pages.push(i);
}
pages.push('...');
pages.push(totalPages);
}
}
return pages;
};
const handlePageClick = (page) => {
if (page !== '...' && page !== currentPage && page >= 1 && page <= totalPages) {
onPageChange(page);
}
};
const startItem = (currentPage - 1) * itemsPerPage + 1;
const endItem = Math.min(currentPage * itemsPerPage, totalItems);
return (
<PaginationContainer>
{/* 上一页按钮 */}
<PaginationButton
onClick={() => handlePageClick(currentPage - 1)}
disabled={currentPage === 1}
>
上一页
</PaginationButton>
{/* 页码按钮 */}
{getPageNumbers().map((page, index) => (
page === '...' ? (
<Ellipsis key={`ellipsis-${index}`}>...</Ellipsis>
) : (
<PaginationButton
key={page}
active={page === currentPage}
onClick={() => handlePageClick(page)}
>
{page}
</PaginationButton>
)
))}
{/* 下一页按钮 */}
<PaginationButton
onClick={() => handlePageClick(currentPage + 1)}
disabled={currentPage === totalPages}
>
下一页
</PaginationButton>
{/* 页面信息 */}
<PageInfo>
{startItem}-{endItem} {totalItems}
</PageInfo>
</PaginationContainer>
);
};
export default Pagination;

View File

@@ -0,0 +1,103 @@
import React, { useState } from 'react';
import styled from 'styled-components';
import { getGlassOpacity } from '../config/background';
const glassOpacity = getGlassOpacity();
const SearchContainer = styled.div`
position: relative;
flex: 1;
max-width: 400px;
@media (max-width: 768px) {
max-width: 100%;
}
`;
const SearchInput = styled.input`
width: 100%;
padding: 12px 45px 12px 15px;
border: 2px solid #e0e0e0;
border-radius: 25px;
font-size: 16px;
outline: none;
transition: all 0.3s ease;
background: rgba(255, 255, 255, ${glassOpacity});
&:focus {
border-color: #81c784;
box-shadow: 0 0 0 3px rgba(129, 199, 132, 0.1);
}
&::placeholder {
color: #999;
}
`;
const SearchButton = styled.button`
position: absolute;
right: 5px;
top: 50%;
transform: translateY(-50%);
background: #81c784;
border: none;
border-radius: 50%;
width: 35px;
height: 35px;
display: flex;
align-items: center;
justify-content: center;
cursor: pointer;
transition: background 0.3s ease;
&:hover {
background: #66bb6a;
}
&:active {
transform: translateY(-50%) scale(0.95);
}
`;
const SearchIcon = styled.span`
color: white;
font-size: 16px;
`;
const SearchBar = ({ onSearch }) => {
const [query, setQuery] = useState('');
const handleSubmit = (e) => {
e.preventDefault();
onSearch(query.trim());
};
const handleInputChange = (e) => {
setQuery(e.target.value);
};
const handleKeyPress = (e) => {
if (e.key === 'Enter') {
handleSubmit(e);
}
};
return (
<SearchContainer>
<form onSubmit={handleSubmit}>
<SearchInput
type="text"
placeholder="搜索作品名称、描述或标签..."
value={query}
onChange={handleInputChange}
onKeyPress={handleKeyPress}
/>
<SearchButton type="submit">
<SearchIcon>🔍</SearchIcon>
</SearchButton>
</form>
</SearchContainer>
);
};
export default SearchBar;

View File

@@ -0,0 +1,369 @@
import React from 'react';
import styled, { keyframes } from 'styled-components';
const fadeIn = keyframes`
from {
opacity: 0;
transform: scale(0.9);
}
to {
opacity: 1;
transform: scale(1);
}
`;
const ModalOverlay = styled.div`
position: fixed;
top: 0;
left: 0;
right: 0;
bottom: 0;
background: rgba(0, 0, 0, 0.7);
display: flex;
align-items: center;
justify-content: center;
z-index: 9999;
backdrop-filter: blur(5px);
`;
const ModalContent = styled.div`
background: white;
border-radius: 20px;
padding: 30px;
min-width: 400px;
max-width: 90vw;
max-height: 80vh;
overflow-y: auto;
box-shadow: 0 20px 60px rgba(0, 0, 0, 0.3);
animation: ${fadeIn} 0.3s ease-out;
@media (max-width: 768px) {
min-width: 300px;
padding: 20px;
margin: 20px;
}
`;
const ModalHeader = styled.div`
display: flex;
justify-content: space-between;
align-items: center;
margin-bottom: 25px;
padding-bottom: 15px;
border-bottom: 2px solid #e8f5e8;
`;
const ModalTitle = styled.h2`
color: #2e7d32;
font-size: 1.5rem;
margin: 0;
display: flex;
align-items: center;
gap: 10px;
`;
const CloseButton = styled.button`
background: none;
border: none;
font-size: 1.5rem;
color: #666;
cursor: pointer;
padding: 5px;
border-radius: 50%;
transition: all 0.3s ease;
&:hover {
background: #f0f0f0;
color: #333;
}
&:disabled {
opacity: 0.5;
cursor: not-allowed;
}
`;
const UploadList = styled.div`
max-height: 400px;
overflow-y: auto;
`;
const UploadItem = styled.div`
margin-bottom: 20px;
padding: 15px;
background: #f8f9fa;
border-radius: 12px;
border-left: 4px solid #81c784;
&:last-child {
margin-bottom: 0;
}
`;
const FileInfo = styled.div`
display: flex;
justify-content: space-between;
align-items: center;
margin-bottom: 10px;
flex-wrap: wrap;
gap: 10px;
`;
const FileName = styled.div`
font-weight: 500;
color: #333;
word-break: break-all;
flex: 1;
`;
const FileSize = styled.div`
font-size: 0.9rem;
color: #666;
background: #e0e0e0;
padding: 2px 8px;
border-radius: 12px;
`;
const ProgressInfo = styled.div`
display: flex;
justify-content: space-between;
align-items: center;
margin-bottom: 8px;
font-size: 0.9rem;
`;
const ProgressText = styled.span`
color: #2e7d32;
font-weight: 500;
`;
const ProgressPercentage = styled.span`
color: #666;
font-weight: bold;
`;
const ProgressBarContainer = styled.div`
width: 100%;
height: 12px;
background: #e0e0e0;
border-radius: 6px;
overflow: hidden;
margin-bottom: 5px;
`;
const ProgressBar = styled.div`
height: 100%;
background: linear-gradient(90deg, #4caf50, #81c784);
transition: width 0.3s ease;
width: ${props => props.progress}%;
border-radius: 6px;
position: relative;
&::after {
content: '';
position: absolute;
top: 0;
left: 0;
right: 0;
bottom: 0;
background: linear-gradient(
90deg,
transparent,
rgba(255, 255, 255, 0.3),
transparent
);
animation: shimmer 2s infinite;
}
@keyframes shimmer {
0% { transform: translateX(-100%); }
100% { transform: translateX(100%); }
}
`;
const SpeedInfo = styled.div`
font-size: 0.8rem;
color: #999;
display: flex;
justify-content: space-between;
`;
const StatusIcon = styled.span`
font-size: 1.2rem;
margin-right: 5px;
`;
const RetryInfo = styled.div`
font-size: 0.8rem;
color: #ff9800;
margin-bottom: 5px;
display: flex;
align-items: center;
gap: 5px;
`;
const ErrorMessage = styled.div`
font-size: 0.8rem;
color: #f44336;
margin-top: 5px;
padding: 5px 8px;
background: #ffebee;
border-radius: 4px;
border-left: 3px solid #f44336;
`;
const EmptyState = styled.div`
text-align: center;
padding: 40px 20px;
color: #666;
font-size: 1.1rem;
`;
const formatFileSize = (bytes) => {
if (bytes === 0) return '0 B';
const k = 1024;
const sizes = ['B', 'KB', 'MB', 'GB'];
const i = Math.floor(Math.log(bytes) / Math.log(k));
return parseFloat((bytes / Math.pow(k, i)).toFixed(1)) + ' ' + sizes[i];
};
const formatSpeed = (bytesPerSecond) => {
return formatFileSize(bytesPerSecond) + '/s';
};
const formatETA = (seconds) => {
if (!seconds || seconds <= 0) return '计算中...';
if (seconds < 60) return `${seconds}`;
if (seconds < 3600) return `${Math.round(seconds / 60)}分钟`;
return `${Math.round(seconds / 3600)}小时`;
};
const calculateETA = (uploaded, total, speed) => {
if (speed === 0 || uploaded >= total) return '完成';
const remaining = total - uploaded;
const seconds = Math.round(remaining / speed);
return formatETA(seconds);
};
const UploadProgressModal = ({
isOpen,
onClose,
uploadItems,
canClose = true
}) => {
if (!isOpen) return null;
const hasActiveUploads = Object.keys(uploadItems).length > 0;
return (
<ModalOverlay onClick={canClose ? onClose : undefined}>
<ModalContent onClick={(e) => e.stopPropagation()}>
<ModalHeader>
<ModalTitle>
<StatusIcon>📤</StatusIcon>
文件上传进度
{hasActiveUploads && <span style={{ color: '#81c784' }}>({Object.keys(uploadItems).length})</span>}
</ModalTitle>
<CloseButton
onClick={onClose}
disabled={!canClose}
title={canClose ? '关闭' : '上传中,无法关闭'}
>
×
</CloseButton>
</ModalHeader>
<UploadList>
{!hasActiveUploads ? (
<EmptyState>
<StatusIcon></StatusIcon>
当前没有文件上传任务
</EmptyState>
) : (
Object.entries(uploadItems).map(([fileKey, uploadInfo]) => {
const {
fileName,
fileSize,
progress,
uploaded,
speed,
status,
retryCount,
eta,
error
} = uploadInfo;
const isCompleted = status === 'completed' || progress >= 100;
const isFailed = status === 'error';
const isRetrying = status === 'retrying';
const isUploading = status === 'uploading' || (!status && progress < 100);
return (
<UploadItem key={fileKey}>
<FileInfo>
<FileName>
{isCompleted && <StatusIcon></StatusIcon>}
{isFailed && <StatusIcon></StatusIcon>}
{isRetrying && <StatusIcon>🔄</StatusIcon>}
{isUploading && <StatusIcon>📤</StatusIcon>}
{fileName}
</FileName>
<FileSize>{formatFileSize(fileSize)}</FileSize>
</FileInfo>
{/* 重试信息 */}
{(isRetrying || (retryCount > 0 && !isCompleted)) && (
<RetryInfo>
<span>🔄</span>
{isRetrying ? '重试中...' : `已重试 ${retryCount}`}
</RetryInfo>
)}
<ProgressInfo>
<ProgressText>
{isFailed ? '上传失败' :
isCompleted ? '上传完成' :
isRetrying ? '重试中...' : '上传中...'}
</ProgressText>
<ProgressPercentage>{progress}%</ProgressPercentage>
</ProgressInfo>
<ProgressBarContainer>
<ProgressBar progress={progress} />
</ProgressBarContainer>
<SpeedInfo>
<span>
{formatFileSize(uploaded || 0)} / {formatFileSize(fileSize)}
</span>
{(isUploading || isRetrying) && (
<span>
{speed > 0 && (
<>
{formatSpeed(speed)}
{eta > 0 ? ` • 剩余 ${formatETA(eta)}` :
speed > 0 ? ` • 剩余 ${calculateETA(uploaded || 0, fileSize, speed)}` : ''}
</>
)}
{speed === 0 && !isRetrying && '计算速度中...'}
</span>
)}
</SpeedInfo>
{/* 错误信息 */}
{(isFailed || error) && (
<ErrorMessage>
{error || '上传失败,请重试'}
</ErrorMessage>
)}
</UploadItem>
);
})
)}
</UploadList>
</ModalContent>
</ModalOverlay>
);
};
export default UploadProgressModal;

View File

@@ -0,0 +1,254 @@
import React from 'react';
import { useNavigate } from 'react-router-dom';
import styled from 'styled-components';
import { getApiOrigin } from '../config/apiBase';
import { getGlassOpacity } from '../config/background';
const glassOpacity = getGlassOpacity();
const Card = styled.div`
background: linear-gradient(145deg, rgba(255, 255, 255, ${0.7 + glassOpacity * 0.3}), rgba(248, 255, 248, ${0.7 + glassOpacity * 0.3}));
border-radius: 15px;
box-shadow: 0 4px 20px rgba(0, 0, 0, 0.1);
overflow: hidden;
transition: all 0.3s ease;
cursor: pointer;
border: 1px solid rgba(129, 199, 132, 0.2);
&:hover {
transform: translateY(-5px);
box-shadow: 0 8px 30px rgba(129, 199, 132, 0.2);
border-color: rgba(129, 199, 132, 0.4);
}
`;
const ImageContainer = styled.div`
position: relative;
width: 100%;
height: 200px;
overflow: hidden;
background: #f5f5f5;
`;
const WorkImage = styled.img`
width: 100%;
height: 100%;
object-fit: cover;
transition: transform 0.3s ease;
${Card}:hover & {
transform: scale(1.05);
}
`;
const ImagePlaceholder = styled.div`
width: 100%;
height: 100%;
display: flex;
align-items: center;
justify-content: center;
background: linear-gradient(135deg, #e8f5e8 0%, #f1f8e9 100%);
color: #81c784;
font-size: 3rem;
`;
const CardContent = styled.div`
padding: 20px;
`;
const WorkTitle = styled.h3`
font-size: 1.3rem;
color: #2e7d32;
margin-bottom: 8px;
font-weight: 600;
`;
const WorkDescription = styled.p`
color: #666;
font-size: 0.9rem;
line-height: 1.5;
margin-bottom: 15px;
display: -webkit-box;
-webkit-line-clamp: 2;
-webkit-box-orient: vertical;
overflow: hidden;
`;
const TagsContainer = styled.div`
display: flex;
flex-wrap: wrap;
gap: 6px;
margin-bottom: 15px;
`;
const Tag = styled.span`
background: #e8f5e8;
color: #2e7d32;
padding: 4px 8px;
border-radius: 12px;
font-size: 0.75rem;
font-weight: 500;
`;
const InfoRow = styled.div`
display: flex;
justify-content: space-between;
align-items: center;
margin-bottom: 10px;
font-size: 0.85rem;
color: #666;
`;
const PlatformsContainer = styled.div`
display: flex;
gap: 8px;
margin-bottom: 10px;
`;
const Platform = styled.span`
background: #81c784;
color: white;
padding: 4px 8px;
border-radius: 8px;
font-size: 0.75rem;
font-weight: 500;
`;
const StatsContainer = styled.div`
display: flex;
justify-content: space-around;
align-items: center;
padding: 8px 0;
border-top: 1px solid #eee;
margin-top: 10px;
font-size: 0.75rem;
color: #666;
`;
const StatItem = styled.div`
display: flex;
flex-direction: column;
align-items: center;
gap: 2px;
`;
const StatIcon = styled.span`
font-size: 0.9rem;
`;
const StatValue = styled.span`
font-weight: 500;
color: #2e7d32;
`;
const ViewDetailText = styled.div`
text-align: center;
color: #81c784;
font-size: 0.85rem;
font-weight: 500;
padding: 6px 0;
border-top: 1px solid #eee;
margin-top: 8px;
`;
const WorkCard = ({ work }) => {
const navigate = useNavigate();
const formatDate = (dateString) => {
if (!dateString) return '';
return new Date(dateString).toLocaleDateString('zh-CN');
};
const getCoverImage = () => {
if (work.作品封面 && work.图片链接) {
const coverIndex = work.作品截图?.indexOf(work.作品封面);
if (coverIndex >= 0 && work.图片链接[coverIndex]) {
return `${getApiOrigin()}${work.图片链接[coverIndex]}`;
}
}
return null;
};
const handleCardClick = () => {
navigate(`/work/${work.作品ID}`);
};
return (
<Card onClick={handleCardClick}>
<ImageContainer>
{getCoverImage() ? (
<WorkImage
src={getCoverImage()}
alt={work.作品作品}
onError={(e) => {
e.target.style.display = 'none';
e.target.nextSibling.style.display = 'flex';
}}
/>
) : null}
<ImagePlaceholder style={{ display: getCoverImage() ? 'none' : 'flex' }}>
🎨
</ImagePlaceholder>
</ImageContainer>
<CardContent>
<WorkTitle>{work.作品作品}</WorkTitle>
<WorkDescription>{work.作品描述}</WorkDescription>
{work.作品标签 && work.作品标签.length > 0 && (
<TagsContainer>
{work.作品标签.slice(0, 3).map((tag, index) => (
<Tag key={index}>{tag}</Tag>
))}
{work.作品标签.length > 3 && (
<Tag>+{work.作品标签.length - 3}</Tag>
)}
</TagsContainer>
)}
<InfoRow>
<span>👨💻 作者: {work.作者}</span>
<span>🏷 v{work.作品版本号}</span>
</InfoRow>
<InfoRow>
<span>📂 分类: {work.作品分类}</span>
<span>📅 {formatDate(work.更新时间)}</span>
</InfoRow>
{work.支持平台 && work.支持平台.length > 0 && (
<PlatformsContainer>
{work.支持平台.map((platform, index) => (
<Platform key={index}>{platform}</Platform>
))}
</PlatformsContainer>
)}
<StatsContainer>
<StatItem>
<StatIcon>👀</StatIcon>
<StatValue>{work.作品浏览量 || 0}</StatValue>
</StatItem>
<StatItem>
<StatIcon>📥</StatIcon>
<StatValue>{work.作品下载量 || 0}</StatValue>
</StatItem>
<StatItem>
<StatIcon>💖</StatIcon>
<StatValue>{work.作品点赞量 || 0}</StatValue>
</StatItem>
<StatItem>
<StatIcon>🔄</StatIcon>
<StatValue>{work.作品更新次数 || 0}</StatValue>
</StatItem>
</StatsContainer>
<ViewDetailText>
🌟 点击查看详情
</ViewDetailText>
</CardContent>
</Card>
);
};
export default WorkCard;

View File

@@ -0,0 +1,872 @@
import React, { useState, useEffect } from 'react';
import { useParams, useNavigate } from 'react-router-dom';
import styled from 'styled-components';
import LoadingSpinner from './LoadingSpinner';
import { getWorkDetail, likeWork } from '../services/api';
import { getApiOrigin } from '../config/apiBase';
const DetailContainer = styled.div`
max-width: 1000px;
margin: 0 auto;
padding: 20px;
min-height: 100vh;
@media (max-width: 768px) {
padding: 10px;
}
`;
const BackButton = styled.button`
background: linear-gradient(45deg, #81c784, #66bb6a);
color: white;
border: none;
padding: 10px 20px;
border-radius: 25px;
cursor: pointer;
font-size: 14px;
margin-bottom: 20px;
transition: all 0.3s ease;
box-shadow: 0 4px 15px rgba(129, 199, 132, 0.3);
&:before {
content: '🏠 ';
}
&:hover {
background: linear-gradient(45deg, #66bb6a, #4caf50);
transform: translateY(-2px);
box-shadow: 0 6px 20px rgba(129, 199, 132, 0.4);
}
@media (max-width: 768px) {
padding: 8px 16px;
font-size: 13px;
}
`;
const WorkHeader = styled.div`
background: white;
border-radius: 15px;
padding: 30px;
margin-bottom: 20px;
box-shadow: 0 4px 20px rgba(0, 0, 0, 0.1);
@media (max-width: 768px) {
padding: 20px;
margin-bottom: 15px;
}
`;
const WorkTitle = styled.h1`
font-size: 2.2rem;
color: #2e7d32;
margin-bottom: 15px;
font-weight: 700;
@media (max-width: 768px) {
font-size: 1.8rem;
margin-bottom: 12px;
}
`;
const WorkMeta = styled.div`
display: grid;
grid-template-columns: repeat(auto-fit, minmax(200px, 1fr));
gap: 15px;
margin-bottom: 20px;
@media (max-width: 768px) {
grid-template-columns: 1fr;
gap: 10px;
}
`;
const MetaItem = styled.div`
display: flex;
align-items: center;
font-size: 0.9rem;
color: #666;
strong {
color: #2e7d32;
margin-right: 8px;
}
`;
const WorkDescription = styled.p`
font-size: 1.1rem;
line-height: 1.6;
color: #444;
margin-bottom: 20px;
@media (max-width: 768px) {
font-size: 1rem;
}
`;
const TagsContainer = styled.div`
display: flex;
flex-wrap: wrap;
gap: 8px;
margin-bottom: 20px;
`;
const Tag = styled.span`
background: #e8f5e8;
color: #2e7d32;
padding: 6px 12px;
border-radius: 15px;
font-size: 0.85rem;
font-weight: 500;
`;
const PlatformsContainer = styled.div`
display: flex;
flex-wrap: wrap;
gap: 10px;
margin-bottom: 20px;
`;
const Platform = styled.span`
background: #81c784;
color: white;
padding: 8px 16px;
border-radius: 10px;
font-size: 0.9rem;
font-weight: 500;
`;
const ContentSection = styled.div`
background: white;
border-radius: 15px;
padding: 30px;
margin-bottom: 20px;
box-shadow: 0 4px 20px rgba(0, 0, 0, 0.1);
@media (max-width: 768px) {
padding: 20px;
margin-bottom: 15px;
}
`;
const SectionTitle = styled.h2`
font-size: 1.5rem;
color: #2e7d32;
margin-bottom: 20px;
font-weight: 600;
@media (max-width: 768px) {
font-size: 1.3rem;
margin-bottom: 15px;
}
`;
const ImageGallery = styled.div`
display: grid;
grid-template-columns: repeat(auto-fit, minmax(250px, 1fr));
gap: 15px;
@media (max-width: 768px) {
grid-template-columns: 1fr;
gap: 10px;
}
`;
const WorkImage = styled.img`
width: 100%;
height: 200px;
object-fit: cover;
border-radius: 10px;
cursor: pointer;
transition: transform 0.3s ease;
&:hover {
transform: scale(1.02);
}
@media (max-width: 768px) {
height: 180px;
}
`;
const DownloadSection = styled.div`
display: grid;
grid-template-columns: repeat(auto-fit, minmax(250px, 1fr));
gap: 20px;
@media (max-width: 768px) {
grid-template-columns: 1fr;
gap: 15px;
}
`;
const PlatformDownload = styled.div`
background: #f8f9fa;
border-radius: 10px;
padding: 20px;
text-align: center;
@media (max-width: 768px) {
padding: 15px;
}
`;
const PlatformTitle = styled.h3`
font-size: 1.2rem;
color: #2e7d32;
margin-bottom: 15px;
font-weight: 600;
`;
const DownloadButton = styled.a`
display: inline-block;
background: #81c784;
color: white;
padding: 12px 24px;
border-radius: 8px;
text-decoration: none;
font-size: 1rem;
font-weight: 500;
margin: 5px;
transition: background 0.3s ease;
&:hover {
background: #66bb6a;
}
@media (max-width: 768px) {
padding: 10px 20px;
font-size: 0.9rem;
display: block;
margin: 8px 0;
}
`;
const VideoContainer = styled.div`
margin-bottom: 15px;
`;
const VideoPlayer = styled.video`
width: 100%;
max-height: 400px;
border-radius: 10px;
@media (max-width: 768px) {
max-height: 250px;
}
`;
const StatsSection = styled.div`
display: grid;
grid-template-columns: repeat(auto-fit, minmax(120px, 1fr));
gap: 15px;
margin: 20px 0;
@media (max-width: 768px) {
display: flex;
flex-direction: row;
justify-content: space-between;
flex-wrap: nowrap;
overflow-x: auto;
gap: 10px;
padding-bottom: 5px;
/* 添加滚动条样式 */
&::-webkit-scrollbar {
height: 4px;
}
&::-webkit-scrollbar-track {
background: #f1f1f1;
border-radius: 10px;
}
&::-webkit-scrollbar-thumb {
background: #81c784;
border-radius: 10px;
}
}
`;
const StatCard = styled.div`
background: #f8f9fa;
border-radius: 12px;
padding: 15px;
text-align: center;
border: 2px solid transparent;
transition: all 0.3s ease;
&:hover {
border-color: #81c784;
background: #f0f8f0;
}
@media (max-width: 768px) {
padding: 12px;
min-width: 80px;
flex: 1 0 auto;
margin-right: 2px;
}
`;
const StatIcon = styled.div`
font-size: 1.5rem;
margin-bottom: 8px;
@media (max-width: 768px) {
font-size: 1.2rem;
margin-bottom: 6px;
}
`;
const StatValue = styled.div`
font-size: 1.4rem;
font-weight: 700;
color: #2e7d32;
margin-bottom: 4px;
@media (max-width: 768px) {
font-size: 1.2rem;
}
`;
const StatLabel = styled.div`
font-size: 0.8rem;
color: #666;
@media (max-width: 768px) {
font-size: 0.75rem;
}
`;
const LikeButton = styled.button`
background: linear-gradient(
45deg,
rgba(255, 107, 107, 0.8),
rgba(255, 165, 0, 0.8),
rgba(255, 255, 0, 0.7),
rgba(50, 205, 50, 0.8),
rgba(0, 191, 255, 0.8),
rgba(65, 105, 225, 0.8),
rgba(147, 112, 219, 0.8)
);
background-size: 300% 300%;
animation: buttonRainbow 12s ease infinite;
color: white;
border: none;
border-radius: 12px;
padding: 15px;
font-size: 1rem;
cursor: pointer;
transition: all 0.3s ease;
display: flex;
align-items: center;
justify-content: center;
gap: 8px;
box-shadow: 0 4px 15px rgba(0, 0, 0, 0.2);
&:hover {
transform: translateY(-2px);
box-shadow: 0 6px 20px rgba(0, 0, 0, 0.3);
}
&:active {
transform: translateY(0);
}
&:disabled {
background: #ccc;
cursor: not-allowed;
transform: none;
animation: none;
}
@keyframes buttonRainbow {
0%, 100% {
background-position: 0% 50%;
}
50% {
background-position: 100% 50%;
}
}
@media (max-width: 768px) {
padding: 12px;
font-size: 0.9rem;
}
`;
const ErrorMessage = styled.div`
text-align: center;
padding: 40px 20px;
color: #e53e3e;
font-size: 18px;
background: white;
border-radius: 15px;
box-shadow: 0 4px 20px rgba(0, 0, 0, 0.1);
`;
// 模态框样式
const ModalOverlay = styled.div`
position: fixed;
top: 0;
left: 0;
right: 0;
bottom: 0;
background: rgba(0, 0, 0, 0.8);
display: flex;
align-items: center;
justify-content: center;
z-index: 1000;
padding: 20px;
@media (max-width: 768px) {
padding: 10px;
}
`;
const ModalContent = styled.div`
position: relative;
max-width: 90vw;
max-height: 90vh;
background: white;
border-radius: 15px;
overflow: hidden;
box-shadow: 0 10px 40px rgba(0, 0, 0, 0.3);
`;
const ModalImage = styled.img`
width: 100%;
height: auto;
max-height: 85vh;
object-fit: contain;
display: block;
`;
const ModalVideo = styled.video`
width: 100%;
height: auto;
max-height: 85vh;
display: block;
`;
const CloseButton = styled.button`
position: absolute;
top: 15px;
right: 15px;
background: rgba(0, 0, 0, 0.7);
color: white;
border: none;
border-radius: 50%;
width: 40px;
height: 40px;
font-size: 20px;
cursor: pointer;
display: flex;
align-items: center;
justify-content: center;
z-index: 1001;
transition: background 0.3s ease;
&:hover {
background: rgba(0, 0, 0, 0.9);
}
@media (max-width: 768px) {
width: 35px;
height: 35px;
font-size: 18px;
top: 10px;
right: 10px;
}
`;
const ModalTitle = styled.div`
position: absolute;
bottom: 0;
left: 0;
right: 0;
background: linear-gradient(transparent, rgba(0, 0, 0, 0.8));
color: white;
padding: 20px;
font-size: 16px;
z-index: 1001;
@media (max-width: 768px) {
padding: 15px;
font-size: 14px;
}
`;
const WorkDetail = () => {
const { workId } = useParams();
const navigate = useNavigate();
const [work, setWork] = useState(null);
const [loading, setLoading] = useState(true);
const [error, setError] = useState(null);
const [liking, setLiking] = useState(false);
const [likeMessage, setLikeMessage] = useState('');
// 模态框状态
const [modalOpen, setModalOpen] = useState(false);
const [modalType, setModalType] = useState(''); // 'image' 或 'video'
const [modalSrc, setModalSrc] = useState('');
const [modalTitle, setModalTitle] = useState('');
useEffect(() => {
loadWorkDetail();
}, [workId]);
const loadWorkDetail = async () => {
try {
setLoading(true);
setError(null);
const response = await getWorkDetail(workId);
if (response.success) {
setWork(response.data);
} else {
setError(response.message || '作品不存在');
}
} catch (error) {
console.error('加载作品详情失败:', error);
setError('加载失败,请稍后重试');
} finally {
setLoading(false);
}
};
const formatDate = (dateString) => {
if (!dateString) return '';
return new Date(dateString).toLocaleDateString('zh-CN', {
year: 'numeric',
month: 'long',
day: 'numeric'
});
};
// 打开图片模态框
const handleImageClick = (imageUrl, index) => {
setModalType('image');
setModalSrc(`${getApiOrigin()}${imageUrl}`);
setModalTitle(`${work.作品作品} - 截图 ${index + 1}`);
setModalOpen(true);
};
// 打开视频模态框
const handleVideoClick = (videoUrl, index) => {
setModalType('video');
setModalSrc(`${getApiOrigin()}${videoUrl}`);
setModalTitle(`${work.作品作品} - 视频 ${index + 1}`);
setModalOpen(true);
};
// 关闭模态框
const closeModal = () => {
setModalOpen(false);
setModalType('');
setModalSrc('');
setModalTitle('');
};
// 处理模态框背景点击
const handleModalOverlayClick = (e) => {
if (e.target === e.currentTarget) {
closeModal();
}
};
// 处理键盘事件
useEffect(() => {
const handleKeyPress = (e) => {
if (e.key === 'Escape' && modalOpen) {
closeModal();
}
};
if (modalOpen) {
document.addEventListener('keydown', handleKeyPress);
document.body.style.overflow = 'hidden'; // 防止背景滚动
}
return () => {
document.removeEventListener('keydown', handleKeyPress);
document.body.style.overflow = 'unset';
};
}, [modalOpen]);
const handleLike = async () => {
if (liking) return;
setLiking(true);
setLikeMessage('');
try {
const response = await likeWork(workId);
if (response.success) {
setLikeMessage('点赞成功!');
// 更新本地作品数据
setWork(prev => ({
...prev,
作品点赞量: response.likes
}));
} else {
setLikeMessage(response.message || '点赞失败');
}
} catch (error) {
console.error('点赞失败:', error);
if (error.response?.status === 429) {
setLikeMessage('操作太频繁,请稍后再试');
} else {
setLikeMessage('点赞失败,请稍后重试');
}
} finally {
setLiking(false);
// 3秒后清除消息
setTimeout(() => setLikeMessage(''), 3000);
}
};
if (loading) {
return <LoadingSpinner text="加载作品详情中..." />;
}
if (error) {
return (
<DetailContainer>
<BackButton onClick={() => navigate('/')}>
返回首页
</BackButton>
<ErrorMessage>{error}</ErrorMessage>
</DetailContainer>
);
}
if (!work) {
return (
<DetailContainer>
<BackButton onClick={() => navigate('/')}>
返回首页
</BackButton>
<ErrorMessage>作品不存在</ErrorMessage>
</DetailContainer>
);
}
return (
<DetailContainer>
<BackButton onClick={() => navigate('/')}>
返回首页
</BackButton>
<WorkHeader>
<WorkTitle>{work.作品作品}</WorkTitle>
<WorkMeta>
<MetaItem>
<strong>👨💻 作者:</strong> {work.}
</MetaItem>
<MetaItem>
<strong>🏷 版本:</strong> {work.}
</MetaItem>
<MetaItem>
<strong>📂 分类:</strong> {work.}
</MetaItem>
<MetaItem>
<strong>📅 上传时间:</strong> {formatDate(work.)}
</MetaItem>
<MetaItem>
<strong>🔄 更新时间:</strong> {formatDate(work.)}
</MetaItem>
</WorkMeta>
<WorkDescription>{work.作品描述}</WorkDescription>
{work.作品标签 && work.作品标签.length > 0 && (
<TagsContainer>
{work.作品标签.map((tag, index) => (
<Tag key={index}>{tag}</Tag>
))}
</TagsContainer>
)}
{work.支持平台 && work.支持平台.length > 0 && (
<PlatformsContainer>
{work.支持平台.map((platform, index) => (
<Platform key={index}>{platform}</Platform>
))}
</PlatformsContainer>
)}
{/* 统计数据 */}
<StatsSection>
<StatCard>
<StatIcon>👁🗨</StatIcon>
<StatValue>{work.作品浏览量 || 0}</StatValue>
<StatLabel>浏览量</StatLabel>
</StatCard>
<StatCard>
<StatIcon>📥</StatIcon>
<StatValue>{work.作品下载量 || 0}</StatValue>
<StatLabel>下载量</StatLabel>
</StatCard>
<StatCard>
<StatIcon>💖</StatIcon>
<StatValue>{work.作品点赞量 || 0}</StatValue>
<StatLabel>点赞量</StatLabel>
</StatCard>
<StatCard>
<StatIcon>🔄</StatIcon>
<StatValue>{work.作品更新次数 || 0}</StatValue>
<StatLabel>更新次数</StatLabel>
</StatCard>
</StatsSection>
{/* 点赞按钮 */}
<LikeButton
onClick={handleLike}
disabled={liking}
style={{
width: '100%',
marginTop: '15px',
position: 'relative'
}}
>
<span>💖</span>
{liking ? '💫 点赞中...' : '点赞作品'}
{likeMessage && (
<div style={{
position: 'absolute',
top: '-35px',
left: '50%',
transform: 'translateX(-50%)',
background: likeMessage.includes('成功') ? '#4caf50' : '#f44336',
color: 'white',
padding: '4px 8px',
borderRadius: '4px',
fontSize: '0.8rem',
whiteSpace: 'nowrap'
}}>
{likeMessage}
</div>
)}
</LikeButton>
</WorkHeader>
{work.视频链接 && work.视频链接.length > 0 && (
<ContentSection>
<SectionTitle>🎬 作品视频</SectionTitle>
{work.视频链接.map((videoUrl, index) => (
<VideoContainer key={index}>
<VideoPlayer
controls
onClick={() => handleVideoClick(videoUrl, index)}
style={{ cursor: 'pointer' }}
>
<source src={`${getApiOrigin()}${videoUrl}`} type="video/mp4" />
您的浏览器不支持视频播放
</VideoPlayer>
</VideoContainer>
))}
</ContentSection>
)}
{(work.下载资源 && Object.keys(work.下载资源).length > 0) && (
<ContentSection>
<SectionTitle>📦 下载作品</SectionTitle>
<DownloadSection>
{Object.entries(work.下载资源).map(([platform, resources]) => (
<PlatformDownload key={platform}>
<PlatformTitle>{platform}</PlatformTitle>
{resources.map((res, index) => {
const isExternal = res.类型 === 'external';
const href = isExternal ? res.链接 : `${getApiOrigin()}${res.链接}`;
return (
<DownloadButton
key={index}
href={href}
target={isExternal ? '_blank' : undefined}
rel={isExternal ? 'noreferrer' : undefined}
download={isExternal ? undefined : true}
>
📥 {res.别名 || `下载 ${platform} 版本`}
</DownloadButton>
);
})}
</PlatformDownload>
))}
</DownloadSection>
</ContentSection>
)}
{/* 兼容旧后端:仅返回“下载链接”时依旧可用 */}
{(!work.下载资源 || Object.keys(work.下载资源).length === 0) &&
work.下载链接 &&
Object.keys(work.下载链接).length > 0 && (
<ContentSection>
<SectionTitle>📦 下载作品</SectionTitle>
<DownloadSection>
{Object.entries(work.下载链接).map(([platform, links]) => (
<PlatformDownload key={platform}>
<PlatformTitle>{platform}</PlatformTitle>
{links.map((link, index) => (
<DownloadButton key={index} href={`${getApiOrigin()}${link}`} download>
📥 下载 {platform} 版本
</DownloadButton>
))}
</PlatformDownload>
))}
</DownloadSection>
</ContentSection>
)}
{work.图片链接 && work.图片链接.length > 0 && (
<ContentSection>
<SectionTitle>🖼 作品截图</SectionTitle>
<ImageGallery>
{work.图片链接.map((imageUrl, index) => (
<WorkImage
key={index}
src={`${getApiOrigin()}${imageUrl}`}
alt={`${work.作品作品} 截图 ${index + 1}`}
onClick={() => handleImageClick(imageUrl, index)}
onError={(e) => {
e.target.style.display = 'none';
}}
/>
))}
</ImageGallery>
</ContentSection>
)}
{/* 模态框 */}
{modalOpen && (
<ModalOverlay onClick={handleModalOverlayClick}>
<ModalContent>
<CloseButton onClick={closeModal}>×</CloseButton>
{modalType === 'image' ? (
<ModalImage
src={modalSrc}
alt={modalTitle}
onError={(e) => {
console.error('图片加载失败:', modalSrc);
}}
/>
) : modalType === 'video' ? (
<ModalVideo
src={modalSrc}
controls
autoPlay
onError={(e) => {
console.error('视频加载失败:', modalSrc);
}}
/>
) : null}
<ModalTitle>{modalTitle}</ModalTitle>
</ModalContent>
</ModalOverlay>
)}
</DetailContainer>
);
};
export default WorkDetail;

File diff suppressed because it is too large Load Diff

View File

@@ -0,0 +1,38 @@
const DEFAULT_PROD_API_ORIGIN = 'https://work.api.shumengya.top';
const stripTrailingSlashes = (value) => value.replace(/\/+$/, '');
const stripApiSuffix = (value) => value.replace(/\/api\/?$/, '');
const hasHttpProtocol = (value) => /^https?:\/\//i.test(value);
export const getApiBaseUrl = () => {
const envUrl = process.env.REACT_APP_API_URL;
if (envUrl) {
const normalized = stripTrailingSlashes(envUrl);
// 避免生产环境错误使用相对路径(例如 /api导致请求打到前端自身域名
if (normalized.startsWith('/')) {
if (process.env.NODE_ENV === 'production') {
// eslint-disable-next-line no-console
console.warn(
`[SproutWorkCollect] REACT_APP_API_URL=${normalized} 是相对路径,已忽略并回退到默认后端:${DEFAULT_PROD_API_ORIGIN}/api`,
);
return `${DEFAULT_PROD_API_ORIGIN}/api`;
}
return normalized.endsWith('/api') ? normalized : `${normalized}/api`;
}
const absolute = hasHttpProtocol(normalized) ? normalized : `https://${normalized}`;
return absolute.endsWith('/api') ? absolute : `${absolute}/api`;
}
if (process.env.NODE_ENV === 'production') {
return `${DEFAULT_PROD_API_ORIGIN}/api`;
}
return 'http://localhost:5000/api';
};
export const getApiOrigin = () => stripApiSuffix(getApiBaseUrl());

View File

@@ -0,0 +1,59 @@
// 网站背景图配置(前端可配,不需要改代码)。
// - 手机端用 mobileImages电脑端用 desktopImages按视口宽度 768px 区分)
// - blur.enabled 控制是否启用高斯模糊遮罩
// - blur.amount 是模糊强度,建议 4px10px
// - blur.overlayOpacity 是白色蒙层透明度0~1建议 0.20.5
const mobileImages = [
'https://image.smyhub.com/file/手机壁纸/女生/1772108123232_VJ86r.jpg',
'https://image.smyhub.com/file/手机壁纸/女生/1772108022800_f945774e0a45f7a4afdc3da2b112025f.png',
'https://image.smyhub.com/file/手机壁纸/女生/1772108024006_3f9030ba77e355869115bc90fe019d53.png',
'https://image.smyhub.com/file/手机壁纸/女生/1772108030393_159bbf61f88b38475ee9144a2e8e4956.png',
'https://image.smyhub.com/file/手机壁纸/女生/1772108021977_8020902a0c8788538eee1cd06e784c6a.png',
'https://image.smyhub.com/file/手机壁纸/女生/1772108021881_44374ab6c1daa54e0204bca48ac382f2.png',
];
const desktopImages = [
'https://image.smyhub.com/file/电脑壁纸/女生/cuSpSkq4.webp',
'https://image.smyhub.com/file/电脑壁纸/女生/5CrdoShv.webp',
'https://image.smyhub.com/file/电脑壁纸/女生/xTsVkCli.webp',
'https://image.smyhub.com/file/电脑壁纸/女生/ItOJOHST.webp',
'https://image.smyhub.com/file/电脑壁纸/女生/cUDkKiOf.webp',
'https://image.smyhub.com/file/电脑壁纸/女生/c2HxMuGK.webp',
'https://image.smyhub.com/file/电脑壁纸/女生/L0nQHehz.webp',
'https://image.smyhub.com/file/电脑壁纸/女生/hj64Cqxn.webp',
];
// 内容区块搜索框、分类块、内容卡片、顶栏和底栏的半透明背景透明度0=全透明 1=不透明,可自行修改
window.SITE_GLASS_OPACITY = 0.3;
export const getGlassOpacity = () => {
if (typeof window !== 'undefined' && typeof window.SITE_GLASS_OPACITY === 'number') {
return window.SITE_GLASS_OPACITY;
}
return 0.3;
};
export const BACKGROUND_CONFIG = {
mobileImages,
desktopImages,
blur: {
enabled: true,
amount: '6px',
overlayOpacity: 0.35,
},
};
export const pickBackgroundImage = (isMobile) => {
const list = isMobile ? BACKGROUND_CONFIG.mobileImages : BACKGROUND_CONFIG.desktopImages;
if (!Array.isArray(list) || list.length === 0) return null;
const index = Math.floor(Math.random() * list.length);
return list[index];
};
// 同时挂到 window 上,方便在控制台调试或以后用纯 script 标签引入时访问。
if (typeof window !== 'undefined') {
window.SITE_MOBILE_BACKGROUND_IMAGES = mobileImages;
window.SITE_DESKTOP_BACKGROUND_IMAGES = desktopImages;
window.SITE_BACKGROUND_BLUR = BACKGROUND_CONFIG.blur;
}

View File

@@ -0,0 +1,14 @@
import React from 'react';
import ReactDOM from 'react-dom/client';
import App from './App';
import { registerServiceWorker } from './serviceWorkerRegistration';
const root = ReactDOM.createRoot(document.getElementById('root'));
root.render(
<React.StrictMode>
<App />
</React.StrictMode>
);
// 注册自定义 Service Worker使应用具备 PWA 能力
registerServiceWorker();

View File

@@ -0,0 +1,60 @@
/* eslint-disable no-restricted-globals */
/* 简易 PWA Service Worker兼容 CRA 的 Workbox 注入机制):
* - 使用 Workbox 预缓存构建产物precacheAndRoute(self.__WB_MANIFEST)
* - 额外对首页等关键路径做手动预缓存
* - 对同源的 GET 请求走 cache-first 策略
*/
import { precacheAndRoute } from 'workbox-precaching';
// 由 react-scripts 在构建时注入实际的资源清单
precacheAndRoute(self.__WB_MANIFEST || []);
const CACHE_NAME = 'sproutworkcollect-cache-v1';
const PRECACHE_URLS = ['/', '/index.html'];
self.addEventListener('install', (event) => {
event.waitUntil(
caches.open(CACHE_NAME).then((cache) => cache.addAll(PRECACHE_URLS)),
);
self.skipWaiting();
});
self.addEventListener('activate', (event) => {
event.waitUntil(
caches.keys().then((keys) =>
Promise.all(
keys.map((key) => {
if (key !== CACHE_NAME) {
return caches.delete(key);
}
return null;
}),
),
),
);
self.clients.claim();
});
self.addEventListener('fetch', (event) => {
const { request } = event;
// 只对 GET 请求、同源请求做缓存处理,其它直接放行
if (request.method !== 'GET' || new URL(request.url).origin !== self.location.origin) {
return;
}
event.respondWith(
caches.match(request).then((cached) => {
if (cached) {
return cached;
}
return fetch(request).then((response) => {
const responseClone = response.clone();
caches.open(CACHE_NAME).then((cache) => cache.put(request, responseClone));
return response;
});
}),
);
});

View File

@@ -0,0 +1,16 @@
// 在浏览器加载完成后注册自定义 Service Worker使应用成为 PWA。
// 生产环境和开发环境都可以注册,方便本地调试。
export function registerServiceWorker() {
if ('serviceWorker' in navigator) {
window.addEventListener('load', () => {
navigator.serviceWorker
.register('/service-worker.js')
.catch((error) => {
// eslint-disable-next-line no-console
console.error('[PWA] Service Worker 注册失败:', error);
});
});
}
}

View File

@@ -0,0 +1,240 @@
import axios from 'axios';
import { getApiBaseUrl } from '../config/apiBase';
const API_BASE_URL = getApiBaseUrl();
const adminApi = axios.create({
baseURL: API_BASE_URL,
timeout: 30000,
});
adminApi.interceptors.response.use(
(response) => {
const contentType = response?.headers?.['content-type'] || '';
if (typeof response.data === 'string') {
const trimmed = response.data.trim().toLowerCase();
const looksLikeHtml =
contentType.includes('text/html') ||
trimmed.startsWith('<!doctype') ||
trimmed.startsWith('<html');
if (looksLikeHtml) {
throw new Error(
`API 返回了 HTML疑似请求打到了前端自身域名/SPA重写请检查 Cloudflare Pages 环境变量 REACT_APP_API_URL。当前 baseURL: ${API_BASE_URL}`
);
}
}
return response;
},
(error) => Promise.reject(error)
);
// 管理员token
let adminToken = null;
export const setAdminToken = (token) => {
adminToken = token;
adminApi.defaults.headers.common['Authorization'] = token;
};
export const getAdminToken = () => adminToken;
// 管理员获取所有作品
export const adminGetWorks = async () => {
const response = await adminApi.get('/admin/works', {
params: { token: adminToken }
});
return response.data;
};
// 管理员创建作品
export const adminCreateWork = async (workData) => {
const response = await adminApi.post('/admin/works', workData, {
params: { token: adminToken }
});
return response.data;
};
// 管理员更新作品
export const adminUpdateWork = async (workId, workData) => {
const response = await adminApi.put(`/admin/works/${workId}`, workData, {
params: { token: adminToken }
});
return response.data;
};
// 管理员删除作品
export const adminDeleteWork = async (workId) => {
const response = await adminApi.delete(`/admin/works/${workId}`, {
params: { token: adminToken }
});
return response.data;
};
// 管理员上传文件 (支持大文件和详细进度回调,增强错误处理和重试机制)
export const adminUploadFile = async (workId, fileType, file, platform = null, onProgress = null, maxRetries = 3) => {
// 检查文件大小 (前端预检查)
const maxSize = 5000 * 1024 * 1024; // 5000MB
if (file.size > maxSize) {
throw new Error(`文件太大,最大支持 ${maxSize / (1024 * 1024)}MB当前文件大小${(file.size / (1024 * 1024)).toFixed(1)}MB`);
}
console.log(`开始上传文件: ${file.name}, 大小: ${(file.size / (1024 * 1024)).toFixed(1)}MB, 作品ID: ${workId}, 类型: ${fileType}, 平台: ${platform}`);
const formData = new FormData();
formData.append('file', file);
if (platform) {
formData.append('platform', platform);
}
let startTime = Date.now();
let lastLoaded = 0;
let lastTime = startTime;
let retryCount = 0;
// 根据文件大小动态调整超时时间
const getTimeoutForFileSize = (fileSize) => {
const fileSizeMB = fileSize / (1024 * 1024);
if (fileSizeMB < 10) return 5 * 60 * 1000; // 小于10MB: 5分钟
if (fileSizeMB < 100) return 15 * 60 * 1000; // 小于100MB: 15分钟
if (fileSizeMB < 500) return 30 * 60 * 1000; // 小于500MB: 30分钟
return 60 * 60 * 1000; // 大于500MB: 60分钟
};
const uploadAttempt = async () => {
try {
console.log(`上传尝试 ${retryCount + 1}/${maxRetries + 1}`);
const timeout = getTimeoutForFileSize(file.size);
console.log(`设置超时时间: ${timeout / 1000}`);
const response = await adminApi.post(`/admin/upload/${workId}/${fileType}`, formData, {
params: { token: adminToken },
headers: {
'Content-Type': 'multipart/form-data',
},
timeout: timeout,
onUploadProgress: (progressEvent) => {
if (onProgress && progressEvent.total) {
const currentTime = Date.now();
const currentLoaded = progressEvent.loaded;
// 计算上传速度
const timeDiff = (currentTime - lastTime) / 1000;
const loadedDiff = currentLoaded - lastLoaded;
const speed = timeDiff > 0 ? loadedDiff / timeDiff : 0;
const percentCompleted = Math.round((currentLoaded * 100) / progressEvent.total);
// 计算剩余时间
const remainingBytes = progressEvent.total - currentLoaded;
const eta = speed > 0 ? Math.round(remainingBytes / speed) : 0;
onProgress({
progress: percentCompleted,
uploaded: currentLoaded,
total: progressEvent.total,
speed: speed,
fileName: file.name,
fileSize: file.size,
eta: eta,
retryCount: retryCount
});
lastLoaded = currentLoaded;
lastTime = currentTime;
}
},
});
console.log(`文件上传成功: ${file.name}`);
return response.data;
} catch (error) {
console.error(`上传尝试 ${retryCount + 1} 失败:`, error);
// 分析错误类型
const isRetryableError = (error) => {
if (!error.response) {
// 网络错误或超时,可重试
return true;
}
const status = error.response.status;
// 5xx服务器错误可重试4xx客户端错误通常不可重试
if (status >= 500) return true;
if (status === 408 || status === 429) return true; // 超时或限流可重试
return false;
};
const errorMessage = error.response?.data?.message || error.message || '未知错误';
// 如果是可重试的错误且还有重试次数
if (isRetryableError(error) && retryCount < maxRetries) {
retryCount++;
const delayMs = Math.min(1000 * Math.pow(2, retryCount - 1), 10000); // 指数退避最大10秒
console.log(`${delayMs}ms后进行第${retryCount}次重试...`);
// 通知前端正在重试
if (onProgress) {
onProgress({
progress: 0,
uploaded: 0,
total: file.size,
speed: 0,
fileName: file.name,
fileSize: file.size,
eta: 0,
retryCount: retryCount,
status: 'retrying',
error: `上传失败,${delayMs/1000}秒后重试: ${errorMessage}`
});
}
await new Promise(resolve => setTimeout(resolve, delayMs));
return uploadAttempt(); // 递归重试
}
// 不可重试或重试次数用完
console.error(`文件上传最终失败: ${file.name}, 错误: ${errorMessage}`);
// 增强错误信息
let enhancedError = new Error(errorMessage);
enhancedError.originalError = error;
enhancedError.retryCount = retryCount;
enhancedError.fileName = file.name;
enhancedError.fileSize = file.size;
// 根据错误类型提供更好的用户提示
if (error.code === 'ECONNABORTED' || errorMessage.includes('timeout')) {
enhancedError.message = `文件上传超时,请检查网络连接或尝试上传更小的文件。文件: ${file.name}`;
} else if (error.response?.status === 413) {
enhancedError.message = `文件太大无法上传: ${file.name} (${(file.size / (1024 * 1024)).toFixed(1)}MB)`;
} else if (error.response?.status >= 500) {
enhancedError.message = `服务器错误,请稍后重试。文件: ${file.name}`;
}
throw enhancedError;
}
};
return uploadAttempt();
};
// 管理员删除文件
export const adminDeleteFile = async (workId, fileType, filename, platform = null) => {
const params = { token: adminToken };
if (platform) {
params.platform = platform;
}
const response = await adminApi.delete(`/admin/delete-file/${workId}/${fileType}/${filename}`, {
params
});
return response.data;
};
export default adminApi;

View File

@@ -0,0 +1,73 @@
import axios from 'axios';
import { getApiBaseUrl } from '../config/apiBase';
const API_BASE_URL = getApiBaseUrl();
const api = axios.create({
baseURL: API_BASE_URL,
timeout: 10000,
});
api.interceptors.response.use(
(response) => {
const contentType = response?.headers?.['content-type'] || '';
if (typeof response.data === 'string') {
const trimmed = response.data.trim().toLowerCase();
const looksLikeHtml =
contentType.includes('text/html') ||
trimmed.startsWith('<!doctype') ||
trimmed.startsWith('<html');
if (looksLikeHtml) {
throw new Error(
`API 返回了 HTML疑似请求打到了前端自身域名/SPA重写请检查 Cloudflare Pages 环境变量 REACT_APP_API_URL。当前 baseURL: ${API_BASE_URL}`
);
}
}
return response;
},
(error) => Promise.reject(error)
);
// 获取网站设置
export const getSettings = async () => {
const response = await api.get('/settings');
return response.data;
};
// 获取所有作品
export const getWorks = async () => {
const response = await api.get('/works');
return response.data;
};
// 获取单个作品详情
export const getWorkDetail = async (workId) => {
const response = await api.get(`/works/${workId}`);
return response.data;
};
// 搜索作品
export const searchWorks = async (query = '', category = '') => {
const params = new URLSearchParams();
if (query) params.append('q', query);
if (category) params.append('category', category);
const response = await api.get(`/search?${params.toString()}`);
return response.data;
};
// 获取所有分类
export const getCategories = async () => {
const response = await api.get('/categories');
return response.data;
};
// 点赞作品
export const likeWork = async (workId) => {
const response = await api.post(`/like/${workId}`);
return response.data;
};
export default api;