a
This commit is contained in:
@@ -0,0 +1,177 @@
|
||||
import { BrowserRouter, Routes, Route, Navigate } from 'react-router-dom'
|
||||
import { useState, useEffect } from 'react'
|
||||
import { Home } from './pages/Home'
|
||||
import { PostDetail } from './pages/PostDetail'
|
||||
import { Login } from './pages/Login'
|
||||
import { Dashboard } from './pages/Dashboard'
|
||||
import { Posts } from './pages/Posts'
|
||||
import { PostEdit } from './pages/PostEdit'
|
||||
import { CrawlEdit } from './pages/CrawlEdit'
|
||||
import { WechatCrawlEdit } from './pages/WechatCrawlEdit'
|
||||
import { UniversalCrawlEdit } from './pages/UniversalCrawlEdit'
|
||||
import { Images } from './pages/admin/Images'
|
||||
import { Settings } from './pages/admin/Settings'
|
||||
import { Categories } from './pages/admin/Categories'
|
||||
import { NanobotChat } from './pages/admin/NanobotChat'
|
||||
import { authApi } from './api/auth'
|
||||
|
||||
// 路由守卫 - 需要登录才能访问(支持本地 Token + SSO Cookie 双模式)
|
||||
function PrivateRoute({ children }) {
|
||||
const [authState, setAuthState] = useState('checking') // checking / ok / redirect
|
||||
|
||||
useEffect(() => {
|
||||
// 本地 token 优先
|
||||
const token = localStorage.getItem('token')
|
||||
if (token) {
|
||||
setAuthState('ok')
|
||||
return
|
||||
}
|
||||
// 无本地 token 时,尝试用 SSO Cookie 调用后端
|
||||
authApi.getMe()
|
||||
.then(() => setAuthState('ok'))
|
||||
.catch(() => setAuthState('redirect'))
|
||||
}, [])
|
||||
|
||||
if (authState === 'checking') {
|
||||
return (
|
||||
<div className="min-h-screen flex items-center justify-center">
|
||||
<div className="text-gray-500">加载中...</div>
|
||||
</div>
|
||||
)
|
||||
}
|
||||
if (authState === 'ok') {
|
||||
return children
|
||||
}
|
||||
return <Navigate to="/login" />
|
||||
}
|
||||
|
||||
function App() {
|
||||
return (
|
||||
<BrowserRouter>
|
||||
<Routes>
|
||||
{/* === 访客公开路由 === */}
|
||||
<Route path="/" element={<Home />} />
|
||||
<Route path="/post/:slug" element={<PostDetail />} />
|
||||
|
||||
{/* === 登录路由 === */}
|
||||
<Route path="/login" element={<Login />} />
|
||||
|
||||
{/* === 管理后台路由(需要登录)=== */}
|
||||
<Route
|
||||
path="/admin"
|
||||
element={
|
||||
<PrivateRoute>
|
||||
<Dashboard />
|
||||
</PrivateRoute>
|
||||
}
|
||||
/>
|
||||
<Route
|
||||
path="/admin/posts"
|
||||
element={
|
||||
<PrivateRoute>
|
||||
<Posts />
|
||||
</PrivateRoute>
|
||||
}
|
||||
/>
|
||||
<Route
|
||||
path="/admin/posts/new"
|
||||
element={
|
||||
<PrivateRoute>
|
||||
<PostEdit />
|
||||
</PrivateRoute>
|
||||
}
|
||||
/>
|
||||
<Route
|
||||
path="/admin/posts/edit/:id"
|
||||
element={
|
||||
<PrivateRoute>
|
||||
<PostEdit />
|
||||
</PrivateRoute>
|
||||
}
|
||||
/>
|
||||
{/* 文章采集 */}
|
||||
<Route
|
||||
path="/admin/crawl"
|
||||
element={
|
||||
<PrivateRoute>
|
||||
<CrawlEdit />
|
||||
</PrivateRoute>
|
||||
}
|
||||
/>
|
||||
{/* 公众号采集 */}
|
||||
<Route
|
||||
path="/admin/wechat-crawl"
|
||||
element={
|
||||
<PrivateRoute>
|
||||
<WechatCrawlEdit />
|
||||
</PrivateRoute>
|
||||
}
|
||||
/>
|
||||
{/* 通用采集 */}
|
||||
<Route
|
||||
path="/admin/universal-crawl"
|
||||
element={
|
||||
<PrivateRoute>
|
||||
<UniversalCrawlEdit />
|
||||
</PrivateRoute>
|
||||
}
|
||||
/>
|
||||
{/* 分类管理 */}
|
||||
<Route
|
||||
path="/admin/categories"
|
||||
element={
|
||||
<PrivateRoute>
|
||||
<Categories />
|
||||
</PrivateRoute>
|
||||
}
|
||||
/>
|
||||
<Route
|
||||
path="/admin/tags"
|
||||
element={
|
||||
<PrivateRoute>
|
||||
<div className="p-8">标签管理(开发中)</div>
|
||||
</PrivateRoute>
|
||||
}
|
||||
/>
|
||||
<Route
|
||||
path="/admin/images"
|
||||
element={
|
||||
<PrivateRoute>
|
||||
<Images />
|
||||
</PrivateRoute>
|
||||
}
|
||||
/>
|
||||
<Route
|
||||
path="/admin/pages"
|
||||
element={
|
||||
<PrivateRoute>
|
||||
<div className="p-8">页面管理(开发中)</div>
|
||||
</PrivateRoute>
|
||||
}
|
||||
/>
|
||||
<Route
|
||||
path="/admin/nanobot"
|
||||
element={
|
||||
<PrivateRoute>
|
||||
<NanobotChat />
|
||||
</PrivateRoute>
|
||||
}
|
||||
/>
|
||||
<Route
|
||||
path="/admin/settings"
|
||||
element={
|
||||
<PrivateRoute>
|
||||
<Settings />
|
||||
</PrivateRoute>
|
||||
}
|
||||
/>
|
||||
{/* 旧路由兼容(重定向到新路由) */}
|
||||
<Route path="/posts" element={<Navigate to="/admin/posts" />} />
|
||||
<Route path="/posts/new" element={<Navigate to="/admin/posts/new" />} />
|
||||
<Route path="/posts/edit/:id" element={<Navigate to="/admin/posts/edit/:id" />} />
|
||||
</Routes>
|
||||
</BrowserRouter>
|
||||
)
|
||||
}
|
||||
|
||||
export default App
|
||||
@@ -0,0 +1,27 @@
|
||||
// 认证相关 API
|
||||
import api from './config'
|
||||
|
||||
export const authApi = {
|
||||
// 登录
|
||||
login: (username, password) => {
|
||||
return api.post('/auth/login', { username, password })
|
||||
},
|
||||
|
||||
// 退出登录(同时清除后端 SSO Cookie)
|
||||
logout: () => {
|
||||
return api.post('/auth/logout')
|
||||
},
|
||||
|
||||
// 获取当前用户
|
||||
getMe: () => {
|
||||
return api.get('/auth/me')
|
||||
},
|
||||
|
||||
// 修改密码
|
||||
changePassword: (oldPassword, newPassword) => {
|
||||
return api.post('/auth/change-password', {
|
||||
old_password: oldPassword,
|
||||
new_password: newPassword
|
||||
})
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,9 @@
|
||||
// 分类相关 API
|
||||
import api from './config'
|
||||
|
||||
export const categoriesApi = {
|
||||
getCategories: () => api.get('/categories'),
|
||||
createCategory: (data) => api.post('/categories', data),
|
||||
updateCategory: (id, data) => api.put(`/categories/${id}`, data),
|
||||
deleteCategory: (id) => api.delete(`/categories/${id}`)
|
||||
}
|
||||
@@ -0,0 +1,43 @@
|
||||
import axios from 'axios'
|
||||
|
||||
// API基础配置 - 使用绝对URL确保跨域访问
|
||||
// 强制使用后端端口 8889
|
||||
export const API_BASE_URL = 'http://129.211.173.87:8889/api'
|
||||
|
||||
const api = axios.create({
|
||||
baseURL: API_BASE_URL,
|
||||
headers: {
|
||||
'Content-Type': 'application/json'
|
||||
},
|
||||
timeout: 10000,
|
||||
withCredentials: true, // 允许跨域携带 Cookie(SSO 必需)
|
||||
})
|
||||
|
||||
// 请求拦截器 - 添加Token
|
||||
api.interceptors.request.use(
|
||||
(config) => {
|
||||
const token = localStorage.getItem('token')
|
||||
if (token) {
|
||||
config.headers.Authorization = `Bearer ${token}`
|
||||
}
|
||||
return config
|
||||
},
|
||||
(error) => Promise.reject(error)
|
||||
)
|
||||
|
||||
// 响应拦截器 - 处理错误
|
||||
api.interceptors.response.use(
|
||||
(response) => response,
|
||||
(error) => {
|
||||
if (error.response?.status === 401) {
|
||||
localStorage.removeItem('token')
|
||||
// 避免在登录页本身触发跳转导致死循环刷新
|
||||
if (window.location.pathname !== '/login') {
|
||||
window.location.href = '/login'
|
||||
}
|
||||
}
|
||||
return Promise.reject(error)
|
||||
}
|
||||
)
|
||||
|
||||
export default api
|
||||
@@ -0,0 +1,34 @@
|
||||
// 文章相关 API
|
||||
import api from './config'
|
||||
|
||||
export const postsApi = {
|
||||
// 获取文章列表
|
||||
getPosts: (params = {}) => {
|
||||
return api.get('/posts', { params })
|
||||
},
|
||||
|
||||
// 获取单篇文章
|
||||
getPost: (id) => {
|
||||
return api.get(`/posts/${id}`)
|
||||
},
|
||||
|
||||
// 创建文章
|
||||
createPost: (data) => {
|
||||
return api.post('/posts', data)
|
||||
},
|
||||
|
||||
// 更新文章
|
||||
updatePost: (id, data) => {
|
||||
return api.put(`/posts/${id}`, data)
|
||||
},
|
||||
|
||||
// 删除文章
|
||||
deletePost: (id) => {
|
||||
return api.delete(`/posts/${id}`)
|
||||
},
|
||||
|
||||
// 获取统计
|
||||
getStats: () => {
|
||||
return api.get('/posts/stats/overview')
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,29 @@
|
||||
import api from './config'
|
||||
|
||||
/**
|
||||
* 获取博客设置(需要登录)
|
||||
*/
|
||||
export async function getSettings() {
|
||||
const res = await api.get('/settings')
|
||||
return res.data
|
||||
}
|
||||
|
||||
/**
|
||||
* 更新博客设置(需要登录)
|
||||
*/
|
||||
export async function updateSettings(data) {
|
||||
const res = await api.put('/settings', data)
|
||||
return res.data
|
||||
}
|
||||
|
||||
/**
|
||||
* 公开获取博客设置(无需登录,用于主题预加载)
|
||||
*/
|
||||
export async function getPublicSettings() {
|
||||
const res = await fetch(`${api.defaults.baseURL}/settings/public`, {
|
||||
method: 'GET',
|
||||
headers: { 'Content-Type': 'application/json' },
|
||||
})
|
||||
if (!res.ok) throw new Error('获取公开设置失败')
|
||||
return res.json()
|
||||
}
|
||||
@@ -0,0 +1,8 @@
|
||||
// 标签相关 API
|
||||
import api from './config'
|
||||
|
||||
export const tagsApi = {
|
||||
getTags: () => api.get('/tags/'),
|
||||
createTag: (data) => api.post('/tags/', data),
|
||||
deleteTag: (id) => api.delete(`/tags/${id}`)
|
||||
}
|
||||
@@ -0,0 +1,68 @@
|
||||
// Preline UI 风格按钮组件
|
||||
import React from 'react';
|
||||
|
||||
/**
|
||||
* Preline 风格按钮
|
||||
* @param {string} variant - 'primary' | 'secondary' | 'danger' | 'ghost'
|
||||
* @param {string} size - 'sm' | 'md' | 'lg'
|
||||
* @param {boolean} disabled - 是否禁用
|
||||
* @param {boolean} loading - 是否加载中
|
||||
* @param {React.ReactNode} children - 子元素
|
||||
* @param {function} onClick - 点击事件
|
||||
* @param {string} type - 按钮类型
|
||||
* @param {string} className - 额外类名
|
||||
*/
|
||||
export function Button({
|
||||
variant = 'primary',
|
||||
size = 'md',
|
||||
disabled = false,
|
||||
loading = false,
|
||||
children,
|
||||
onClick,
|
||||
type = 'button',
|
||||
className = '',
|
||||
...props
|
||||
}) {
|
||||
const baseClasses = 'inline-flex items-center justify-center gap-2 font-medium transition-all duration-200 focus:outline-none focus:ring-2 focus:ring-offset-2';
|
||||
|
||||
const variantClasses = {
|
||||
primary: 'text-white bg-preline-primary hover:bg-preline-primary-hover focus:ring-preline-primary disabled:opacity-50',
|
||||
secondary: 'bg-preline-card text-preline-gray-700 border border-preline-gray-300 hover:bg-preline-gray-50 focus:ring-preline-primary disabled:bg-preline-gray-100 disabled:text-preline-gray-400',
|
||||
danger: 'bg-preline-danger text-white hover:bg-preline-danger-hover focus:ring-preline-danger disabled:opacity-50',
|
||||
ghost: 'bg-transparent text-preline-gray-600 hover:bg-preline-gray-100 focus:ring-preline-primary disabled:text-preline-gray-400',
|
||||
};
|
||||
|
||||
const sizeClasses = {
|
||||
sm: 'px-3 py-1.5 text-xs rounded-md',
|
||||
md: 'px-4 py-2.5 text-sm rounded-lg',
|
||||
lg: 'px-6 py-3 text-base rounded-lg',
|
||||
};
|
||||
|
||||
const classes = [
|
||||
baseClasses,
|
||||
variantClasses[variant],
|
||||
sizeClasses[size],
|
||||
(disabled || loading) && 'cursor-not-allowed opacity-70',
|
||||
className,
|
||||
].filter(Boolean).join(' ');
|
||||
|
||||
return (
|
||||
<button
|
||||
type={type}
|
||||
className={classes}
|
||||
onClick={onClick}
|
||||
disabled={disabled || loading}
|
||||
{...props}
|
||||
>
|
||||
{loading && (
|
||||
<svg className="animate-spin h-4 w-4" viewBox="0 0 24 24" fill="none">
|
||||
<circle className="opacity-25" cx="12" cy="12" r="10" stroke="currentColor" strokeWidth="4" />
|
||||
<path className="opacity-75" fill="currentColor" d="M4 12a8 8 0 018-8V0C5.373 0 0 5.373 0 12h4z" />
|
||||
</svg>
|
||||
)}
|
||||
{children}
|
||||
</button>
|
||||
);
|
||||
}
|
||||
|
||||
export default Button;
|
||||
@@ -0,0 +1,87 @@
|
||||
// Preline UI 风格卡片组件
|
||||
import React from 'react';
|
||||
|
||||
/**
|
||||
* Preline 风格卡片容器
|
||||
*/
|
||||
export function Card({ children, className = '', ...props }) {
|
||||
return (
|
||||
<div
|
||||
className={`bg-preline-card rounded-xl border border-preline-border shadow-sm ${className}`}
|
||||
{...props}
|
||||
>
|
||||
{children}
|
||||
</div>
|
||||
);
|
||||
}
|
||||
|
||||
/**
|
||||
* 卡片头部
|
||||
*/
|
||||
export function CardHeader({ children, className = '', action, ...props }) {
|
||||
return (
|
||||
<div
|
||||
className={`px-6 py-4 border-b border-preline-border flex items-center justify-between ${className}`}
|
||||
{...props}
|
||||
>
|
||||
<div className="flex-1">{children}</div>
|
||||
{action && <div className="ml-4">{action}</div>}
|
||||
</div>
|
||||
);
|
||||
}
|
||||
|
||||
/**
|
||||
* 卡片标题
|
||||
*/
|
||||
export function CardTitle({ children, className = '' }) {
|
||||
return (
|
||||
<h3 className={`text-lg font-semibold text-preline-text ${className}`}>
|
||||
{children}
|
||||
</h3>
|
||||
);
|
||||
}
|
||||
|
||||
/**
|
||||
* 卡片描述
|
||||
*/
|
||||
export function CardDescription({ children, className = '' }) {
|
||||
return (
|
||||
<p className={`text-sm text-preline-text-secondary mt-1 ${className}`}>
|
||||
{children}
|
||||
</p>
|
||||
);
|
||||
}
|
||||
|
||||
/**
|
||||
* 卡片内容
|
||||
*/
|
||||
export function CardBody({ children, className = '', ...props }) {
|
||||
return (
|
||||
<div className={`px-6 py-4 ${className}`} {...props}>
|
||||
{children}
|
||||
</div>
|
||||
);
|
||||
}
|
||||
|
||||
/**
|
||||
* 卡片底部
|
||||
*/
|
||||
export function CardFooter({ children, className = '', ...props }) {
|
||||
return (
|
||||
<div
|
||||
className={`px-6 py-4 border-t border-preline-border flex items-center justify-end gap-3 ${className}`}
|
||||
{...props}
|
||||
>
|
||||
{children}
|
||||
</div>
|
||||
);
|
||||
}
|
||||
|
||||
// 默认导出完整卡片组件
|
||||
Card.Header = CardHeader;
|
||||
Card.Title = CardTitle;
|
||||
Card.Description = CardDescription;
|
||||
Card.Body = CardBody;
|
||||
Card.Footer = CardFooter;
|
||||
|
||||
export default Card;
|
||||
@@ -0,0 +1,173 @@
|
||||
// Preline UI 风格输入框组件
|
||||
import React from 'react';
|
||||
|
||||
/**
|
||||
* 表单标签
|
||||
*/
|
||||
export function Label({ children, htmlFor, className = '', required = false }) {
|
||||
return (
|
||||
<label
|
||||
htmlFor={htmlFor}
|
||||
className={`block text-sm font-medium text-preline-gray-700 mb-1.5 ${className}`}
|
||||
>
|
||||
{children}
|
||||
{required && <span className="text-preline-danger ml-0.5">*</span>}
|
||||
</label>
|
||||
);
|
||||
}
|
||||
|
||||
/**
|
||||
* Preline 风格输入框
|
||||
*/
|
||||
export function Input({
|
||||
type = 'text',
|
||||
placeholder,
|
||||
value,
|
||||
onChange,
|
||||
onBlur,
|
||||
onFocus,
|
||||
disabled = false,
|
||||
readOnly = false,
|
||||
required = false,
|
||||
error,
|
||||
className = '',
|
||||
id,
|
||||
name,
|
||||
autoComplete,
|
||||
...props
|
||||
}) {
|
||||
const baseClasses = 'w-full px-4 py-2.5 rounded-lg border bg-preline-card text-preline-text placeholder:text-preline-gray-400 transition-all duration-200 focus:outline-none focus:ring-2';
|
||||
|
||||
const stateClasses = error
|
||||
? 'border-preline-danger-border focus:border-preline-danger focus:ring-preline-danger/20'
|
||||
: 'border-preline-gray-300 focus:border-preline-primary-500 focus:ring-preline-primary-500/20';
|
||||
|
||||
const disabledClasses = disabled ? 'bg-preline-gray-100 cursor-not-allowed opacity-70' : '';
|
||||
|
||||
return (
|
||||
<input
|
||||
type={type}
|
||||
id={id}
|
||||
name={name}
|
||||
value={value}
|
||||
onChange={onChange}
|
||||
onBlur={onBlur}
|
||||
onFocus={onFocus}
|
||||
placeholder={placeholder}
|
||||
disabled={disabled}
|
||||
readOnly={readOnly}
|
||||
required={required}
|
||||
autoComplete={autoComplete}
|
||||
className={`${baseClasses} ${stateClasses} ${disabledClasses} ${className}`}
|
||||
{...props}
|
||||
/>
|
||||
);
|
||||
}
|
||||
|
||||
/**
|
||||
* Preline 风格文本域
|
||||
*/
|
||||
export function Textarea({
|
||||
placeholder,
|
||||
value,
|
||||
onChange,
|
||||
onBlur,
|
||||
disabled = false,
|
||||
readOnly = false,
|
||||
required = false,
|
||||
error,
|
||||
rows = 4,
|
||||
className = '',
|
||||
id,
|
||||
name,
|
||||
...props
|
||||
}) {
|
||||
const baseClasses = 'w-full px-4 py-2.5 rounded-lg border bg-preline-card text-preline-text placeholder:text-preline-gray-400 transition-all duration-200 focus:outline-none focus:ring-2 resize-y';
|
||||
|
||||
const stateClasses = error
|
||||
? 'border-preline-danger-border focus:border-preline-danger focus:ring-preline-danger/20'
|
||||
: 'border-preline-gray-300 focus:border-preline-primary-500 focus:ring-preline-primary-500/20';
|
||||
|
||||
const disabledClasses = disabled ? 'bg-preline-gray-100 cursor-not-allowed opacity-70' : '';
|
||||
|
||||
return (
|
||||
<textarea
|
||||
id={id}
|
||||
name={name}
|
||||
value={value}
|
||||
onChange={onChange}
|
||||
onBlur={onBlur}
|
||||
placeholder={placeholder}
|
||||
disabled={disabled}
|
||||
readOnly={readOnly}
|
||||
required={required}
|
||||
rows={rows}
|
||||
className={`${baseClasses} ${stateClasses} ${disabledClasses} ${className}`}
|
||||
{...props}
|
||||
/>
|
||||
);
|
||||
}
|
||||
|
||||
/**
|
||||
* Preline 风格选择框
|
||||
*/
|
||||
export function Select({
|
||||
value,
|
||||
onChange,
|
||||
disabled = false,
|
||||
required = false,
|
||||
error,
|
||||
className = '',
|
||||
id,
|
||||
name,
|
||||
children,
|
||||
...props
|
||||
}) {
|
||||
const baseClasses = 'w-full px-4 py-2.5 rounded-lg border bg-preline-card text-preline-text transition-all duration-200 focus:outline-none focus:ring-2 appearance-none bg-[url("data:image/svg+xml;charset=utf-8,%3Csvg%20xmlns%3D%22http%3A%2F%2Fwww.w3.org%2F2000%2Fsvg%22%20viewBox%3D%220%200%2020%2020%22%20fill%3D%22%236B7280%22%3E%3Cpath%20fill-rule%3D%22evenodd%22%20d%3D%22M5.293%207.293a1%201%200%20011.414%200L10%2010.586l3.293-3.293a1%201%200%20111.414%201.414l-4%204a1%201%200%2001-1.414%200l-4-4a1%201%200%20010-1.414z%22%20clip-rule%3D%22evenodd%22%2F%3E%3C%2Fsvg%3E")] bg-[length:1.5em_1.5em] bg-[right_0.5rem_center] bg-no-repeat pr-10';
|
||||
|
||||
const stateClasses = error
|
||||
? 'border-preline-danger-border focus:border-preline-danger focus:ring-preline-danger/20'
|
||||
: 'border-preline-gray-300 focus:border-preline-primary-500 focus:ring-preline-primary-500/20';
|
||||
|
||||
const disabledClasses = disabled ? 'bg-preline-gray-100 cursor-not-allowed opacity-70' : '';
|
||||
|
||||
return (
|
||||
<select
|
||||
id={id}
|
||||
name={name}
|
||||
value={value}
|
||||
onChange={onChange}
|
||||
disabled={disabled}
|
||||
required={required}
|
||||
className={`${baseClasses} ${stateClasses} ${disabledClasses} ${className}`}
|
||||
{...props}
|
||||
>
|
||||
{children}
|
||||
</select>
|
||||
);
|
||||
}
|
||||
|
||||
/**
|
||||
* 表单错误提示
|
||||
*/
|
||||
export function FormError({ children }) {
|
||||
if (!children) return null;
|
||||
return (
|
||||
<p className="mt-1.5 text-sm text-preline-danger">
|
||||
{children}
|
||||
</p>
|
||||
);
|
||||
}
|
||||
|
||||
/**
|
||||
* 表单帮助文本
|
||||
*/
|
||||
export function FormHelp({ children }) {
|
||||
return (
|
||||
<p className="mt-1.5 text-sm text-preline-text-secondary">
|
||||
{children}
|
||||
</p>
|
||||
);
|
||||
}
|
||||
|
||||
export default Input;
|
||||
@@ -0,0 +1,163 @@
|
||||
// Preline UI 风格侧边栏组件
|
||||
import React from 'react';
|
||||
import { NavLink } from 'react-router-dom';
|
||||
|
||||
// 导航项目配置
|
||||
const navItems = [
|
||||
{ path: '/admin', label: '仪表盘', icon: HomeIcon },
|
||||
{ path: '/admin/posts', label: '文章管理', icon: DocumentIcon },
|
||||
{ path: '/admin/categories', label: '分类管理', icon: FolderIcon },
|
||||
{ path: '/admin/images', label: '图片管理', icon: ImageIcon },
|
||||
{ path: '/admin/nanobot', label: 'Nanobot 助手', icon: ChatIcon },
|
||||
{ path: '/admin/settings', label: '系统设置', icon: CogIcon },
|
||||
];
|
||||
|
||||
/**
|
||||
* Preline 风格侧边栏
|
||||
*/
|
||||
export function Sidebar({ user, onLogout }) {
|
||||
return (
|
||||
<aside
|
||||
className="w-64 min-h-screen fixed left-0 top-0 z-40 flex flex-col"
|
||||
style={{ backgroundColor: 'var(--color-sidebar)' }}
|
||||
>
|
||||
{/* Logo */}
|
||||
<div className="h-16 flex items-center px-6 border-b border-white/10">
|
||||
<NavLink to="/admin" className="flex items-center gap-2">
|
||||
<div
|
||||
className="w-8 h-8 rounded-lg flex items-center justify-center"
|
||||
style={{ backgroundColor: 'var(--color-primary)' }}
|
||||
>
|
||||
<span className="text-white font-bold text-sm">B</span>
|
||||
</div>
|
||||
<span className="text-white font-semibold text-lg">Blog Admin</span>
|
||||
</NavLink>
|
||||
</div>
|
||||
|
||||
{/* 导航 */}
|
||||
<nav className="flex-1 mt-6 px-3 space-y-1 overflow-y-auto">
|
||||
{navItems.map((item) => (
|
||||
<NavLink
|
||||
key={item.path}
|
||||
to={item.path}
|
||||
className={({ isActive }) => `
|
||||
flex items-center gap-3 px-3 py-2.5 rounded-lg transition-colors duration-200
|
||||
${isActive
|
||||
? 'text-white font-medium'
|
||||
: 'text-gray-400 hover:text-white'
|
||||
}
|
||||
`}
|
||||
style={({ isActive }) => ({
|
||||
backgroundColor: isActive ? 'var(--color-sidebar-active)' : undefined,
|
||||
})}
|
||||
>
|
||||
<item.icon className="w-5 h-5 flex-shrink-0" />
|
||||
<span className="text-sm">{item.label}</span>
|
||||
</NavLink>
|
||||
))}
|
||||
</nav>
|
||||
|
||||
{/* 底部用户信息 */}
|
||||
<div className="p-4 border-t border-white/10">
|
||||
<div className="flex items-center gap-3">
|
||||
<div className="w-9 h-9 rounded-full bg-white/10 flex items-center justify-center">
|
||||
<span className="text-white text-sm font-medium">
|
||||
{user?.username?.[0]?.toUpperCase() || 'U'}
|
||||
</span>
|
||||
</div>
|
||||
<div className="flex-1 min-w-0">
|
||||
<p className="text-sm font-medium text-white truncate">
|
||||
{user?.username || 'User'}
|
||||
</p>
|
||||
<p className="text-xs text-gray-400 truncate">
|
||||
{user?.email || 'admin@blog.com'}
|
||||
</p>
|
||||
</div>
|
||||
<button
|
||||
onClick={onLogout}
|
||||
className="p-1.5 text-gray-400 hover:text-white transition-colors"
|
||||
title="退出登录"
|
||||
>
|
||||
<LogoutIcon className="w-5 h-5" />
|
||||
</button>
|
||||
</div>
|
||||
</div>
|
||||
</aside>
|
||||
);
|
||||
}
|
||||
|
||||
/**
|
||||
* 后台布局容器
|
||||
*/
|
||||
export function AdminLayout({ children, user, onLogout }) {
|
||||
return (
|
||||
<div className="min-h-screen" style={{ backgroundColor: 'var(--color-bg)' }}>
|
||||
<Sidebar user={user} onLogout={onLogout} />
|
||||
|
||||
{/* 主内容区域 */}
|
||||
<main className="ml-64 min-h-screen">
|
||||
{children}
|
||||
</main>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
|
||||
// Icons
|
||||
function HomeIcon({ className }) {
|
||||
return (
|
||||
<svg className={className} fill="none" viewBox="0 0 24 24" stroke="currentColor">
|
||||
<path strokeLinecap="round" strokeLinejoin="round" strokeWidth={2} d="M3 12l2-2m0 0l7-7 7 7M5 10v10a1 1 0 001 1h3m10-11l2 2m-2-2v10a1 1 0 01-1 1h-3m-6 0a1 1 0 001-1v-4a1 1 0 011-1h2a1 1 0 011 1v4a1 1 0 001 1m-6 0h6" />
|
||||
</svg>
|
||||
);
|
||||
}
|
||||
|
||||
function DocumentIcon({ className }) {
|
||||
return (
|
||||
<svg className={className} fill="none" viewBox="0 0 24 24" stroke="currentColor">
|
||||
<path strokeLinecap="round" strokeLinejoin="round" strokeWidth={2} d="M9 12h6m-6 4h6m2 5H7a2 2 0 01-2-2V5a2 2 0 012-2h5.586a1 1 0 01.707.293l5.414 5.414a1 1 0 01.293.707V19a2 2 0 01-2 2z" />
|
||||
</svg>
|
||||
);
|
||||
}
|
||||
|
||||
function FolderIcon({ className }) {
|
||||
return (
|
||||
<svg className={className} fill="none" viewBox="0 0 24 24" stroke="currentColor">
|
||||
<path strokeLinecap="round" strokeLinejoin="round" strokeWidth={2} d="M3 7v10a2 2 0 002 2h14a2 2 0 002-2V9a2 2 0 00-2-2h-6l-2-2H5a2 2 0 00-2 2z" />
|
||||
</svg>
|
||||
);
|
||||
}
|
||||
|
||||
function ImageIcon({ className }) {
|
||||
return (
|
||||
<svg className={className} fill="none" viewBox="0 0 24 24" stroke="currentColor">
|
||||
<path strokeLinecap="round" strokeLinejoin="round" strokeWidth={2} d="M4 16l4.586-4.586a2 2 0 012.828 0L16 16m-2-2l1.586-1.586a2 2 0 012.828 0L20 14m-6-6h.01M6 20h12a2 2 0 002-2V6a2 2 0 00-2-2H6a2 2 0 00-2 2v12a2 2 0 002 2z" />
|
||||
</svg>
|
||||
);
|
||||
}
|
||||
|
||||
function CogIcon({ className }) {
|
||||
return (
|
||||
<svg className={className} fill="none" viewBox="0 0 24 24" stroke="currentColor">
|
||||
<path strokeLinecap="round" strokeLinejoin="round" strokeWidth={2} d="M10.325 4.317c.426-1.756 2.924-1.756 3.35 0a1.724 1.724 0 002.573 1.066c1.543-.94 3.31.826 2.37 2.37a1.724 1.724 0 001.065 2.572c1.756.426 1.756 2.924 0 3.35a1.724 1.724 0 00-1.066 2.573c.94 1.543-.826 3.31-2.37 2.37a1.724 1.724 0 00-2.572 1.065c-.426 1.756-2.924 1.756-3.35 0a1.724 1.724 0 00-2.573-1.066c-1.543.94-3.31-.826-2.37-2.37a1.724 1.724 0 00-1.065-2.572c-1.756-.426-1.756-2.924 0-3.35a1.724 1.724 0 001.066-2.573c-.94-1.543.826-3.31 2.37-2.37.996.608 2.296.07 2.572-1.065z" />
|
||||
<path strokeLinecap="round" strokeLinejoin="round" strokeWidth={2} d="M15 12a3 3 0 11-6 0 3 3 0 016 0z" />
|
||||
</svg>
|
||||
);
|
||||
}
|
||||
|
||||
function ChatIcon({ className }) {
|
||||
return (
|
||||
<svg className={className} fill="none" viewBox="0 0 24 24" stroke="currentColor">
|
||||
<path strokeLinecap="round" strokeLinejoin="round" strokeWidth={2} d="M8 10h.01M12 10h.01M16 10h.01M9 16H5a2 2 0 01-2-2V6a2 2 0 012-2h14a2 2 0 012 2v8a2 2 0 01-2 2h-5l-5 5v-5z" />
|
||||
</svg>
|
||||
);
|
||||
}
|
||||
|
||||
function LogoutIcon({ className }) {
|
||||
return (
|
||||
<svg className={className} fill="none" viewBox="0 0 24 24" stroke="currentColor">
|
||||
<path strokeLinecap="round" strokeLinejoin="round" strokeWidth={2} d="M17 16l4-4m0 0l-4-4m4 4H7m6 4v1a3 3 0 01-3 3H6a3 3 0 01-3-3V7a3 3 0 013-3h4a3 3 0 013 3v1" />
|
||||
</svg>
|
||||
);
|
||||
}
|
||||
|
||||
export default Sidebar;
|
||||
@@ -0,0 +1,14 @@
|
||||
// Preline UI 风格组件库
|
||||
// 用于管理后台的现代风格组件
|
||||
|
||||
export { Button } from './Button';
|
||||
export { Card, CardHeader, CardTitle, CardDescription, CardBody, CardFooter } from './Card';
|
||||
export {
|
||||
Input,
|
||||
Textarea,
|
||||
Select,
|
||||
Label,
|
||||
FormError,
|
||||
FormHelp
|
||||
} from './Input';
|
||||
export { Sidebar, AdminLayout } from './Sidebar';
|
||||
@@ -0,0 +1,40 @@
|
||||
// 新粗野主义按钮组件
|
||||
export function Button({
|
||||
children,
|
||||
variant = 'primary',
|
||||
size = 'md',
|
||||
className = '',
|
||||
onClick,
|
||||
type = 'button',
|
||||
disabled = false
|
||||
}) {
|
||||
const baseClasses = 'inline-flex items-center justify-center font-bold transition-all duration-150 border-2 border-black'
|
||||
|
||||
const variants = {
|
||||
primary: 'bg-brutal-pink text-black shadow-brutal hover:shadow-none hover:translate-x-[2px] hover:translate-y-[2px]',
|
||||
secondary: 'bg-brutal-cyan text-black shadow-brutal hover:shadow-none hover:translate-x-[2px] hover:translate-y-[2px]',
|
||||
success: 'bg-brutal-green text-black shadow-brutal hover:shadow-none hover:translate-x-[2px] hover:translate-y-[2px]',
|
||||
warning: 'bg-brutal-yellow text-black shadow-brutal hover:shadow-none hover:translate-x-[2px] hover:translate-y-[2px]',
|
||||
danger: 'bg-red-500 text-white shadow-brutal hover:shadow-none hover:translate-x-[2px] hover:translate-y-[2px]',
|
||||
outline: 'bg-white text-black shadow-brutal-sm hover:shadow-none hover:translate-x-[1px] hover:translate-y-[1px]'
|
||||
}
|
||||
|
||||
const sizes = {
|
||||
sm: 'px-3 py-1.5 text-xs',
|
||||
md: 'px-4 py-2 text-sm',
|
||||
lg: 'px-6 py-3 text-base'
|
||||
}
|
||||
|
||||
const disabledClasses = disabled ? 'opacity-50 cursor-not-allowed' : ''
|
||||
|
||||
return (
|
||||
<button
|
||||
type={type}
|
||||
onClick={onClick}
|
||||
disabled={disabled}
|
||||
className={`${baseClasses} ${variants[variant]} ${sizes[size]} ${disabledClasses} ${className}`}
|
||||
>
|
||||
{children}
|
||||
</button>
|
||||
)
|
||||
}
|
||||
@@ -0,0 +1,54 @@
|
||||
// 新粗野主义卡片组件
|
||||
export function Card({
|
||||
children,
|
||||
className = '',
|
||||
padding = 'normal',
|
||||
shadow = 'normal'
|
||||
}) {
|
||||
const paddings = {
|
||||
none: '',
|
||||
small: 'p-3',
|
||||
normal: 'p-4',
|
||||
large: 'p-6'
|
||||
}
|
||||
|
||||
const shadows = {
|
||||
none: '',
|
||||
small: 'shadow-brutal-sm',
|
||||
normal: 'shadow-brutal',
|
||||
large: 'shadow-brutal-lg'
|
||||
}
|
||||
|
||||
return (
|
||||
<div className={`bg-white border-2 border-black ${shadows[shadow]} ${paddings[padding]} ${className}`}>
|
||||
{children}
|
||||
</div>
|
||||
)
|
||||
}
|
||||
|
||||
// 卡片头部
|
||||
export function CardHeader({ children, className = '' }) {
|
||||
return (
|
||||
<div className={`border-b-2 border-black pb-3 mb-4 ${className}`}>
|
||||
{children}
|
||||
</div>
|
||||
)
|
||||
}
|
||||
|
||||
// 卡片标题
|
||||
export function CardTitle({ children, className = '' }) {
|
||||
return (
|
||||
<h3 className={`text-lg font-bold ${className}`}>
|
||||
{children}
|
||||
</h3>
|
||||
)
|
||||
}
|
||||
|
||||
// 卡片内容
|
||||
export function CardContent({ children, className = '' }) {
|
||||
return (
|
||||
<div className={className}>
|
||||
{children}
|
||||
</div>
|
||||
)
|
||||
}
|
||||
@@ -0,0 +1,92 @@
|
||||
// 新粗野主义输入框组件
|
||||
export function Input({
|
||||
id,
|
||||
type = 'text',
|
||||
placeholder = '',
|
||||
value,
|
||||
onChange,
|
||||
className = '',
|
||||
disabled = false,
|
||||
required = false,
|
||||
name = ''
|
||||
}) {
|
||||
return (
|
||||
<input
|
||||
id={id}
|
||||
type={type}
|
||||
name={name}
|
||||
placeholder={placeholder}
|
||||
value={value}
|
||||
onChange={onChange}
|
||||
disabled={disabled}
|
||||
required={required}
|
||||
className={`
|
||||
w-full px-3 py-2
|
||||
border-2 border-black
|
||||
bg-white
|
||||
focus:outline-none focus:ring-2 focus:ring-brutal-yellow
|
||||
placeholder:text-black/40
|
||||
disabled:bg-gray-100 disabled:cursor-not-allowed
|
||||
${className}
|
||||
`}
|
||||
/>
|
||||
)
|
||||
}
|
||||
|
||||
// 文本域
|
||||
export function TextArea({
|
||||
id,
|
||||
placeholder = '',
|
||||
value,
|
||||
onChange,
|
||||
rows = 4,
|
||||
className = '',
|
||||
disabled = false,
|
||||
required = false,
|
||||
name = ''
|
||||
}) {
|
||||
return (
|
||||
<textarea
|
||||
id={id}
|
||||
name={name}
|
||||
placeholder={placeholder}
|
||||
value={value}
|
||||
onChange={onChange}
|
||||
rows={rows}
|
||||
disabled={disabled}
|
||||
required={required}
|
||||
className={`
|
||||
w-full px-3 py-2
|
||||
border-2 border-black
|
||||
bg-white
|
||||
focus:outline-none focus:ring-2 focus:ring-brutal-yellow
|
||||
placeholder:text-black/40
|
||||
disabled:bg-gray-100 disabled:cursor-not-allowed
|
||||
resize-vertical
|
||||
${className}
|
||||
`}
|
||||
/>
|
||||
)
|
||||
}
|
||||
|
||||
// 标签
|
||||
export function Label({ children, htmlFor = '', className = '', required = false }) {
|
||||
return (
|
||||
<label
|
||||
htmlFor={htmlFor}
|
||||
className={`block text-sm font-bold mb-1 ${className}`}
|
||||
>
|
||||
{children}
|
||||
{required && <span className="text-brutal-pink ml-1">*</span>}
|
||||
</label>
|
||||
)
|
||||
}
|
||||
|
||||
// 表单组
|
||||
export function FormGroup({ children, className = '' }) {
|
||||
return (
|
||||
<div className={`mb-4 ${className}`}>
|
||||
{children}
|
||||
</div>
|
||||
)
|
||||
}
|
||||
@@ -0,0 +1,38 @@
|
||||
import { Sidebar } from './Sidebar'
|
||||
|
||||
// 页面布局组件
|
||||
export function Layout({ children, title, actions }) {
|
||||
return (
|
||||
<div className="flex min-h-screen bg-brutal-cream">
|
||||
<Sidebar />
|
||||
|
||||
<main className="flex-1 flex flex-col">
|
||||
{/* 顶部标题栏 */}
|
||||
<header className="bg-white border-b-2 border-black px-6 py-4">
|
||||
<div className="flex items-center justify-between">
|
||||
<h1 className="text-2xl font-bold">{title}</h1>
|
||||
{actions && (
|
||||
<div className="flex items-center gap-3">
|
||||
{actions}
|
||||
</div>
|
||||
)}
|
||||
</div>
|
||||
</header>
|
||||
|
||||
{/* 内容区域 */}
|
||||
<div className="flex-1 p-6 overflow-auto">
|
||||
{children}
|
||||
</div>
|
||||
</main>
|
||||
</div>
|
||||
)
|
||||
}
|
||||
|
||||
// 简单布局(无侧边栏,用于登录页)
|
||||
export function SimpleLayout({ children }) {
|
||||
return (
|
||||
<div className="min-h-screen bg-brutal-cream flex items-center justify-center p-4">
|
||||
{children}
|
||||
</div>
|
||||
)
|
||||
}
|
||||
@@ -0,0 +1,88 @@
|
||||
import { NavLink, useNavigate } from 'react-router-dom'
|
||||
import { authApi } from '../api/auth'
|
||||
|
||||
// 导航项
|
||||
function NavItem({ to, icon, label }) {
|
||||
return (
|
||||
<NavLink
|
||||
to={to}
|
||||
className={({ isActive }) =>
|
||||
`flex items-center gap-3 px-4 py-3 font-bold transition-all duration-150 ${
|
||||
isActive
|
||||
? 'bg-black text-brutal-yellow border-l-4 border-brutal-yellow'
|
||||
: 'text-black hover:bg-black/10 border-l-4 border-transparent'
|
||||
}`
|
||||
}
|
||||
>
|
||||
<span className="text-lg">{icon}</span>
|
||||
<span>{label}</span>
|
||||
</NavLink>
|
||||
)
|
||||
}
|
||||
|
||||
// 侧边栏组件
|
||||
export function Sidebar() {
|
||||
const navigate = useNavigate()
|
||||
|
||||
const handleLogout = async () => {
|
||||
// 1) 先调用后端清除 SSO Cookie,避免自动登录
|
||||
try {
|
||||
await authApi.logout()
|
||||
} catch {
|
||||
// 即使后端失败也继续本地清理
|
||||
}
|
||||
// 2) 再清除本地 token
|
||||
localStorage.removeItem('token')
|
||||
// 3) 跳转登录页
|
||||
navigate('/login')
|
||||
}
|
||||
|
||||
return (
|
||||
<aside className="w-64 bg-brutal-yellow border-r-2 border-black flex flex-col min-h-screen">
|
||||
{/* Logo */}
|
||||
<div className="p-4 border-b-2 border-black">
|
||||
<NavLink to="/" className="inline-block -rotate-2 border-2 border-black bg-black px-4 py-2 shadow-brutal hover:rotate-0 transition-transform">
|
||||
<span className="font-bold text-xl text-brutal-yellow">BLOG</span>
|
||||
</NavLink>
|
||||
</div>
|
||||
|
||||
{/* 导航菜单 */}
|
||||
<nav className="flex-1 py-4 space-y-1">
|
||||
<NavItem to="/admin" icon="🏠" label="控制台" />
|
||||
<NavItem to="/admin/posts" icon="📝" label="文章管理" />
|
||||
<NavItem to="/admin/categories" icon="📁" label="分类管理" />
|
||||
<NavItem to="/admin/images" icon="🖼️" label="图片管理" />
|
||||
<NavItem to="/admin/nanobot" icon="🤖" label="Nanobot 助手" />
|
||||
<NavItem to="/admin/settings" icon="⚙️" label="博客设置" />
|
||||
</nav>
|
||||
|
||||
{/* 退出登录 */}
|
||||
<div className="p-4 border-t-2 border-black">
|
||||
<button
|
||||
onClick={handleLogout}
|
||||
className="w-full flex items-center gap-3 px-4 py-3 font-bold text-black hover:bg-red-100 border-l-4 border-transparent hover:border-red-500 transition-all"
|
||||
>
|
||||
<span className="text-lg">🚪</span>
|
||||
<span>退出登录</span>
|
||||
</button>
|
||||
</div>
|
||||
|
||||
{/* 底部信息 */}
|
||||
<div className="p-4 border-t-2 border-black">
|
||||
<div className="flex items-center justify-between">
|
||||
<p className="text-xs font-bold text-black/60">
|
||||
Personal Blog v1.0
|
||||
</p>
|
||||
<a
|
||||
href="/"
|
||||
target="_blank"
|
||||
rel="noopener noreferrer"
|
||||
className="text-xs font-bold text-black hover:underline"
|
||||
>
|
||||
查看首页 →
|
||||
</a>
|
||||
</div>
|
||||
</div>
|
||||
</aside>
|
||||
)
|
||||
}
|
||||
@@ -0,0 +1,364 @@
|
||||
/* ========== Personal Blog - 双主题共存方案 ========== */
|
||||
/* 主题1: Neobrutalism (访客端默认) */
|
||||
/* 主题2: Preline Admin (管理后台) */
|
||||
|
||||
/* 基础 Tailwind */
|
||||
@tailwind base;
|
||||
@tailwind components;
|
||||
@tailwind utilities;
|
||||
|
||||
/* ============================================ */
|
||||
/* CSS 变量定义 */
|
||||
/* ============================================ */
|
||||
|
||||
:root {
|
||||
/* Neobrutalism 默认配色 */
|
||||
--brutal-cream: #FEF9E7;
|
||||
--brutal-yellow: #FFDE59;
|
||||
--brutal-pink: #FF6B9D;
|
||||
--brutal-cyan: #00D9FF;
|
||||
--brutal-lavender: #C084FC;
|
||||
--brutal-green: #4ADE80;
|
||||
|
||||
/* 动态主题变量(默认 Preline 配色,会被后端配置覆盖) */
|
||||
--color-primary: #2563EB;
|
||||
--color-primary-hover: #1D4ED8;
|
||||
--color-primary-light: #EFF6FF;
|
||||
--color-secondary: #06B6D4;
|
||||
--color-sidebar: #1E293B;
|
||||
--color-sidebar-active: #334155;
|
||||
--color-bg: #F8FAFC;
|
||||
--color-card: #FFFFFF;
|
||||
--color-border: #E2E8F0;
|
||||
--color-text: #0F172A;
|
||||
--color-text-secondary: #64748B;
|
||||
|
||||
/* Primary 色阶 (50-950) */
|
||||
--color-primary-50: #EFF6FF;
|
||||
--color-primary-100: #DBEAFE;
|
||||
--color-primary-200: #BFDBFE;
|
||||
--color-primary-300: #93C5FD;
|
||||
--color-primary-400: #60A5FA;
|
||||
--color-primary-500: #3B82F6;
|
||||
--color-primary-600: #2563EB;
|
||||
--color-primary-700: #1D4ED8;
|
||||
--color-primary-800: #1E40AF;
|
||||
--color-primary-900: #1E3A8A;
|
||||
--color-primary-950: #172554;
|
||||
|
||||
/* Secondary 色阶 (50-950) */
|
||||
--color-secondary-50: #ECFEFF;
|
||||
--color-secondary-100: #CFFAFE;
|
||||
--color-secondary-200: #A5F3FC;
|
||||
--color-secondary-300: #67E8F9;
|
||||
--color-secondary-400: #22D3EE;
|
||||
--color-secondary-500: #06B6D4;
|
||||
--color-secondary-600: #0891B2;
|
||||
--color-secondary-700: #0E7490;
|
||||
--color-secondary-800: #155E75;
|
||||
--color-secondary-900: #164E63;
|
||||
--color-secondary-950: #083344;
|
||||
|
||||
/* Gray 色阶 (50-950) */
|
||||
--color-gray-50: #F8FAFC;
|
||||
--color-gray-100: #F1F5F9;
|
||||
--color-gray-200: #E2E8F0;
|
||||
--color-gray-300: #CBD5E1;
|
||||
--color-gray-400: #94A3B8;
|
||||
--color-gray-500: #64748B;
|
||||
--color-gray-600: #475569;
|
||||
--color-gray-700: #334155;
|
||||
--color-gray-800: #1E293B;
|
||||
--color-gray-900: #0F172A;
|
||||
--color-gray-950: #020617;
|
||||
|
||||
/* Semantic colors */
|
||||
--color-success: #22C55E;
|
||||
--color-success-bg: #DCFCE7;
|
||||
--color-success-border: #BBF7D0;
|
||||
--color-success-text: #14532D;
|
||||
--color-warning: #F59E0B;
|
||||
--color-warning-bg: #FEF3C7;
|
||||
--color-warning-border: #FDE68A;
|
||||
--color-warning-text: #78350F;
|
||||
--color-danger: #EF4444;
|
||||
--color-danger-bg: #FEE2E2;
|
||||
--color-danger-border: #FECACA;
|
||||
--color-danger-text: #7F1D1D;
|
||||
--color-info: #3B82F6;
|
||||
--color-info-bg: #DBEAFE;
|
||||
--color-info-border: #BFDBFE;
|
||||
--color-info-text: #1E3A8A;
|
||||
|
||||
/* Neobrutalism 装饰变量 */
|
||||
--border-width: 2px;
|
||||
--border-radius: 0px;
|
||||
--shadow: 4px 4px 0px 0px rgba(0,0,0,1);
|
||||
}
|
||||
|
||||
/* ============================================ */
|
||||
/* 基础样式 */
|
||||
/* ============================================ */
|
||||
|
||||
@layer base {
|
||||
body {
|
||||
@apply bg-[var(--color-bg)] text-[var(--color-text)];
|
||||
font-family: system-ui, -apple-system, sans-serif;
|
||||
}
|
||||
}
|
||||
|
||||
/* ============================================ */
|
||||
/* Neobrutalism 组件样式 (保留) */
|
||||
/* ============================================ */
|
||||
|
||||
@layer components {
|
||||
/* 核心按钮样式 */
|
||||
.btn-brutal {
|
||||
@apply inline-flex items-center justify-center px-4 py-2
|
||||
border-2 border-black font-bold text-sm
|
||||
transition-all duration-150
|
||||
shadow-brutal hover:shadow-none
|
||||
hover:translate-x-[2px] hover:translate-y-[2px]
|
||||
active:translate-x-[4px] active:translate-y-[4px];
|
||||
}
|
||||
|
||||
.btn-brutal-sm {
|
||||
@apply inline-flex items-center justify-center px-3 py-1.5
|
||||
border-2 border-black font-bold text-xs
|
||||
transition-all duration-150
|
||||
shadow-brutal-sm hover:shadow-none
|
||||
hover:translate-x-[1px] hover:translate-y-[1px];
|
||||
}
|
||||
|
||||
/* 卡片样式 */
|
||||
.card-brutal {
|
||||
@apply bg-white border-2 border-black shadow-brutal;
|
||||
}
|
||||
|
||||
.card-brutal-sm {
|
||||
@apply bg-white border-2 border-black shadow-brutal-sm;
|
||||
}
|
||||
|
||||
/* 输入框样式 */
|
||||
.input-brutal {
|
||||
@apply w-full px-3 py-2
|
||||
border-2 border-black
|
||||
bg-white
|
||||
focus:outline-none focus:ring-2 focus:ring-brutal-yellow
|
||||
placeholder:text-black/40;
|
||||
}
|
||||
|
||||
/* 导航链接 */
|
||||
.nav-link {
|
||||
@apply px-3 py-1 font-bold text-sm
|
||||
border-2 border-transparent
|
||||
hover:border-black hover:bg-white
|
||||
transition-all duration-150;
|
||||
}
|
||||
|
||||
.nav-link-active {
|
||||
@apply px-3 py-1 font-bold text-sm
|
||||
border-2 border-black bg-brutal-yellow;
|
||||
}
|
||||
}
|
||||
|
||||
/* ============================================ */
|
||||
/* Preline Admin 组件样式 (新增) */
|
||||
/* ============================================ */
|
||||
|
||||
@layer components {
|
||||
/* Preline 风格按钮 */
|
||||
.btn-preline {
|
||||
@apply inline-flex items-center justify-center gap-2
|
||||
px-4 py-2.5 rounded-lg font-medium text-sm
|
||||
bg-blue-600 text-white
|
||||
hover:bg-blue-700 focus:outline-none focus:ring-2
|
||||
focus:ring-blue-500 focus:ring-offset-2
|
||||
transition-all duration-200;
|
||||
}
|
||||
|
||||
.btn-preline-secondary {
|
||||
@apply inline-flex items-center justify-center gap-2
|
||||
px-4 py-2.5 rounded-lg font-medium text-sm
|
||||
bg-white text-gray-700
|
||||
border border-gray-300
|
||||
hover:bg-gray-50 focus:outline-none focus:ring-2
|
||||
focus:ring-gray-200 transition-all duration-200;
|
||||
}
|
||||
|
||||
.btn-preline-danger {
|
||||
@apply inline-flex items-center justify-center gap-2
|
||||
px-4 py-2.5 rounded-lg font-medium text-sm
|
||||
bg-red-600 text-white
|
||||
hover:bg-red-700 focus:outline-none focus:ring-2
|
||||
focus:ring-red-500 focus:ring-offset-2
|
||||
transition-all duration-200;
|
||||
}
|
||||
|
||||
/* Preline 风格卡片 */
|
||||
.card-preline {
|
||||
@apply bg-white rounded-xl
|
||||
border border-gray-200
|
||||
shadow-sm hover:shadow-md transition-shadow duration-200;
|
||||
}
|
||||
|
||||
.card-preline-header {
|
||||
@apply px-6 py-4 border-b border-gray-200
|
||||
flex items-center justify-between;
|
||||
}
|
||||
|
||||
.card-preline-body {
|
||||
@apply px-6 py-4;
|
||||
}
|
||||
|
||||
.card-preline-footer {
|
||||
@apply px-6 py-4 border-t border-gray-200
|
||||
flex items-center justify-end gap-3;
|
||||
}
|
||||
|
||||
/* Preline 风格输入框 */
|
||||
.input-preline {
|
||||
@apply w-full px-4 py-2.5 rounded-lg
|
||||
border border-gray-300 bg-white
|
||||
text-gray-900
|
||||
focus:outline-none focus:ring-2
|
||||
focus:ring-blue-500/20
|
||||
focus:border-blue-500
|
||||
placeholder:text-gray-400
|
||||
transition-all duration-200;
|
||||
}
|
||||
|
||||
.label-preline {
|
||||
@apply block text-sm font-medium text-gray-700 mb-1.5;
|
||||
}
|
||||
|
||||
/* Preline 侧边栏 */
|
||||
.sidebar-preline {
|
||||
@apply w-64 bg-slate-900 min-h-screen
|
||||
fixed left-0 top-0 z-40;
|
||||
}
|
||||
|
||||
.sidebar-preline-nav {
|
||||
@apply mt-6 px-3 space-y-1;
|
||||
}
|
||||
|
||||
.sidebar-preline-item {
|
||||
@apply flex items-center gap-3 px-3 py-2.5 rounded-lg
|
||||
text-gray-400 hover:bg-slate-800
|
||||
hover:text-white transition-colors duration-200;
|
||||
}
|
||||
|
||||
.sidebar-preline-item.active {
|
||||
@apply bg-slate-800 text-white font-medium;
|
||||
}
|
||||
|
||||
.sidebar-preline-icon {
|
||||
@apply w-5 h-5 flex-shrink-0;
|
||||
}
|
||||
|
||||
/* Preline 页面头部 */
|
||||
.page-header-preline {
|
||||
@apply flex items-center justify-between mb-6;
|
||||
}
|
||||
|
||||
.page-title-preline {
|
||||
@apply text-2xl font-semibold text-gray-900;
|
||||
}
|
||||
|
||||
/* Preline 统计卡片 */
|
||||
.stats-card-preline {
|
||||
@apply bg-white rounded-xl p-6
|
||||
border border-gray-200 shadow-sm;
|
||||
}
|
||||
|
||||
.stats-card-preline-label {
|
||||
@apply text-sm font-medium text-gray-500 mb-1;
|
||||
}
|
||||
|
||||
.stats-card-preline-value {
|
||||
@apply text-3xl font-bold text-gray-900;
|
||||
}
|
||||
|
||||
/* Preline 数据表格 */
|
||||
.table-preline {
|
||||
@apply w-full text-sm text-left;
|
||||
}
|
||||
|
||||
.table-preline thead {
|
||||
@apply bg-gray-50 text-gray-700 font-medium;
|
||||
}
|
||||
|
||||
.table-preline th {
|
||||
@apply px-6 py-4;
|
||||
}
|
||||
|
||||
.table-preline td {
|
||||
@apply px-6 py-4 border-b border-gray-100;
|
||||
}
|
||||
|
||||
.table-preline tbody tr:hover {
|
||||
@apply bg-gray-50;
|
||||
}
|
||||
|
||||
/* Preline 标签 */
|
||||
.badge-preline {
|
||||
@apply inline-flex items-center px-2.5 py-0.5 rounded-full
|
||||
text-xs font-medium;
|
||||
}
|
||||
|
||||
.badge-preline-green {
|
||||
@apply bg-green-100 text-green-800;
|
||||
}
|
||||
|
||||
.badge-preline-blue {
|
||||
@apply bg-blue-100 text-blue-800;
|
||||
}
|
||||
|
||||
.badge-preline-gray {
|
||||
@apply bg-gray-100 text-gray-800;
|
||||
}
|
||||
}
|
||||
|
||||
/* ============================================ */
|
||||
/* 工具类扩展 */
|
||||
/* ============================================ */
|
||||
|
||||
@layer utilities {
|
||||
.shadow-brutal {
|
||||
box-shadow: 4px 4px 0px 0px rgba(0,0,0,1);
|
||||
}
|
||||
|
||||
.shadow-brutal-sm {
|
||||
box-shadow: 2px 2px 0px 0px rgba(0,0,0,1);
|
||||
}
|
||||
}
|
||||
|
||||
/* ============================================ */
|
||||
/* 滚动条样式 */
|
||||
/* ============================================ */
|
||||
|
||||
/* Neobrutalism 滚动条 */
|
||||
::-webkit-scrollbar {
|
||||
width: 10px;
|
||||
height: 10px;
|
||||
}
|
||||
|
||||
::-webkit-scrollbar-track {
|
||||
background: #FEF9E7;
|
||||
border-left: 2px solid black;
|
||||
}
|
||||
|
||||
::-webkit-scrollbar-thumb {
|
||||
background: #000;
|
||||
border: 2px solid #FEF9E7;
|
||||
}
|
||||
|
||||
::-webkit-scrollbar-thumb:hover {
|
||||
background: #333;
|
||||
}
|
||||
|
||||
/* 选中文字样式 */
|
||||
::selection {
|
||||
background: #FFDE59;
|
||||
color: #000;
|
||||
}
|
||||
@@ -0,0 +1,92 @@
|
||||
import React from 'react'
|
||||
import ReactDOM from 'react-dom/client'
|
||||
import App from './App.jsx'
|
||||
import './index.css'
|
||||
|
||||
// Preline UI JavaScript
|
||||
import 'preline'
|
||||
|
||||
import { generateShades } from './utils/colorPalette.js'
|
||||
|
||||
const API_BASE_URL = 'http://129.211.173.87:8889/api'
|
||||
const SHADE_STOPS = [50, 100, 200, 300, 400, 500, 600, 700, 800, 900, 950]
|
||||
|
||||
/**
|
||||
* 从后端加载配色配置并注入 CSS 变量
|
||||
* 这个请求在登录前也能访问,确保访客和管理员都能看到统一主题
|
||||
*/
|
||||
async function loadThemeColors() {
|
||||
try {
|
||||
const res = await fetch(`${API_BASE_URL}/settings/public`, {
|
||||
method: 'GET',
|
||||
headers: { 'Content-Type': 'application/json' },
|
||||
})
|
||||
if (!res.ok) return
|
||||
const data = await res.json()
|
||||
let colors = data.theme_colors || {}
|
||||
if (typeof colors === 'string') {
|
||||
try {
|
||||
colors = JSON.parse(colors)
|
||||
} catch (e) {
|
||||
colors = {}
|
||||
}
|
||||
}
|
||||
const root = document.documentElement
|
||||
|
||||
const shades = colors.shades || {}
|
||||
const primaryFallback = shades[500] || colors.primary
|
||||
const hoverFallback = shades[600] || colors['primary-hover'] || primaryFallback
|
||||
const lightFallback = shades[100] || colors['primary-light'] || primaryFallback
|
||||
|
||||
// 语义变量(色阶优先)
|
||||
if (primaryFallback) root.style.setProperty('--color-primary', primaryFallback)
|
||||
if (hoverFallback) root.style.setProperty('--color-primary-hover', hoverFallback)
|
||||
if (lightFallback) root.style.setProperty('--color-primary-light', lightFallback)
|
||||
|
||||
const mapping = {
|
||||
secondary: '--color-secondary',
|
||||
bg: '--color-bg',
|
||||
text: '--color-text',
|
||||
sidebar: '--color-sidebar',
|
||||
'sidebar-active': '--color-sidebar-active',
|
||||
card: '--color-card',
|
||||
border: '--color-border',
|
||||
'text-secondary': '--color-text-secondary',
|
||||
}
|
||||
|
||||
Object.entries(mapping).forEach(([key, cssVar]) => {
|
||||
if (colors[key]) {
|
||||
root.style.setProperty(cssVar, colors[key])
|
||||
}
|
||||
})
|
||||
|
||||
// Primary 色阶 (50-950)
|
||||
if (shades && Object.keys(shades).length > 0) {
|
||||
SHADE_STOPS.forEach(stop => {
|
||||
if (shades[stop]) {
|
||||
root.style.setProperty(`--color-primary-${stop}`, shades[stop])
|
||||
}
|
||||
})
|
||||
}
|
||||
|
||||
// Secondary 色阶 (50-950)
|
||||
if (colors.secondary) {
|
||||
const secShades = generateShades(colors.secondary)
|
||||
SHADE_STOPS.forEach(stop => {
|
||||
root.style.setProperty(`--color-secondary-${stop}`, secShades[stop])
|
||||
})
|
||||
}
|
||||
} catch (e) {
|
||||
// 静默失败,使用默认 CSS 变量值
|
||||
console.warn('加载主题配色失败,使用默认值', e)
|
||||
}
|
||||
}
|
||||
|
||||
// 先加载主题,再渲染应用
|
||||
loadThemeColors().then(() => {
|
||||
ReactDOM.createRoot(document.getElementById('root')).render(
|
||||
<React.StrictMode>
|
||||
<App />
|
||||
</React.StrictMode>,
|
||||
)
|
||||
})
|
||||
@@ -0,0 +1,598 @@
|
||||
// 文章采集编辑页面 - Preline UI 风格
|
||||
import { useState, useEffect } from 'react'
|
||||
import { useNavigate } from 'react-router-dom'
|
||||
import { AdminLayout } from '../components-preline/Sidebar'
|
||||
import { authApi } from '../api/auth'
|
||||
import { Card, CardHeader, CardTitle, CardDescription, CardBody, CardFooter } from '../components-preline/Card'
|
||||
import { Button } from '../components-preline/Button'
|
||||
import { Input, Textarea, Label, FormError } from '../components-preline/Input'
|
||||
import { postsApi } from '../api/posts'
|
||||
import { categoriesApi } from '../api/categories'
|
||||
import { tagsApi } from '../api/tags'
|
||||
import { API_BASE_URL } from '../api/config'
|
||||
|
||||
// 错误弹窗组件
|
||||
function ErrorModal({ message, onClose, onClear }) {
|
||||
if (!message) return null
|
||||
|
||||
return (
|
||||
<div className="fixed inset-0 bg-black/50 flex items-center justify-center z-50 p-4">
|
||||
<div className="bg-white rounded-xl shadow-xl max-w-md w-full p-6">
|
||||
<div className="flex items-center gap-3 mb-4">
|
||||
<div className="w-12 h-12 bg-red-100 rounded-full flex items-center justify-center">
|
||||
<svg className="w-6 h-6 text-red-600" fill="none" viewBox="0 0 24 24" stroke="currentColor">
|
||||
<path strokeLinecap="round" strokeLinejoin="round" strokeWidth={2} d="M6 18L18 6M6 6l12 12" />
|
||||
</svg>
|
||||
</div>
|
||||
<h3 className="text-lg font-semibold text-gray-900">采集失败</h3>
|
||||
</div>
|
||||
<p className="text-gray-600 mb-6 leading-relaxed">
|
||||
{message}
|
||||
</p>
|
||||
<div className="flex gap-3">
|
||||
<Button
|
||||
onClick={onClose}
|
||||
variant="primary"
|
||||
className="flex-1"
|
||||
>
|
||||
确定
|
||||
</Button>
|
||||
<Button
|
||||
onClick={() => {
|
||||
onClose()
|
||||
onClear()
|
||||
}}
|
||||
variant="secondary"
|
||||
>
|
||||
清空链接
|
||||
</Button>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
)
|
||||
}
|
||||
|
||||
export function CrawlEdit() {
|
||||
const navigate = useNavigate()
|
||||
|
||||
// 获取当前用户信息
|
||||
const user = JSON.parse(localStorage.getItem('user') || '{}')
|
||||
|
||||
// 采集步骤
|
||||
const [step, setStep] = useState('input') // input -> crawling -> edit
|
||||
const [crawlUrl, setCrawlUrl] = useState('')
|
||||
const [crawling, setCrawling] = useState(false)
|
||||
const [crawlError, setCrawlError] = useState('')
|
||||
|
||||
// 表单数据
|
||||
const [form, setForm] = useState({
|
||||
title: '',
|
||||
content: '',
|
||||
summary: '',
|
||||
category_id: '',
|
||||
tag_ids: [],
|
||||
is_published: false,
|
||||
is_draft: true
|
||||
})
|
||||
|
||||
// 采集的图片
|
||||
const [crawledImages, setCrawledImages] = useState([])
|
||||
|
||||
// 分类和标签
|
||||
const [categories, setCategories] = useState([])
|
||||
const [tags, setTags] = useState([])
|
||||
|
||||
// 保存状态
|
||||
const [saving, setSaving] = useState(false)
|
||||
|
||||
// 错误弹窗
|
||||
const [showErrorModal, setShowErrorModal] = useState(false)
|
||||
const [errorModalMessage, setErrorModalMessage] = useState('')
|
||||
|
||||
// 加载分类和标签,并清空之前的状态
|
||||
useEffect(() => {
|
||||
// 清空表单状态,防止显示之前缓存的数据
|
||||
setForm({
|
||||
title: '',
|
||||
content: '',
|
||||
summary: '',
|
||||
category_id: '',
|
||||
tag_ids: [],
|
||||
is_published: false,
|
||||
is_draft: true
|
||||
})
|
||||
setCrawledImages([])
|
||||
setStep('input')
|
||||
setCrawlError('')
|
||||
|
||||
const loadData = async () => {
|
||||
try {
|
||||
const [catRes, tagRes] = await Promise.all([
|
||||
categoriesApi.getCategories(),
|
||||
tagsApi.getTags()
|
||||
])
|
||||
setCategories(catRes.data)
|
||||
setTags(tagRes.data)
|
||||
} catch (error) {
|
||||
console.error('加载数据失败:', error)
|
||||
}
|
||||
}
|
||||
loadData()
|
||||
}, [])
|
||||
|
||||
// 开始采集
|
||||
const handleCrawl = async (e) => {
|
||||
e.preventDefault()
|
||||
|
||||
if (!crawlUrl.trim()) {
|
||||
alert('请输入文章链接')
|
||||
return
|
||||
}
|
||||
|
||||
if (!crawlUrl.startsWith('http://') && !crawlUrl.startsWith('https://')) {
|
||||
alert('请输入有效的URL(以 http:// 或 https:// 开头)')
|
||||
return
|
||||
}
|
||||
|
||||
setCrawling(true)
|
||||
setCrawlError('')
|
||||
|
||||
try {
|
||||
const token = localStorage.getItem('token')
|
||||
// 添加随机数防止缓存
|
||||
const nocache = Date.now()
|
||||
// 采集文章可能耗时较长(需下载图片),设置 120 秒超时
|
||||
const controller = new AbortController()
|
||||
const timeoutId = setTimeout(() => controller.abort(), 120000)
|
||||
|
||||
// 构造请求头:有 token 则带 Bearer,同时启用 credentials 以支持 SSO Cookie 认证
|
||||
const headers = {
|
||||
'Content-Type': 'application/json',
|
||||
'Cache-Control': 'no-cache, no-store, must-revalidate',
|
||||
'Pragma': 'no-cache'
|
||||
}
|
||||
if (token) {
|
||||
headers['Authorization'] = `Bearer ${token}`
|
||||
}
|
||||
|
||||
const response = await fetch(`${API_BASE_URL}/crawl?_=${nocache}`, {
|
||||
method: 'POST',
|
||||
headers,
|
||||
body: JSON.stringify({ url: crawlUrl }),
|
||||
signal: controller.signal,
|
||||
credentials: 'include'
|
||||
})
|
||||
clearTimeout(timeoutId)
|
||||
|
||||
if (!response.ok) {
|
||||
const errorText = await response.text()
|
||||
throw new Error(`服务器错误 ${response.status}: ${errorText || response.statusText}`)
|
||||
}
|
||||
|
||||
const data = await response.json()
|
||||
|
||||
if (!data.success) {
|
||||
const errorMsg = data.error || '采集失败,请检查链接是否有效'
|
||||
setCrawlError(errorMsg)
|
||||
setErrorModalMessage(errorMsg)
|
||||
setShowErrorModal(true)
|
||||
setCrawling(false)
|
||||
return
|
||||
}
|
||||
|
||||
// 填充表单
|
||||
setForm({
|
||||
title: data.title || '',
|
||||
content: data.content || '',
|
||||
summary: data.summary || '',
|
||||
category_id: '',
|
||||
tag_ids: [],
|
||||
is_published: false,
|
||||
is_draft: true
|
||||
})
|
||||
|
||||
// 设置图片
|
||||
setCrawledImages(data.images || [])
|
||||
|
||||
// 进入编辑步骤
|
||||
setStep('edit')
|
||||
|
||||
} catch (error) {
|
||||
const errorMsg = '采集失败: ' + (error.message || '网络错误,请稍后重试')
|
||||
setCrawlError(errorMsg)
|
||||
setErrorModalMessage(errorMsg)
|
||||
setShowErrorModal(true)
|
||||
} finally {
|
||||
setCrawling(false)
|
||||
}
|
||||
}
|
||||
|
||||
// 保存文章
|
||||
const handleSubmit = async (e, isDraft = false) => {
|
||||
e.preventDefault()
|
||||
|
||||
if (!form.title.trim() || !form.content.trim()) {
|
||||
alert('请填写标题和内容')
|
||||
return
|
||||
}
|
||||
|
||||
setSaving(true)
|
||||
try {
|
||||
const data = {
|
||||
...form,
|
||||
category_id: form.category_id || null,
|
||||
is_draft: isDraft,
|
||||
is_published: !isDraft
|
||||
}
|
||||
|
||||
await postsApi.createPost(data)
|
||||
navigate('/admin/posts')
|
||||
} catch (error) {
|
||||
alert('保存失败: ' + (error.response?.data?.detail || '未知错误'))
|
||||
} finally {
|
||||
setSaving(false)
|
||||
}
|
||||
}
|
||||
|
||||
// 在内容中插入图片
|
||||
const insertImageToContent = (imagePath) => {
|
||||
const imageMarkdown = `\n\n\n\n`
|
||||
setForm({
|
||||
...form,
|
||||
content: form.content + imageMarkdown
|
||||
})
|
||||
}
|
||||
|
||||
// 取消/返回
|
||||
const handleCancel = () => {
|
||||
if (confirm('确定要取消吗?未保存的内容将丢失。')) {
|
||||
navigate('/admin/posts')
|
||||
}
|
||||
}
|
||||
|
||||
// 退出登录
|
||||
const handleLogout = async () => {
|
||||
localStorage.removeItem('token')
|
||||
await authApi.logout()
|
||||
localStorage.removeItem('user')
|
||||
window.location.href = '/login'
|
||||
}
|
||||
|
||||
// 输入URL界面
|
||||
if (step === 'input') {
|
||||
return (
|
||||
<AdminLayout user={user} onLogout={handleLogout}>
|
||||
<ErrorModal
|
||||
message={showErrorModal ? errorModalMessage : ''}
|
||||
onClose={() => setShowErrorModal(false)}
|
||||
onClear={() => setCrawlUrl('')}
|
||||
/>
|
||||
|
||||
<div className="p-6 w-full">
|
||||
{/* 页面标题 */}
|
||||
<div className="mb-6">
|
||||
<h1 className="text-2xl font-semibold text-gray-900">采集文章</h1>
|
||||
<p className="text-gray-500 mt-1">从网页自动采集文章内容</p>
|
||||
</div>
|
||||
|
||||
<Card>
|
||||
<CardHeader>
|
||||
<div>
|
||||
<CardTitle>从网页采集文章</CardTitle>
|
||||
<CardDescription>输入文章链接,自动提取标题、正文和图片</CardDescription>
|
||||
</div>
|
||||
</CardHeader>
|
||||
<CardBody>
|
||||
<form onSubmit={handleCrawl} className="space-y-6">
|
||||
<div>
|
||||
<Label htmlFor="url">文章链接 URL</Label>
|
||||
<Input
|
||||
id="url"
|
||||
type="url"
|
||||
value={crawlUrl}
|
||||
onChange={(e) => setCrawlUrl(e.target.value)}
|
||||
placeholder="https://example.com/article"
|
||||
disabled={crawling}
|
||||
required
|
||||
/>
|
||||
<p className="text-sm text-gray-500 mt-1">
|
||||
支持采集新闻网站、博客等公开文章
|
||||
</p>
|
||||
</div>
|
||||
|
||||
{crawlError && (
|
||||
<div className="bg-red-50 border border-red-200 rounded-lg p-4">
|
||||
<div className="flex items-center gap-2">
|
||||
<svg className="w-5 h-5 text-red-500" fill="none" viewBox="0 0 24 24" stroke="currentColor">
|
||||
<path strokeLinecap="round" strokeLinejoin="round" strokeWidth={2} d="M12 8v4m0 4h.01M21 12a9 9 0 11-18 0 9 9 0 0118 0z" />
|
||||
</svg>
|
||||
<span className="font-medium text-red-800">采集失败</span>
|
||||
</div>
|
||||
<p className="text-red-600 mt-1 text-sm">{crawlError}</p>
|
||||
</div>
|
||||
)}
|
||||
|
||||
<div className="flex gap-3">
|
||||
<Button
|
||||
type="submit"
|
||||
variant="primary"
|
||||
disabled={crawling}
|
||||
loading={crawling}
|
||||
>
|
||||
{crawling ? '采集中...' : '开始采集'}
|
||||
</Button>
|
||||
<Button
|
||||
type="button"
|
||||
variant="secondary"
|
||||
onClick={handleCancel}
|
||||
disabled={crawling}
|
||||
>
|
||||
取消
|
||||
</Button>
|
||||
</div>
|
||||
|
||||
{crawling && (
|
||||
<div className="text-center py-8">
|
||||
<div className="inline-flex items-center justify-center w-16 h-16 bg-blue-50 rounded-full mb-4">
|
||||
<svg className="animate-spin w-8 h-8 text-blue-600" viewBox="0 0 24 24" fill="none">
|
||||
<circle className="opacity-25" cx="12" cy="12" r="10" stroke="currentColor" strokeWidth="4" />
|
||||
<path className="opacity-75" fill="currentColor" d="M4 12a8 8 0 018-8V0C5.373 0 0 5.373 0 12h4z" />
|
||||
</svg>
|
||||
</div>
|
||||
<p className="text-gray-500">正在分析网页内容...</p>
|
||||
</div>
|
||||
)}
|
||||
</form>
|
||||
</CardBody>
|
||||
</Card>
|
||||
|
||||
<Card className="mt-6">
|
||||
<CardHeader>
|
||||
<div>
|
||||
<CardTitle>使用说明</CardTitle>
|
||||
<CardDescription>采集功能的使用注意事项</CardDescription>
|
||||
</div>
|
||||
</CardHeader>
|
||||
<CardBody>
|
||||
<ul className="space-y-3 text-sm text-gray-600">
|
||||
<li className="flex items-start gap-2">
|
||||
<svg className="w-5 h-5 text-blue-500 flex-shrink-0 mt-0.5" fill="none" viewBox="0 0 24 24" stroke="currentColor">
|
||||
<path strokeLinecap="round" strokeLinejoin="round" strokeWidth={2} d="M13 16h-1v-4h-1m1-4h.01M21 12a9 9 0 11-18 0 9 9 0 0118 0z" />
|
||||
</svg>
|
||||
<span>支持采集新闻网站、技术博客、学术论文等公开内容</span>
|
||||
</li>
|
||||
<li className="flex items-start gap-2">
|
||||
<svg className="w-5 h-5 text-blue-500 flex-shrink-0 mt-0.5" fill="none" viewBox="0 0 24 24" stroke="currentColor">
|
||||
<path strokeLinecap="round" strokeLinejoin="round" strokeWidth={2} d="M13 16h-1v-4h-1m1-4h.01M21 12a9 9 0 11-18 0 9 9 0 0118 0z" />
|
||||
</svg>
|
||||
<span>采集后需要人工编辑确认内容准确性</span>
|
||||
</li>
|
||||
<li className="flex items-start gap-2">
|
||||
<svg className="w-5 h-5 text-blue-500 flex-shrink-0 mt-0.5" fill="none" viewBox="0 0 24 24" stroke="currentColor">
|
||||
<path strokeLinecap="round" strokeLinejoin="round" strokeWidth={2} d="M13 16h-1v-4h-1m1-4h.01M21 12a9 9 0 11-18 0 9 9 0 0118 0z" />
|
||||
</svg>
|
||||
<span>系统会自动提取标题、正文和图片</span>
|
||||
</li>
|
||||
<li className="flex items-start gap-2">
|
||||
<svg className="w-5 h-5 text-blue-500 flex-shrink-0 mt-0.5" fill="none" viewBox="0 0 24 24" stroke="currentColor">
|
||||
<path strokeLinecap="round" strokeLinejoin="round" strokeWidth={2} d="M13 16h-1v-4h-1m1-4h.01M21 12a9 9 0 11-18 0 9 9 0 0118 0z" />
|
||||
</svg>
|
||||
<span>采集的内容默认保存为草稿,需要手动发布</span>
|
||||
</li>
|
||||
<li className="flex items-start gap-2">
|
||||
<svg className="w-5 h-5 text-blue-500 flex-shrink-0 mt-0.5" fill="none" viewBox="0 0 24 24" stroke="currentColor">
|
||||
<path strokeLinecap="round" strokeLinejoin="round" strokeWidth={2} d="M13 16h-1v-4h-1m1-4h.01M21 12a9 9 0 11-18 0 9 9 0 0118 0z" />
|
||||
</svg>
|
||||
<span>请尊重原作者版权,仅用于个人学习参考</span>
|
||||
</li>
|
||||
</ul>
|
||||
</CardBody>
|
||||
</Card>
|
||||
</div>
|
||||
</AdminLayout>
|
||||
)
|
||||
}
|
||||
|
||||
// 编辑界面
|
||||
return (
|
||||
<AdminLayout user={user} onLogout={handleLogout}>
|
||||
<div className="p-6 w-full">
|
||||
{/* 页面标题 */}
|
||||
<div className="mb-6 flex items-center justify-between">
|
||||
<div>
|
||||
<h1 className="text-2xl font-semibold text-gray-900">编辑采集内容</h1>
|
||||
<p className="text-gray-500 mt-1">确认并编辑采集的文章内容</p>
|
||||
</div>
|
||||
<div className="flex gap-3">
|
||||
<Button onClick={handleCancel} variant="secondary">
|
||||
取消
|
||||
</Button>
|
||||
<Button
|
||||
onClick={(e) => handleSubmit(e, true)}
|
||||
variant="secondary"
|
||||
disabled={saving}
|
||||
>
|
||||
{saving ? '保存中...' : '保存草稿'}
|
||||
</Button>
|
||||
<Button
|
||||
onClick={(e) => handleSubmit(e, false)}
|
||||
variant="primary"
|
||||
disabled={saving}
|
||||
>
|
||||
{saving ? '发布中...' : '发布文章'}
|
||||
</Button>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<div className="grid grid-cols-1 lg:grid-cols-3 gap-6">
|
||||
{/* 左侧:主要内容 */}
|
||||
<div className="lg:col-span-2 space-y-6">
|
||||
<Card>
|
||||
<CardHeader>
|
||||
<div>
|
||||
<CardTitle>文章内容</CardTitle>
|
||||
<CardDescription>编辑文章标题、摘要和正文</CardDescription>
|
||||
</div>
|
||||
</CardHeader>
|
||||
<CardBody className="space-y-6">
|
||||
<div>
|
||||
<Label htmlFor="title">文章标题 <span className="text-red-500">*</span></Label>
|
||||
<Input
|
||||
id="title"
|
||||
value={form.title}
|
||||
onChange={(e) => setForm({...form, title: e.target.value})}
|
||||
placeholder="请输入标题"
|
||||
required
|
||||
/>
|
||||
</div>
|
||||
|
||||
<div>
|
||||
<Label htmlFor="summary">文章摘要</Label>
|
||||
<Textarea
|
||||
id="summary"
|
||||
value={form.summary}
|
||||
onChange={(e) => setForm({...form, summary: e.target.value})}
|
||||
placeholder="简短描述文章内容(可选)"
|
||||
rows={3}
|
||||
/>
|
||||
</div>
|
||||
|
||||
<div>
|
||||
<Label htmlFor="content">正文内容 <span className="text-red-500">*</span></Label>
|
||||
<Textarea
|
||||
id="content"
|
||||
value={form.content}
|
||||
onChange={(e) => setForm({...form, content: e.target.value})}
|
||||
placeholder="支持 Markdown 格式"
|
||||
rows={20}
|
||||
required
|
||||
/>
|
||||
</div>
|
||||
</CardBody>
|
||||
</Card>
|
||||
</div>
|
||||
|
||||
{/* 右侧:设置和图片 */}
|
||||
<div className="space-y-6">
|
||||
{/* 分类和标签 */}
|
||||
<Card>
|
||||
<CardHeader>
|
||||
<div>
|
||||
<CardTitle>文章设置</CardTitle>
|
||||
<CardDescription>设置分类和标签</CardDescription>
|
||||
</div>
|
||||
</CardHeader>
|
||||
<CardBody className="space-y-4">
|
||||
<div>
|
||||
<Label htmlFor="category">分类</Label>
|
||||
<select
|
||||
id="category"
|
||||
value={form.category_id}
|
||||
onChange={(e) => setForm({...form, category_id: e.target.value})}
|
||||
className="w-full px-3 py-2 border border-gray-300 rounded-lg focus:ring-2 focus:ring-blue-500 focus:border-blue-500"
|
||||
>
|
||||
<option value="">未分类</option>
|
||||
{categories.map(cat => (
|
||||
<option key={cat.id} value={cat.id}>{cat.name}</option>
|
||||
))}
|
||||
</select>
|
||||
</div>
|
||||
|
||||
<div>
|
||||
<Label>标签</Label>
|
||||
<div className="max-h-40 overflow-y-auto border border-gray-300 rounded-lg p-3 space-y-2">
|
||||
{tags.map(tag => (
|
||||
<label key={tag.id} htmlFor={`tag-${tag.id}`} className="flex items-center gap-2 cursor-pointer hover:bg-gray-50 p-1 rounded">
|
||||
<input
|
||||
id={`tag-${tag.id}`}
|
||||
type="checkbox"
|
||||
checked={form.tag_ids.includes(tag.id)}
|
||||
onChange={(e) => {
|
||||
if (e.target.checked) {
|
||||
setForm({...form, tag_ids: [...form.tag_ids, tag.id]})
|
||||
} else {
|
||||
setForm({...form, tag_ids: form.tag_ids.filter(id => id !== tag.id)})
|
||||
}
|
||||
}}
|
||||
className="rounded border-gray-300 text-blue-600 focus:ring-blue-500"
|
||||
/>
|
||||
<span className="text-sm text-gray-700">{tag.name}</span>
|
||||
</label>
|
||||
))}
|
||||
</div>
|
||||
</div>
|
||||
</CardBody>
|
||||
</Card>
|
||||
|
||||
{/* 采集的图片 */}
|
||||
{crawledImages.length > 0 && (
|
||||
<Card>
|
||||
<CardHeader>
|
||||
<div>
|
||||
<CardTitle>采集的图片</CardTitle>
|
||||
<CardDescription>共 {crawledImages.length} 张图片,点击插入到文章</CardDescription>
|
||||
</div>
|
||||
</CardHeader>
|
||||
<CardBody>
|
||||
<div className="grid grid-cols-2 gap-3">
|
||||
{crawledImages.map((img, index) => {
|
||||
const displayUrl = img.local_path || img.original_url
|
||||
const insertUrl = img.local_path || img.original_url
|
||||
|
||||
return (
|
||||
<div key={index} className="relative group rounded-lg overflow-hidden border border-gray-200">
|
||||
<img
|
||||
src={displayUrl.startsWith('/uploads/') ? `${API_BASE_URL.replace('/api', '')}${displayUrl}` : displayUrl}
|
||||
alt={`图片${index + 1}`}
|
||||
className="w-full h-24 object-cover cursor-pointer"
|
||||
onClick={() => insertImageToContent(insertUrl)}
|
||||
/>
|
||||
<div
|
||||
className="absolute inset-0 bg-black/50 opacity-0 group-hover:opacity-100 flex items-center justify-center text-white text-xs cursor-pointer transition-opacity"
|
||||
onClick={() => insertImageToContent(insertUrl)}
|
||||
>
|
||||
点击插入
|
||||
</div>
|
||||
{img.id && (
|
||||
<div className="absolute top-1 right-1 bg-green-500 text-white text-[10px] px-1.5 py-0.5 rounded">
|
||||
✓ 已保存
|
||||
</div>
|
||||
)}
|
||||
</div>
|
||||
)
|
||||
})}
|
||||
</div>
|
||||
<p className="text-xs text-gray-500 mt-3">
|
||||
点击图片可插入到文章末尾(带✓的已保存到图库)
|
||||
</p>
|
||||
</CardBody>
|
||||
</Card>
|
||||
)}
|
||||
|
||||
{/* 来源信息 */}
|
||||
<Card>
|
||||
<CardHeader>
|
||||
<div>
|
||||
<CardTitle>来源</CardTitle>
|
||||
<CardDescription>文章来源链接</CardDescription>
|
||||
</div>
|
||||
</CardHeader>
|
||||
<CardBody>
|
||||
<a
|
||||
href={crawlUrl}
|
||||
target="_blank"
|
||||
rel="noopener noreferrer"
|
||||
className="text-sm text-blue-600 hover:text-blue-800 break-all hover:underline"
|
||||
>
|
||||
{crawlUrl}
|
||||
</a>
|
||||
</CardBody>
|
||||
</Card>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
</AdminLayout>
|
||||
)
|
||||
}
|
||||
|
||||
export default CrawlEdit
|
||||
@@ -0,0 +1,299 @@
|
||||
// 控制台首页 - Preline UI 风格
|
||||
import { useState, useEffect } from 'react'
|
||||
import { AdminLayout } from '../components-preline/Sidebar'
|
||||
import { authApi } from '../api/auth'
|
||||
import { Card, CardHeader, CardTitle, CardDescription, CardBody } from '../components-preline/Card'
|
||||
import { Button } from '../components-preline/Button'
|
||||
import { postsApi } from '../api/posts'
|
||||
|
||||
// 统计卡片 - Preline 风格
|
||||
function StatCard({ title, value, icon, trend, trendUp }) {
|
||||
return (
|
||||
<div className="bg-white rounded-xl p-6 border border-gray-200 shadow-sm hover:shadow-md transition-shadow duration-200">
|
||||
<div className="flex items-start justify-between">
|
||||
<div>
|
||||
<p className="text-sm font-medium text-gray-500">{title}</p>
|
||||
<p className="text-3xl font-bold text-gray-900 mt-2">{value}</p>
|
||||
{trend && (
|
||||
<div className={`flex items-center gap-1 mt-2 text-sm ${trendUp ? 'text-green-600' : 'text-red-600'}`}>
|
||||
<svg className="w-4 h-4" fill="none" viewBox="0 0 24 24" stroke="currentColor">
|
||||
<path strokeLinecap="round" strokeLinejoin="round" strokeWidth={2} d={trendUp ? "M5 10l7-7m0 0l7 7m-7-7v18" : "M19 14l-7 7m0 0l-7-7m7 7V3"} />
|
||||
</svg>
|
||||
<span>{trend}</span>
|
||||
</div>
|
||||
)}
|
||||
</div>
|
||||
<div className="w-12 h-12 bg-blue-50 rounded-xl flex items-center justify-center text-2xl">
|
||||
{icon}
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
)
|
||||
}
|
||||
|
||||
// 最近文章列表项
|
||||
function RecentPostItem({ post }) {
|
||||
return (
|
||||
<div className="flex items-center justify-between py-3 border-b border-gray-100 last:border-0 hover:bg-gray-50 px-2 -mx-2 rounded-lg transition-colors">
|
||||
<div className="flex-1 min-w-0 mr-4">
|
||||
<p className="font-medium text-gray-900 truncate">{post.title}</p>
|
||||
<p className="text-sm text-gray-500 mt-0.5">
|
||||
{new Date(post.created_at).toLocaleDateString('zh-CN')} · {post.category?.name || '未分类'}
|
||||
</p>
|
||||
</div>
|
||||
<div className="flex items-center gap-3">
|
||||
<span className="inline-flex items-center gap-1 text-sm text-gray-500">
|
||||
<svg className="w-4 h-4" fill="none" viewBox="0 0 24 24" stroke="currentColor">
|
||||
<path strokeLinecap="round" strokeLinejoin="round" strokeWidth={2} d="M15 12a3 3 0 11-6 0 3 3 0 016 0z" />
|
||||
<path strokeLinecap="round" strokeLinejoin="round" strokeWidth={2} d="M2.458 12C3.732 7.943 7.523 5 12 5c4.478 0 8.268 2.943 9.542 7-1.274 4.057-5.064 7-9.542 7-4.477 0-8.268-2.943-9.542-7z" />
|
||||
</svg>
|
||||
{post.view_count || 0}
|
||||
</span>
|
||||
<span className={`inline-flex items-center px-2 py-0.5 rounded-full text-xs font-medium ${
|
||||
post.is_published ? 'bg-green-100 text-green-800' : 'bg-yellow-100 text-yellow-800'
|
||||
}`}>
|
||||
{post.is_published ? '已发布' : '草稿'}
|
||||
</span>
|
||||
</div>
|
||||
</div>
|
||||
)
|
||||
}
|
||||
|
||||
// 分类统计项
|
||||
function CategoryStatItem({ name, count, total }) {
|
||||
const percentage = total > 0 ? Math.round((count / total) * 100) : 0
|
||||
|
||||
return (
|
||||
<div className="py-3 border-b border-gray-100 last:border-0">
|
||||
<div className="flex items-center justify-between mb-2">
|
||||
<span className="font-medium text-gray-700">{name}</span>
|
||||
<div className="flex items-center gap-3">
|
||||
<span className="text-sm text-gray-500">{count} 篇</span>
|
||||
<span className="text-sm font-medium text-gray-900 w-10 text-right">{percentage}%</span>
|
||||
</div>
|
||||
</div>
|
||||
<div className="w-full bg-gray-100 rounded-full h-2">
|
||||
<div
|
||||
className="bg-blue-600 h-2 rounded-full transition-all duration-500"
|
||||
style={{ width: `${percentage}%` }}
|
||||
/>
|
||||
</div>
|
||||
</div>
|
||||
)
|
||||
}
|
||||
|
||||
export function Dashboard() {
|
||||
const [stats, setStats] = useState({
|
||||
total_posts: 0,
|
||||
total_views: 0,
|
||||
category_counts: {}
|
||||
})
|
||||
const [recentPosts, setRecentPosts] = useState([])
|
||||
const [loading, setLoading] = useState(true)
|
||||
|
||||
// 获取当前用户信息
|
||||
const user = JSON.parse(localStorage.getItem('user') || '{}')
|
||||
|
||||
useEffect(() => {
|
||||
fetchData()
|
||||
}, [])
|
||||
|
||||
const fetchData = async () => {
|
||||
try {
|
||||
// 获取统计
|
||||
const statsRes = await postsApi.getStats()
|
||||
setStats(statsRes.data)
|
||||
|
||||
// 获取最近文章
|
||||
const postsRes = await postsApi.getPosts({ limit: 5 })
|
||||
setRecentPosts(postsRes.data)
|
||||
} catch (error) {
|
||||
console.error('获取数据失败:', error)
|
||||
} finally {
|
||||
setLoading(false)
|
||||
}
|
||||
}
|
||||
|
||||
const handleLogout = async () => {
|
||||
localStorage.removeItem('token')
|
||||
await authApi.logout()
|
||||
localStorage.removeItem('user')
|
||||
window.location.href = '/login'
|
||||
}
|
||||
|
||||
// 计算总文章数用于百分比
|
||||
const totalPosts = stats.total_posts || 1
|
||||
|
||||
return (
|
||||
<AdminLayout user={user} onLogout={handleLogout}>
|
||||
<div className="p-6 w-full">
|
||||
{/* 页面标题 */}
|
||||
<div className="mb-8">
|
||||
<h1 className="text-2xl font-semibold text-gray-900">控制台</h1>
|
||||
<p className="text-gray-500 mt-1">欢迎回来,{user.username || '管理员'}!这是您的博客概览</p>
|
||||
</div>
|
||||
|
||||
{/* 统计卡片 */}
|
||||
<div className="grid grid-cols-1 sm:grid-cols-2 lg:grid-cols-4 gap-6 mb-8">
|
||||
<StatCard
|
||||
title="总文章数"
|
||||
value={stats.total_posts}
|
||||
icon="📝"
|
||||
trend="+2 本周"
|
||||
trendUp={true}
|
||||
/>
|
||||
<StatCard
|
||||
title="总浏览量"
|
||||
value={stats.total_views?.toLocaleString() || 0}
|
||||
icon="👁️"
|
||||
trend="+12%"
|
||||
trendUp={true}
|
||||
/>
|
||||
<StatCard
|
||||
title="分类数"
|
||||
value={Object.keys(stats.category_counts).length}
|
||||
icon="📁"
|
||||
/>
|
||||
<StatCard
|
||||
title="今日访问"
|
||||
value="--"
|
||||
icon="📈"
|
||||
/>
|
||||
</div>
|
||||
|
||||
<div className="grid grid-cols-1 lg:grid-cols-3 gap-6">
|
||||
{/* 最近文章 */}
|
||||
<div className="lg:col-span-2">
|
||||
<Card>
|
||||
<CardHeader
|
||||
action={
|
||||
<Button
|
||||
variant="secondary"
|
||||
size="sm"
|
||||
onClick={() => window.location.href = '/admin/posts/new'}
|
||||
>
|
||||
<svg className="w-4 h-4" fill="none" viewBox="0 0 24 24" stroke="currentColor">
|
||||
<path strokeLinecap="round" strokeLinejoin="round" strokeWidth={2} d="M12 4v16m8-8H4" />
|
||||
</svg>
|
||||
写文章
|
||||
</Button>
|
||||
}
|
||||
>
|
||||
<div>
|
||||
<CardTitle>最近文章</CardTitle>
|
||||
<CardDescription>最近发布的 5 篇文章</CardDescription>
|
||||
</div>
|
||||
</CardHeader>
|
||||
<CardBody>
|
||||
{loading ? (
|
||||
<div className="flex items-center justify-center py-12">
|
||||
<svg className="animate-spin h-5 w-5 text-gray-400" viewBox="0 0 24 24" fill="none">
|
||||
<circle className="opacity-25" cx="12" cy="12" r="10" stroke="currentColor" strokeWidth="4" />
|
||||
<path className="opacity-75" fill="currentColor" d="M4 12a8 8 0 018-8V0C5.373 0 0 5.373 0 12h4z" />
|
||||
</svg>
|
||||
<span className="ml-2 text-gray-500">加载中...</span>
|
||||
</div>
|
||||
) : recentPosts.length === 0 ? (
|
||||
<div className="text-center py-12">
|
||||
<div className="w-12 h-12 bg-gray-100 rounded-full flex items-center justify-center mx-auto mb-3">
|
||||
<svg className="w-6 h-6 text-gray-400" fill="none" viewBox="0 0 24 24" stroke="currentColor">
|
||||
<path strokeLinecap="round" strokeLinejoin="round" strokeWidth={2} d="M9 12h6m-6 4h6m2 5H7a2 2 0 01-2-2V5a2 2 0 012-2h5.586a1 1 0 01.707.293l5.414 5.414a1 1 0 01.293.707V19a2 2 0 01-2 2z" />
|
||||
</svg>
|
||||
</div>
|
||||
<p className="text-gray-500">暂无文章</p>
|
||||
<Button
|
||||
variant="primary"
|
||||
size="sm"
|
||||
className="mt-3"
|
||||
onClick={() => window.location.href = '/admin/posts/new'}
|
||||
>
|
||||
创建第一篇文章
|
||||
</Button>
|
||||
</div>
|
||||
) : (
|
||||
<div className="divide-y divide-gray-100">
|
||||
{recentPosts.map(post => (
|
||||
<RecentPostItem key={post.id} post={post} />
|
||||
))}
|
||||
</div>
|
||||
)}
|
||||
</CardBody>
|
||||
</Card>
|
||||
</div>
|
||||
|
||||
{/* 分类统计 */}
|
||||
<div>
|
||||
<Card>
|
||||
<CardHeader>
|
||||
<div>
|
||||
<CardTitle>分类统计</CardTitle>
|
||||
<CardDescription>各分类文章数量分布</CardDescription>
|
||||
</div>
|
||||
</CardHeader>
|
||||
<CardBody>
|
||||
{Object.keys(stats.category_counts).length === 0 ? (
|
||||
<div className="text-center py-8">
|
||||
<p className="text-gray-500 text-sm">暂无分类数据</p>
|
||||
</div>
|
||||
) : (
|
||||
<div>
|
||||
{Object.entries(stats.category_counts).map(([name, count]) => (
|
||||
<CategoryStatItem
|
||||
key={name}
|
||||
name={name}
|
||||
count={count}
|
||||
total={totalPosts}
|
||||
/>
|
||||
))}
|
||||
</div>
|
||||
)}
|
||||
</CardBody>
|
||||
</Card>
|
||||
|
||||
{/* 快捷操作 */}
|
||||
<Card className="mt-6">
|
||||
<CardHeader>
|
||||
<CardTitle>快捷操作</CardTitle>
|
||||
</CardHeader>
|
||||
<CardBody className="space-y-2">
|
||||
<Button
|
||||
variant="secondary"
|
||||
className="w-full justify-start"
|
||||
onClick={() => window.location.href = '/admin/posts'}
|
||||
>
|
||||
<svg className="w-4 h-4 mr-2" fill="none" viewBox="0 0 24 24" stroke="currentColor">
|
||||
<path strokeLinecap="round" strokeLinejoin="round" strokeWidth={2} d="M9 12h6m-6 4h6m2 5H7a2 2 0 01-2-2V5a2 2 0 012-2h5.586a1 1 0 01.707.293l5.414 5.414a1 1 0 01.293.707V19a2 2 0 01-2 2z" />
|
||||
</svg>
|
||||
管理文章
|
||||
</Button>
|
||||
<Button
|
||||
variant="secondary"
|
||||
className="w-full justify-start"
|
||||
onClick={() => window.location.href = '/admin/categories'}
|
||||
>
|
||||
<svg className="w-4 h-4 mr-2" fill="none" viewBox="0 0 24 24" stroke="currentColor">
|
||||
<path strokeLinecap="round" strokeLinejoin="round" strokeWidth={2} d="M3 7v10a2 2 0 002 2h14a2 2 0 002-2V9a2 2 0 00-2-2h-6l-2-2H5a2 2 0 00-2 2z" />
|
||||
</svg>
|
||||
管理分类
|
||||
</Button>
|
||||
<Button
|
||||
variant="secondary"
|
||||
className="w-full justify-start"
|
||||
onClick={() => window.location.href = '/admin/settings'}
|
||||
>
|
||||
<svg className="w-4 h-4 mr-2" fill="none" viewBox="0 0 24 24" stroke="currentColor">
|
||||
<path strokeLinecap="round" strokeLinejoin="round" strokeWidth={2} d="M10.325 4.317c.426-1.756 2.924-1.756 3.35 0a1.724 1.724 0 002.573 1.066c1.543-.94 3.31.826 2.37 2.37a1.724 1.724 0 001.065 2.572c1.756.426 1.756 2.924 0 3.35a1.724 1.724 0 00-1.066 2.573c.94 1.543-.826 3.31-2.37 2.37a1.724 1.724 0 00-2.572 1.065c-.426 1.756-2.924 1.756-3.35 0a1.724 1.724 0 00-2.573-1.066c-1.543.94-3.31-.826-2.37-2.37a1.724 1.724 0 00-1.065-2.572c-1.756-.426-1.756-2.924 0-3.35a1.724 1.724 0 001.066-2.573c-.94-1.543.826-3.31 2.37-2.37.996.608 2.296.07 2.572-1.065z" />
|
||||
<path strokeLinecap="round" strokeLinejoin="round" strokeWidth={2} d="M15 12a3 3 0 11-6 0 3 3 0 016 0z" />
|
||||
</svg>
|
||||
系统设置
|
||||
</Button>
|
||||
</CardBody>
|
||||
</Card>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
</AdminLayout>
|
||||
)
|
||||
}
|
||||
|
||||
export default Dashboard
|
||||
@@ -0,0 +1,462 @@
|
||||
// 访客首页 - 展示文章列表(支持无限滚动)
|
||||
import { useState, useEffect, useRef, useCallback } from 'react'
|
||||
import { Link } from 'react-router-dom'
|
||||
import { API_BASE_URL } from '../api/config'
|
||||
|
||||
const POSTS_PER_PAGE = 10 // 每页加载数量
|
||||
|
||||
export function Home() {
|
||||
const [posts, setPosts] = useState([])
|
||||
const [categories, setCategories] = useState([])
|
||||
const [selectedCategory, setSelectedCategory] = useState(null)
|
||||
const [settings, setSettings] = useState({
|
||||
blog_name: '侘寂屋',
|
||||
welcome_message: '欢迎来到侘寂屋 👋 分享技术、生活与思考',
|
||||
banner_type: 'text',
|
||||
layout: 'card' // card 或 list
|
||||
})
|
||||
const [loading, setLoading] = useState(false)
|
||||
const [initialLoading, setInitialLoading] = useState(true)
|
||||
const [error, setError] = useState(null)
|
||||
const [showMoreCategories, setShowMoreCategories] = useState(false)
|
||||
const [visibleCatCount, setVisibleCatCount] = useState(null) // null=未测量, number=能显示的分类数(不含"全部")
|
||||
const navRowRef = useRef(null)
|
||||
|
||||
// 动态测量分类导航:宽度不溢出就不折叠
|
||||
useEffect(() => {
|
||||
if (categories.length === 0) return
|
||||
|
||||
let timeoutId
|
||||
const measure = () => {
|
||||
const row = navRowRef.current
|
||||
if (!row) return
|
||||
// 导航容器跟正文内容区一样宽 (max-w-[1366px] mx-auto px-4)
|
||||
const containerWidth = row.parentElement?.clientWidth
|
||||
if (!containerWidth) return
|
||||
|
||||
const buttons = row.querySelectorAll('.cat-nav-btn')
|
||||
if (buttons.length === 0) return
|
||||
|
||||
// 预留 "更多" 按钮宽度 + gap
|
||||
const MORE_RESERVE = 52 // 约等于 ⋮ 按钮宽度 + gap
|
||||
const GAP = 8
|
||||
|
||||
let total = 0
|
||||
for (let i = 0; i < buttons.length; i++) {
|
||||
const btnW = buttons[i].offsetWidth + (i > 0 ? GAP : 0)
|
||||
const remainingAfter = (i < buttons.length - 1) ? total + btnW + GAP + MORE_RESERVE : total + btnW
|
||||
if (remainingAfter > containerWidth) {
|
||||
// 第 i 个及之后的放不进,前 i 个可见(i 包含了"全部"按钮,所以可见分类数 = i - 1)
|
||||
setVisibleCatCount(Math.max(0, i - 1))
|
||||
return
|
||||
}
|
||||
total += btnW
|
||||
}
|
||||
setVisibleCatCount(categories.length) // 全部能放下
|
||||
}
|
||||
|
||||
// 延迟测量等 DOM 渲染完成
|
||||
timeoutId = setTimeout(measure, 100)
|
||||
|
||||
const ro = new ResizeObserver(() => {
|
||||
clearTimeout(timeoutId)
|
||||
timeoutId = setTimeout(measure, 100)
|
||||
})
|
||||
const parent = navRowRef.current?.parentElement
|
||||
if (parent) ro.observe(parent)
|
||||
|
||||
window.addEventListener('resize', measure)
|
||||
return () => {
|
||||
clearTimeout(timeoutId)
|
||||
ro.disconnect()
|
||||
window.removeEventListener('resize', measure)
|
||||
}
|
||||
}, [categories])
|
||||
|
||||
// 分页状态
|
||||
const [page, setPage] = useState(0)
|
||||
const [hasMore, setHasMore] = useState(true)
|
||||
|
||||
// 用于无限滚动的 ref
|
||||
const observerRef = useRef(null)
|
||||
const loadMoreRef = useRef(null)
|
||||
|
||||
useEffect(() => {
|
||||
fetchCategories()
|
||||
fetchSettings()
|
||||
// 初始加载第一页
|
||||
fetchPosts(0, null, true)
|
||||
}, [])
|
||||
|
||||
// 当分类变化时,重置并重新加载
|
||||
useEffect(() => {
|
||||
setPosts([])
|
||||
setPage(0)
|
||||
setHasMore(true)
|
||||
fetchPosts(0, selectedCategory, true)
|
||||
}, [selectedCategory])
|
||||
|
||||
const fetchPosts = async (pageNum = 0, categoryId = null, isInitial = false) => {
|
||||
try {
|
||||
if (isInitial) {
|
||||
setInitialLoading(true)
|
||||
} else {
|
||||
setLoading(true)
|
||||
}
|
||||
|
||||
const skip = pageNum * POSTS_PER_PAGE
|
||||
let url = `${API_BASE_URL}/posts?skip=${skip}&limit=${POSTS_PER_PAGE}`
|
||||
if (categoryId) {
|
||||
url += `&category_id=${categoryId}`
|
||||
}
|
||||
|
||||
const response = await fetch(url)
|
||||
if (!response.ok) throw new Error('获取文章失败')
|
||||
const data = await response.json()
|
||||
|
||||
const publishedPosts = data.filter(p => p.is_published)
|
||||
|
||||
// 如果返回的数量少于每页数量,说明没有更多数据了
|
||||
if (publishedPosts.length < POSTS_PER_PAGE) {
|
||||
setHasMore(false)
|
||||
}
|
||||
|
||||
if (pageNum === 0) {
|
||||
// 第一页:替换数据
|
||||
setPosts(publishedPosts)
|
||||
} else {
|
||||
// 后续页:追加数据
|
||||
setPosts(prev => {
|
||||
// 去重:避免重复添加已存在的文章
|
||||
const existingIds = new Set(prev.map(p => p.id))
|
||||
const newPosts = publishedPosts.filter(p => !existingIds.has(p.id))
|
||||
return [...prev, ...newPosts]
|
||||
})
|
||||
}
|
||||
} catch (err) {
|
||||
setError(err.message)
|
||||
} finally {
|
||||
setLoading(false)
|
||||
setInitialLoading(false)
|
||||
}
|
||||
}
|
||||
|
||||
// 加载更多
|
||||
const loadMore = useCallback(() => {
|
||||
if (loading || !hasMore) return
|
||||
const nextPage = page + 1
|
||||
setPage(nextPage)
|
||||
fetchPosts(nextPage, selectedCategory, false)
|
||||
}, [page, loading, hasMore, selectedCategory])
|
||||
|
||||
// 无限滚动:使用 Intersection Observer
|
||||
useEffect(() => {
|
||||
if (initialLoading) return
|
||||
|
||||
const observer = new IntersectionObserver(
|
||||
(entries) => {
|
||||
if (entries[0].isIntersecting && hasMore && !loading) {
|
||||
loadMore()
|
||||
}
|
||||
},
|
||||
{ threshold: 0.1, rootMargin: '100px' }
|
||||
)
|
||||
|
||||
if (loadMoreRef.current) {
|
||||
observer.observe(loadMoreRef.current)
|
||||
}
|
||||
|
||||
return () => observer.disconnect()
|
||||
}, [initialLoading, hasMore, loading, loadMore])
|
||||
|
||||
const fetchCategories = async () => {
|
||||
try {
|
||||
const response = await fetch(`${API_BASE_URL}/categories`)
|
||||
if (response.ok) {
|
||||
const data = await response.json()
|
||||
setCategories(data)
|
||||
}
|
||||
} catch (err) {
|
||||
console.error('获取分类失败:', err)
|
||||
}
|
||||
}
|
||||
|
||||
const fetchSettings = async () => {
|
||||
try {
|
||||
const response = await fetch(`${API_BASE_URL}/settings`)
|
||||
if (response.ok) {
|
||||
const data = await response.json()
|
||||
setSettings(data)
|
||||
}
|
||||
} catch (err) {
|
||||
console.error('获取设置失败:', err)
|
||||
}
|
||||
}
|
||||
|
||||
// 处理分类点击
|
||||
const handleCategoryClick = (categoryId) => {
|
||||
setSelectedCategory(categoryId)
|
||||
setShowMoreCategories(false)
|
||||
// 分类变化时会触发 useEffect 自动加载
|
||||
}
|
||||
|
||||
// 显示全部文章
|
||||
const handleShowAll = () => {
|
||||
setSelectedCategory(null)
|
||||
// 重置分页状态
|
||||
setPosts([])
|
||||
setPage(0)
|
||||
setHasMore(true)
|
||||
}
|
||||
|
||||
// 动态可见分类(基于宽度测量,不溢出就不折叠)
|
||||
const isMeasured = visibleCatCount !== null
|
||||
const displayCategories = isMeasured ? categories.slice(0, visibleCatCount) : categories
|
||||
const moreCategories = isMeasured ? categories.slice(visibleCatCount) : []
|
||||
const hasMoreCategories = moreCategories.length > 0
|
||||
|
||||
if (initialLoading) return (
|
||||
<div className="min-h-screen flex items-center justify-center bg-[#FEF9E7]">
|
||||
<div className="text-center">
|
||||
<div className="w-12 h-12 border-4 border-black border-t-transparent rounded-full animate-spin mx-auto mb-4"></div>
|
||||
<p className="font-bold text-lg">加载中...</p>
|
||||
</div>
|
||||
</div>
|
||||
)
|
||||
if (error) return <div className="min-h-screen flex items-center justify-center text-red-500 bg-[#FEF9E7]">{error}</div>
|
||||
|
||||
return (
|
||||
<div className="min-h-screen bg-[#FEF9E7] flex flex-col">
|
||||
{/* 顶部导航 */}
|
||||
<nav className="bg-white border-b-2 border-black sticky top-0 z-10">
|
||||
<div className="max-w-[1366px] mx-auto px-4">
|
||||
{/* 第一行:博客名 + 管理后台 */}
|
||||
<div className="py-4 flex justify-between items-center border-b border-gray-100">
|
||||
<button
|
||||
onClick={handleShowAll}
|
||||
className="text-2xl font-black tracking-tight hover:text-blue-600 transition-colors flex items-center gap-2"
|
||||
>
|
||||
<img src="/logo-48.png" alt="logo" className="w-12 h-12" />
|
||||
{settings.blog_name || '侘寂屋'}
|
||||
</button>
|
||||
<Link
|
||||
to="/admin"
|
||||
className="px-4 py-2 border-2 border-black bg-white hover:bg-gray-100 transition-colors font-bold"
|
||||
>
|
||||
管理后台
|
||||
</Link>
|
||||
</div>
|
||||
|
||||
{/* 第二行:分类导航 */}
|
||||
{categories.length > 0 && (
|
||||
<div ref={navRowRef} className="py-3 flex items-center gap-2 flex-wrap">
|
||||
<button
|
||||
onClick={handleShowAll}
|
||||
className={`cat-nav-btn px-3 py-1.5 text-sm font-bold border-2 border-black transition-all whitespace-nowrap ${
|
||||
selectedCategory === null
|
||||
? 'bg-black text-white'
|
||||
: 'bg-white hover:bg-gray-100'
|
||||
}`}
|
||||
>
|
||||
全部
|
||||
</button>
|
||||
|
||||
{displayCategories.map(cat => (
|
||||
<button
|
||||
key={cat.id}
|
||||
onClick={() => handleCategoryClick(cat.id)}
|
||||
className={`cat-nav-btn px-3 py-1.5 text-sm font-bold border-2 border-black transition-all whitespace-nowrap ${
|
||||
selectedCategory === cat.id
|
||||
? 'bg-black text-white'
|
||||
: 'bg-white hover:bg-gray-100'
|
||||
}`}
|
||||
>
|
||||
{cat.name}
|
||||
{cat.post_count > 0 && (
|
||||
<span className={`ml-1 text-xs ${selectedCategory === cat.id ? 'text-gray-300' : 'text-gray-500'}`}>
|
||||
({cat.post_count})
|
||||
</span>
|
||||
)}
|
||||
</button>
|
||||
))}
|
||||
|
||||
{/* 更多分类下拉菜单 */}
|
||||
{hasMoreCategories && (
|
||||
<div className="relative">
|
||||
<button
|
||||
onClick={() => setShowMoreCategories(!showMoreCategories)}
|
||||
className={`px-3 py-1.5 text-sm font-bold border-2 border-black transition-all ${
|
||||
showMoreCategories
|
||||
? 'bg-black text-white'
|
||||
: 'bg-white hover:bg-gray-100'
|
||||
}`}
|
||||
>
|
||||
⋮
|
||||
</button>
|
||||
|
||||
{showMoreCategories && (
|
||||
<>
|
||||
{/* 点击外部关闭 */}
|
||||
<div
|
||||
className="fixed inset-0 z-10"
|
||||
onClick={() => setShowMoreCategories(false)}
|
||||
/>
|
||||
{/* 下拉菜单 */}
|
||||
<div className="absolute top-full left-0 mt-2 w-48 bg-white border-2 border-black shadow-[4px_4px_0px_0px_rgba(0,0,0,1)] z-20">
|
||||
{moreCategories.map(cat => (
|
||||
<button
|
||||
key={cat.id}
|
||||
onClick={() => handleCategoryClick(cat.id)}
|
||||
className={`w-full text-left px-4 py-2 text-sm font-bold border-b border-gray-100 last:border-b-0 transition-colors ${
|
||||
selectedCategory === cat.id
|
||||
? 'bg-brutal-yellow'
|
||||
: 'hover:bg-gray-50'
|
||||
}`}
|
||||
>
|
||||
{cat.name}
|
||||
{cat.post_count > 0 && (
|
||||
<span className="ml-1 text-xs text-gray-500">
|
||||
({cat.post_count})
|
||||
</span>
|
||||
)}
|
||||
</button>
|
||||
))}
|
||||
</div>
|
||||
</>
|
||||
)}
|
||||
</div>
|
||||
)}
|
||||
</div>
|
||||
)}
|
||||
</div>
|
||||
</nav>
|
||||
|
||||
{/* 主要内容 */}
|
||||
<main className="flex-1 max-w-[1366px] mx-auto px-4 py-8 w-full">
|
||||
{/* 欢迎区域 */}
|
||||
{settings.banner_type === 'text' && selectedCategory === null && (
|
||||
<div className="mb-10 p-8 bg-gradient-to-r from-yellow-200 via-cyan-200 to-pink-200 border-2 border-black shadow-[4px_4px_0px_0px_rgba(0,0,0,1)]">
|
||||
<h1 className="text-3xl md:text-4xl font-black mb-3 text-center">
|
||||
{settings.welcome_message?.split('👋')[0]?.trim() || '欢迎来到侘寂屋'}
|
||||
{settings.welcome_message?.includes('👋') && <span className="inline-block ml-2">👋</span>}
|
||||
</h1>
|
||||
{settings.welcome_message?.split('👋')[1] && (
|
||||
<p className="text-lg text-gray-800 text-center">
|
||||
{settings.welcome_message.split('👋')[1].trim()}
|
||||
</p>
|
||||
)}
|
||||
</div>
|
||||
)}
|
||||
|
||||
{/* 当前筛选提示 */}
|
||||
{selectedCategory !== null && (
|
||||
<div className="mb-6 flex items-center justify-between p-4 bg-brutal-yellow border-2 border-black">
|
||||
<span className="font-bold">
|
||||
当前分类:{categories.find(c => c.id === selectedCategory)?.name}
|
||||
</span>
|
||||
<button
|
||||
onClick={handleShowAll}
|
||||
className="text-sm underline hover:no-underline"
|
||||
>
|
||||
查看全部 →
|
||||
</button>
|
||||
</div>
|
||||
)}
|
||||
|
||||
{/* 文章列表 */}
|
||||
<div className="space-y-6">
|
||||
<h2 className="text-2xl font-black border-b-2 border-black pb-2">
|
||||
{selectedCategory !== null ? '分类文章' : '最新文章'}
|
||||
</h2>
|
||||
|
||||
{posts.length === 0 ? (
|
||||
<div className="text-center py-10 text-gray-500">
|
||||
{selectedCategory !== null
|
||||
? '该分类暂无文章'
|
||||
: '暂无文章'}
|
||||
</div>
|
||||
) : (
|
||||
/* 列表 = 单列,卡片 = 双列网格 */
|
||||
<div className={settings.layout === 'card'
|
||||
? 'grid grid-cols-1 md:grid-cols-2 gap-6'
|
||||
: 'space-y-6'
|
||||
}>
|
||||
{posts.map(post => (
|
||||
<article
|
||||
key={post.id}
|
||||
className="bg-white border-2 border-black p-6 shadow-[4px_4px_0px_0px_rgba(0,0,0,1)] hover:translate-x-[2px] hover:translate-y-[2px] hover:shadow-[2px_2px_0px_0px_rgba(0,0,0,1)] transition-all flex flex-col"
|
||||
>
|
||||
{/* 标题 */}
|
||||
<Link to={`/post/${post.slug || post.id}`}>
|
||||
<h3 className="text-xl font-bold mb-2 hover:text-blue-600 transition-colors line-clamp-2">
|
||||
{post.title}
|
||||
</h3>
|
||||
</Link>
|
||||
|
||||
{/* 摘要 */}
|
||||
<p className="text-gray-600 mb-4 line-clamp-2 flex-1">
|
||||
{post.summary}
|
||||
</p>
|
||||
|
||||
{/* 元信息 */}
|
||||
<div className="flex items-center justify-between text-sm text-gray-500">
|
||||
<div className="flex items-center gap-2 flex-wrap">
|
||||
<span>{new Date(post.created_at).toLocaleDateString('zh-CN')}</span>
|
||||
{post.category && (
|
||||
<>
|
||||
<span className="hidden sm:inline">·</span>
|
||||
<button
|
||||
onClick={() => handleCategoryClick(post.category.id)}
|
||||
className="text-blue-600 hover:underline px-2 py-0.5 bg-blue-50 border border-blue-200 rounded text-xs"
|
||||
>
|
||||
{post.category.name}
|
||||
</button>
|
||||
</>
|
||||
)}
|
||||
</div>
|
||||
<Link
|
||||
to={`/post/${post.slug || post.id}`}
|
||||
className="text-blue-600 hover:underline font-bold whitespace-nowrap ml-2"
|
||||
>
|
||||
阅读更多 →
|
||||
</Link>
|
||||
</div>
|
||||
</article>
|
||||
))}
|
||||
</div>
|
||||
)}
|
||||
|
||||
{/* 加载更多触发器 + 状态显示 */}
|
||||
<div ref={loadMoreRef} className="py-8 text-center">
|
||||
{loading && posts.length > 0 && (
|
||||
<div className="flex items-center justify-center gap-2">
|
||||
<div className="w-5 h-5 border-2 border-black border-t-transparent rounded-full animate-spin"></div>
|
||||
<span className="text-sm font-medium text-gray-600">加载更多...</span>
|
||||
</div>
|
||||
)}
|
||||
{!hasMore && posts.length > 0 && (
|
||||
<div className="text-sm text-gray-500">
|
||||
已经到底了,共 {posts.length} 篇文章
|
||||
</div>
|
||||
)}
|
||||
{hasMore && !loading && posts.length >= POSTS_PER_PAGE && (
|
||||
<button
|
||||
onClick={loadMore}
|
||||
className="px-6 py-2 bg-white border-2 border-black font-bold text-sm shadow-[2px_2px_0px_0px_rgba(0,0,0,1)] hover:shadow-none hover:translate-x-[1px] hover:translate-y-[1px] transition-all"
|
||||
>
|
||||
加载更多 ↓
|
||||
</button>
|
||||
)}
|
||||
</div>
|
||||
</div>
|
||||
</main>
|
||||
|
||||
{/* 页脚 */}
|
||||
<footer className="border-t-2 border-black bg-white">
|
||||
<div className="max-w-[1366px] mx-auto px-4 py-6 text-center text-gray-600">
|
||||
© 2026 {settings.blog_name || '侘寂屋'} · 用心记录每一刻
|
||||
</div>
|
||||
</footer>
|
||||
</div>
|
||||
)
|
||||
}
|
||||
@@ -0,0 +1,169 @@
|
||||
// 登录页面 - Preline UI 风格
|
||||
import { useState, useEffect } from 'react'
|
||||
import { useNavigate } from 'react-router-dom'
|
||||
import { Card } from '../components-preline/Card'
|
||||
import { Button } from '../components-preline/Button'
|
||||
import { Input, Label } from '../components-preline/Input'
|
||||
import { authApi } from '../api/auth'
|
||||
|
||||
export function Login() {
|
||||
const [username, setUsername] = useState('admin')
|
||||
const [password, setPassword] = useState('')
|
||||
const [error, setError] = useState('')
|
||||
const [loading, setLoading] = useState(false)
|
||||
const navigate = useNavigate()
|
||||
|
||||
// 自动检测:如果已有本地 token,或 SSO Cookie 已登录,则跳转
|
||||
useEffect(() => {
|
||||
const token = localStorage.getItem('token')
|
||||
if (token) {
|
||||
navigate('/admin')
|
||||
return
|
||||
}
|
||||
// 无本地 token 时,尝试用 SSO Cookie 调用 /api/auth/me
|
||||
authApi.getMe()
|
||||
.then(() => navigate('/admin'))
|
||||
.catch(() => {
|
||||
// SSO 也未登录,留在登录页
|
||||
})
|
||||
}, [navigate])
|
||||
|
||||
const handleSubmit = async (e) => {
|
||||
e.preventDefault()
|
||||
setError('')
|
||||
setLoading(true)
|
||||
|
||||
try {
|
||||
const response = await authApi.login(username, password)
|
||||
localStorage.setItem('token', response.data.access_token)
|
||||
localStorage.setItem('user', JSON.stringify({ username }))
|
||||
navigate('/admin')
|
||||
} catch (err) {
|
||||
setError(err.response?.data?.detail || '登录失败')
|
||||
} finally {
|
||||
setLoading(false)
|
||||
}
|
||||
}
|
||||
|
||||
const handleSSOLogin = () => {
|
||||
// 跳转到 SSO 中心,携带 redirect 参数
|
||||
const redirect = window.location.origin
|
||||
window.location.href = `http://129.211.173.87:9000/?redirect=${encodeURIComponent(redirect + '/admin')}`
|
||||
}
|
||||
|
||||
return (
|
||||
<div className="min-h-screen bg-gradient-to-br from-blue-50 to-indigo-100 flex items-center justify-center p-4">
|
||||
<div className="w-full max-w-md">
|
||||
{/* Logo */}
|
||||
<div className="text-center mb-8">
|
||||
<div className="inline-flex items-center justify-center w-16 h-16 bg-blue-600 rounded-2xl shadow-lg mb-4">
|
||||
<svg className="w-8 h-8 text-white" fill="none" viewBox="0 0 24 24" stroke="currentColor">
|
||||
<path strokeLinecap="round" strokeLinejoin="round" strokeWidth={2} d="M11 5H6a2 2 0 00-2 2v11a2 2 0 002 2h11a2 2 0 002-2v-5m-1.414-9.414a2 2 0 112.828 2.828L11.828 15H9v-2.828l8.586-8.586z" />
|
||||
</svg>
|
||||
</div>
|
||||
<h1 className="text-2xl font-bold text-gray-900">个人博客</h1>
|
||||
<p className="text-gray-500 mt-1">管理系统</p>
|
||||
</div>
|
||||
|
||||
<Card className="shadow-xl">
|
||||
<div className="p-8">
|
||||
<div className="text-center mb-6">
|
||||
<h2 className="text-xl font-semibold text-gray-900">管理员登录</h2>
|
||||
<p className="text-sm text-gray-500 mt-1">请输入您的账号密码</p>
|
||||
</div>
|
||||
|
||||
{error && (
|
||||
<div className="mb-6 p-4 bg-red-50 border border-red-200 rounded-lg flex items-start gap-3">
|
||||
<svg className="w-5 h-5 text-red-500 flex-shrink-0 mt-0.5" fill="none" viewBox="0 0 24 24" stroke="currentColor">
|
||||
<path strokeLinecap="round" strokeLinejoin="round" strokeWidth={2} d="M12 8v4m0 4h.01M21 12a9 9 0 11-18 0 9 9 0 0118 0z" />
|
||||
</svg>
|
||||
<span className="text-sm text-red-700">{error}</span>
|
||||
</div>
|
||||
)}
|
||||
|
||||
<form onSubmit={handleSubmit} className="space-y-5">
|
||||
<div>
|
||||
<Label htmlFor="username" required>用户名</Label>
|
||||
<div className="relative">
|
||||
<div className="absolute inset-y-0 left-0 pl-3 flex items-center pointer-events-none">
|
||||
<svg className="w-5 h-5 text-gray-400" fill="none" viewBox="0 0 24 24" stroke="currentColor">
|
||||
<path strokeLinecap="round" strokeLinejoin="round" strokeWidth={2} d="M16 7a4 4 0 11-8 0 4 4 0 018 0zM12 14a7 7 0 00-7 7h14a7 7 0 00-7-7z" />
|
||||
</svg>
|
||||
</div>
|
||||
<Input
|
||||
id="username"
|
||||
value={username}
|
||||
onChange={(e) => setUsername(e.target.value)}
|
||||
placeholder="请输入用户名"
|
||||
required
|
||||
className="pl-10"
|
||||
/>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<div>
|
||||
<Label htmlFor="password" required>密码</Label>
|
||||
<div className="relative">
|
||||
<div className="absolute inset-y-0 left-0 pl-3 flex items-center pointer-events-none">
|
||||
<svg className="w-5 h-5 text-gray-400" fill="none" viewBox="0 0 24 24" stroke="currentColor">
|
||||
<path strokeLinecap="round" strokeLinejoin="round" strokeWidth={2} d="M12 15v2m-6 4h12a2 2 0 002-2v-6a2 2 0 00-2-2H6a2 2 0 00-2 2v6a2 2 0 002 2zm10-10V7a4 4 0 00-8 0v4h8z" />
|
||||
</svg>
|
||||
</div>
|
||||
<Input
|
||||
id="password"
|
||||
type="password"
|
||||
value={password}
|
||||
onChange={(e) => setPassword(e.target.value)}
|
||||
placeholder="请输入密码"
|
||||
required
|
||||
className="pl-10"
|
||||
/>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<Button
|
||||
type="submit"
|
||||
variant="primary"
|
||||
size="lg"
|
||||
className="w-full mt-2"
|
||||
loading={loading}
|
||||
>
|
||||
{loading ? '登录中...' : '登录'}
|
||||
</Button>
|
||||
</form>
|
||||
|
||||
{/* SSO 登录入口 */}
|
||||
<div className="mt-6">
|
||||
<div className="relative">
|
||||
<div className="absolute inset-0 flex items-center">
|
||||
<div className="w-full border-t border-gray-200" />
|
||||
</div>
|
||||
<div className="relative flex justify-center text-sm">
|
||||
<span className="px-2 bg-white text-gray-500">或使用</span>
|
||||
</div>
|
||||
</div>
|
||||
<Button
|
||||
type="button"
|
||||
variant="outline"
|
||||
size="lg"
|
||||
className="w-full mt-4"
|
||||
onClick={handleSSOLogin}
|
||||
>
|
||||
🔐 SSO 统一登录
|
||||
</Button>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
{/* Footer */}
|
||||
<div className="px-8 py-4 bg-gray-50 border-t border-gray-100 text-center">
|
||||
<p className="text-xs text-gray-500">
|
||||
© {new Date().getFullYear()} 个人博客 · All rights reserved
|
||||
</p>
|
||||
</div>
|
||||
</Card>
|
||||
</div>
|
||||
</div>
|
||||
)
|
||||
}
|
||||
|
||||
export default Login
|
||||
@@ -0,0 +1,297 @@
|
||||
// 文章详情页 - 访客阅读(支持 Markdown + HTML 双格式渲染)
|
||||
import { useState, useEffect, useRef } from 'react'
|
||||
import { Link, useParams, useNavigate } from 'react-router-dom'
|
||||
import { API_BASE_URL } from '../api/config'
|
||||
import DOMPurify from 'dompurify'
|
||||
|
||||
export function PostDetail() {
|
||||
const { slug } = useParams()
|
||||
const navigate = useNavigate()
|
||||
const [post, setPost] = useState(null)
|
||||
const [loading, setLoading] = useState(true)
|
||||
const [error, setError] = useState(null)
|
||||
const contentRef = useRef(null)
|
||||
|
||||
useEffect(() => {
|
||||
fetchPost()
|
||||
}, [slug])
|
||||
|
||||
// 渲染数学公式
|
||||
useEffect(() => {
|
||||
if (!post || !contentRef.current) return
|
||||
|
||||
const renderMath = () => {
|
||||
if (window.renderMathInElement) {
|
||||
window.renderMathInElement(contentRef.current, {
|
||||
delimiters: [
|
||||
{ left: '$$', right: '$$', display: true },
|
||||
{ left: '\\[', right: '\\]', display: true },
|
||||
{ left: '\\(', right: '\\)', display: false },
|
||||
{ left: '$', right: '$', display: false }
|
||||
],
|
||||
throwOnError: false,
|
||||
trust: true,
|
||||
strict: false
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
// 延迟执行,确保KaTeX和DOM都已加载
|
||||
const timer = setTimeout(renderMath, 100)
|
||||
|
||||
// 如果auto-render还没加载完,再试一次
|
||||
const retryTimer = setTimeout(renderMath, 500)
|
||||
|
||||
return () => {
|
||||
clearTimeout(timer)
|
||||
clearTimeout(retryTimer)
|
||||
}
|
||||
}, [post])
|
||||
|
||||
const fetchPost = async () => {
|
||||
try {
|
||||
const response = await fetch(`${API_BASE_URL}/posts/${slug}`)
|
||||
if (!response.ok) throw new Error('获取文章失败')
|
||||
const data = await response.json()
|
||||
setPost(data)
|
||||
} catch (err) {
|
||||
setError(err.message)
|
||||
} finally {
|
||||
setLoading(false)
|
||||
}
|
||||
}
|
||||
|
||||
// 简单的 Markdown 渲染(不使用外部库,保持轻量)
|
||||
const renderMarkdown = (markdown) => {
|
||||
if (!markdown) return ''
|
||||
|
||||
// API 基础 URL(用于补全图片路径)
|
||||
const imageBaseUrl = API_BASE_URL.replace('/api', '')
|
||||
|
||||
let html = markdown
|
||||
|
||||
// ---- 步骤 0: 先提取表格,用占位符替换,避免表格内容被后续处理破坏 ----
|
||||
const tableBlocks = []
|
||||
html = html.replace(/(?:^|\n)((?:\|.+\|\s*\n)+)/gm, (fullMatch) => {
|
||||
const lines = fullMatch.trim().split('\n')
|
||||
if (lines.length < 2) return fullMatch // 至少需要表头+分隔行
|
||||
// 第二行必须是分隔行(只含 | - : 和空格)
|
||||
if (!/^\|[-:\s|]+\|$/.test(lines[1].trim())) return fullMatch
|
||||
const idx = tableBlocks.length
|
||||
tableBlocks.push(fullMatch.trim())
|
||||
return `\n<!--TABLE_${idx}-->\n`
|
||||
})
|
||||
|
||||
// 处理表格行内的行内标记(链接、代码等)
|
||||
const processInline = (cellText) => {
|
||||
let t = cellText.trim()
|
||||
// 行内代码
|
||||
t = t.replace(/`([^`]+)`/g, '<code class="bg-gray-100 px-1 py-0.5 rounded text-red-600 font-mono text-xs">$1</code>')
|
||||
// 粗体
|
||||
t = t.replace(/\*\*(.*?)\*\*/g, '<strong>$1</strong>')
|
||||
// 斜体
|
||||
t = t.replace(/\*(.*?)\*/g, '<em>$1</em>')
|
||||
// 删除线
|
||||
t = t.replace(/~~(.*?)~~/g, '<del>$1</del>')
|
||||
// 链接
|
||||
t = t.replace(/\[([^\]]+)\]\(([^)]+)\)/g, '<a href="$2" target="_blank" rel="noopener" class="text-blue-600 hover:underline">$1</a>')
|
||||
return t
|
||||
}
|
||||
|
||||
// 渲染单个表格为 HTML
|
||||
const renderTable = (tableMarkdown) => {
|
||||
const lines = tableMarkdown.trim().split('\n')
|
||||
if (lines.length < 3) return tableMarkdown // 至少需要表头+分隔行+1行数据
|
||||
|
||||
const parseRow = (line) => {
|
||||
// 按 | 分割,去掉首尾空元素
|
||||
return line.split('|').slice(1, -1).map(c => c.trim())
|
||||
}
|
||||
|
||||
const headers = parseRow(lines[0])
|
||||
const dataRows = lines.slice(2)
|
||||
|
||||
let html = '<div class="overflow-x-auto my-4"><table class="min-w-full border-collapse border-2 border-black text-sm">'
|
||||
html += '<thead><tr class="bg-gray-100">'
|
||||
headers.forEach(h => {
|
||||
html += `<th class="border-2 border-gray-300 px-3 py-2 text-left font-bold whitespace-nowrap">${processInline(h)}</th>`
|
||||
})
|
||||
html += '</tr></thead><tbody>'
|
||||
dataRows.forEach(row => {
|
||||
const cells = parseRow(row)
|
||||
html += '<tr class="hover:bg-gray-50 border-b border-gray-200">'
|
||||
cells.forEach((c, i) => {
|
||||
if (i < headers.length) {
|
||||
html += `<td class="border border-gray-200 px-3 py-2 align-top">${processInline(c)}</td>`
|
||||
}
|
||||
})
|
||||
html += '</tr>'
|
||||
})
|
||||
html += '</tbody></table></div>'
|
||||
return html
|
||||
}
|
||||
|
||||
// 代码块(必须在行内代码之前处理)
|
||||
html = html.replace(/```(\w+)?\n([\s\S]*?)```/g, '<pre class="bg-gray-900 text-gray-100 p-4 rounded-lg overflow-x-auto my-4"><code>$2</code></pre>')
|
||||
|
||||
// 标题(从大到小依次处理)
|
||||
html = html.replace(/^#### (.*$)/gim, '<h4 class="text-lg font-bold mt-4 mb-2 text-gray-800">$1</h4>')
|
||||
html = html.replace(/^### (.*$)/gim, '<h3 class="text-xl font-bold mt-6 mb-3">$1</h3>')
|
||||
html = html.replace(/^## (.*$)/gim, '<h2 class="text-2xl font-bold mt-8 mb-4 border-b-2 border-gray-200 pb-2">$1</h2>')
|
||||
html = html.replace(/^# (.*$)/gim, '<h1 class="text-3xl font-black mt-8 mb-4">$1</h1>')
|
||||
|
||||
// 粗体
|
||||
html = html.replace(/\*\*(.*?)\*\*/g, '<strong>$1</strong>')
|
||||
|
||||
// 斜体
|
||||
html = html.replace(/\*(.*?)\*/g, '<em>$1</em>')
|
||||
|
||||
// 删除线
|
||||
html = html.replace(/~~(.*?)~~/g, '<del>$1</del>')
|
||||
|
||||
// 行内代码
|
||||
html = html.replace(/`([^`]+)`/g, '<code class="bg-gray-100 px-1 py-0.5 rounded text-red-600 font-mono text-sm">$1</code>')
|
||||
|
||||
// 引用(连续多行 > 合并为一个 blockquote)
|
||||
html = html.replace(/((?:^> .*\n?)+)/gm, (match) => {
|
||||
const lines = match.split('\n').filter(l => l.trim())
|
||||
const content = lines.map(l => l.replace(/^> /, '')).join('<br />')
|
||||
return `<blockquote class="border-l-4 border-yellow-400 pl-4 py-2 my-4 bg-yellow-50 italic">${content}</blockquote>`
|
||||
})
|
||||
|
||||
// 图片(必须在链接之前处理)
|
||||
// 支持相对路径 /uploads/xxx 自动补全为完整 URL
|
||||
html = html.replace(/!\[([^\]]*)\]\(([^)]+)\)/g, (match, alt, src) => {
|
||||
// 如果是相对路径,补全为完整 URL
|
||||
const fullSrc = src.startsWith('http') ? src : `${imageBaseUrl}${src.startsWith('/') ? '' : '/'}${src}`
|
||||
return `<img src="${fullSrc}" alt="${alt}" class="max-w-full h-auto my-6 rounded-lg border-2 border-black shadow-[4px_4px_0px_0px_rgba(0,0,0,0.2)]" loading="lazy" />`
|
||||
})
|
||||
|
||||
// 链接
|
||||
html = html.replace(/\[([^\]]+)\]\(([^)]+)\)/g, '<a href="$2" target="_blank" rel="noopener" class="text-blue-600 hover:underline">$1</a>')
|
||||
|
||||
// 无序列表(使用占位符区分)
|
||||
html = html.replace(/^\s*[-*] (.*$)/gim, '<li data-type="ul" class="ml-4">$1</li>')
|
||||
html = html.replace(/(<li data-type="ul"[^>]*>.*?<\/li>\n?)+/g, '<ul class="list-disc my-4 space-y-1">$&</ul>\n')
|
||||
html = html.replace(/data-type="ul"/g, '') // 清理占位符
|
||||
|
||||
// 有序列表(使用占位符区分)
|
||||
html = html.replace(/^\s*(\d+)\. (.*$)/gim, '<li data-type="ol" class="ml-4">$2</li>')
|
||||
html = html.replace(/(<li data-type="ol"[^>]*>.*?<\/li>\n?)+/g, '<ol class="list-decimal my-4 space-y-1">$&</ol>\n')
|
||||
html = html.replace(/data-type="ol"/g, '') // 清理占位符
|
||||
|
||||
// 分割线
|
||||
html = html.replace(/^---$/gim, '<hr class="my-8 border-t-2 border-gray-300" />')
|
||||
|
||||
// 段落
|
||||
html = html.replace(/\n\n/g, '</p><p class="my-4 leading-relaxed">')
|
||||
html = '<p class="my-4 leading-relaxed">' + html + '</p>'
|
||||
|
||||
// 清理空段落
|
||||
html = html.replace(/<p class="my-4 leading-relaxed"><\/p>/g, '')
|
||||
|
||||
// ---- 最后: 把表格占位符替换回渲染后的 HTML ----
|
||||
html = html.replace(/<!--TABLE_(\d+)-->/g, (match, idx) => {
|
||||
return renderTable(tableBlocks[parseInt(idx)])
|
||||
})
|
||||
|
||||
return html
|
||||
}
|
||||
|
||||
if (loading) return <div className="min-h-screen flex items-center justify-center">加载中...</div>
|
||||
if (error || !post) return (
|
||||
<div className="min-h-screen flex flex-col items-center justify-center">
|
||||
<p className="text-red-500 mb-4">{error || '文章不存在'}</p>
|
||||
<Link to="/" className="text-blue-600 hover:underline">← 返回首页</Link>
|
||||
</div>
|
||||
)
|
||||
|
||||
return (
|
||||
<div className="min-h-screen bg-[#FEF9E7] flex flex-col">
|
||||
{/* 顶部导航 */}
|
||||
<nav className="bg-white border-b-2 border-black sticky top-0 z-10">
|
||||
<div className="max-w-[1366px] mx-auto px-4 py-4 flex justify-between items-center">
|
||||
<Link to="/" className="text-2xl font-black tracking-tight">
|
||||
📝 侘寂屋
|
||||
</Link>
|
||||
<div className="flex gap-4">
|
||||
<Link
|
||||
to="/"
|
||||
className="px-4 py-2 border-2 border-black hover:bg-gray-100 transition-colors font-bold"
|
||||
>
|
||||
首页
|
||||
</Link>
|
||||
<Link
|
||||
to="/admin"
|
||||
className="px-4 py-2 border-2 border-black bg-[#FCD34D] hover:bg-[#F59E0B] transition-colors font-bold"
|
||||
>
|
||||
管理后台
|
||||
</Link>
|
||||
</div>
|
||||
</div>
|
||||
</nav>
|
||||
|
||||
{/* 文章内容 */}
|
||||
<main className="flex-1 max-w-[1366px] mx-auto px-4 py-8 w-full">
|
||||
{/* 返回按钮 */}
|
||||
<button
|
||||
onClick={() => navigate(-1)}
|
||||
className="mb-6 px-4 py-2 border-2 border-black hover:bg-gray-100 transition-colors font-bold"
|
||||
>
|
||||
← 返回
|
||||
</button>
|
||||
|
||||
{/* 文章头部 */}
|
||||
<header className="mb-8 pb-6 border-b-2 border-black">
|
||||
<h1 className="text-3xl md:text-4xl font-black mb-4">{post.title}</h1>
|
||||
<div className="flex items-center gap-4 text-gray-600 text-sm">
|
||||
<span>📅 {new Date(post.created_at).toLocaleDateString('zh-CN')}</span>
|
||||
{post.category && <span>📁 {post.category.name}</span>}
|
||||
</div>
|
||||
</header>
|
||||
|
||||
{/* 摘要 */}
|
||||
{post.summary && (
|
||||
<div className="mb-8 p-4 bg-yellow-100 border-l-4 border-yellow-500 italic text-gray-700">
|
||||
{post.summary}
|
||||
</div>
|
||||
)}
|
||||
|
||||
{/* 正文内容 - 根据 content_type 选择渲染方式 */}
|
||||
<article
|
||||
ref={contentRef}
|
||||
className="prose prose-lg max-w-none bg-white p-6 md:p-8 border-2 border-black shadow-[4px_4px_0px_0px_rgba(0,0,0,1)]"
|
||||
dangerouslySetInnerHTML={{
|
||||
__html: post.content_type === 'html'
|
||||
? DOMPurify.sanitize(post.content, {
|
||||
FORBID_TAGS: ['script', 'iframe', 'object', 'embed', 'form', 'input'],
|
||||
FORBID_ATTR: ['onerror', 'onload', 'onclick', 'onmouseover', 'onmouseenter', 'onmouseleave', 'onfocus', 'onblur', 'onchange', 'onsubmit']
|
||||
})
|
||||
: renderMarkdown(post.content)
|
||||
}}
|
||||
/>
|
||||
|
||||
{/* 标签 */}
|
||||
{post.tags && post.tags.length > 0 && (
|
||||
<div className="mt-8 flex flex-wrap gap-2">
|
||||
{post.tags.map(tag => (
|
||||
<span
|
||||
key={tag.id}
|
||||
className="px-3 py-1 bg-gray-100 border-2 border-black text-sm font-bold"
|
||||
>
|
||||
#{tag.name}
|
||||
</span>
|
||||
))}
|
||||
</div>
|
||||
)}
|
||||
</main>
|
||||
|
||||
{/* 页脚 - 固定在底部 */}
|
||||
<footer className="border-t-2 border-black bg-white">
|
||||
<div className="max-w-[1366px] mx-auto px-4 py-6 text-center text-gray-600">
|
||||
© 2026 侘寂屋 · 用心记录每一刻
|
||||
</div>
|
||||
</footer>
|
||||
</div>
|
||||
)
|
||||
}
|
||||
@@ -0,0 +1,538 @@
|
||||
// 文章编辑页面 - 支持 Markdown / HTML 双格式
|
||||
import { useState, useEffect, useRef, useCallback } from 'react'
|
||||
import { useNavigate, useParams } from 'react-router-dom'
|
||||
import { AdminLayout } from '../components-preline/Sidebar'
|
||||
import { authApi } from '../api/auth'
|
||||
import { Card, CardHeader, CardTitle, CardDescription, CardBody, CardFooter } from '../components-preline/Card'
|
||||
import { Button } from '../components-preline/Button'
|
||||
import { Input, Textarea, Label } from '../components-preline/Input'
|
||||
import { postsApi } from '../api/posts'
|
||||
import { categoriesApi } from '../api/categories'
|
||||
import { tagsApi } from '../api/tags'
|
||||
import { API_BASE_URL } from '../api/config'
|
||||
|
||||
import MDEditor from '@uiw/react-md-editor'
|
||||
import '@uiw/react-md-editor/markdown-editor.css'
|
||||
|
||||
import ReactQuill from 'react-quill-new'
|
||||
import 'react-quill-new/dist/quill.snow.css'
|
||||
|
||||
// 图片上传组件
|
||||
function ImageUploader({ uploadedImages, setUploadedImages, onInsertImage }) {
|
||||
const fileInputRef = useRef(null)
|
||||
const [uploading, setUploading] = useState(false)
|
||||
|
||||
const handleImageUpload = async (e) => {
|
||||
const files = e.target.files
|
||||
if (!files || files.length === 0) return
|
||||
|
||||
setUploading(true)
|
||||
const formData = new FormData()
|
||||
for (let i = 0; i < files.length; i++) {
|
||||
formData.append('files', files[i])
|
||||
}
|
||||
|
||||
try {
|
||||
const token = localStorage.getItem('token')
|
||||
const res = await fetch(`${API_BASE_URL}/images/upload-multiple`, {
|
||||
method: 'POST',
|
||||
headers: {
|
||||
...(token ? { 'Authorization': `Bearer ${token}` } : {})
|
||||
},
|
||||
credentials: 'include',
|
||||
body: formData
|
||||
})
|
||||
const data = await res.json()
|
||||
if (data.uploaded && data.uploaded.length > 0) {
|
||||
setUploadedImages(prev => [...prev, ...data.uploaded])
|
||||
}
|
||||
} catch (error) {
|
||||
alert('上传失败')
|
||||
} finally {
|
||||
setUploading(false)
|
||||
}
|
||||
}
|
||||
|
||||
return (
|
||||
<div className="space-y-4">
|
||||
<input
|
||||
type="file"
|
||||
multiple
|
||||
accept="image/*"
|
||||
ref={fileInputRef}
|
||||
onChange={handleImageUpload}
|
||||
className="hidden"
|
||||
/>
|
||||
<Button
|
||||
type="button"
|
||||
variant="secondary"
|
||||
onClick={() => fileInputRef.current?.click()}
|
||||
disabled={uploading}
|
||||
className="w-full"
|
||||
>
|
||||
{uploading ? '上传中...' : '上传图片'}
|
||||
</Button>
|
||||
|
||||
{uploadedImages.length > 0 && (
|
||||
<div className="space-y-2">
|
||||
<p className="text-sm font-medium text-gray-700">本次上传的图片</p>
|
||||
<div className="grid grid-cols-3 gap-2">
|
||||
{uploadedImages.map((img) => (
|
||||
<div
|
||||
key={img.id}
|
||||
className="relative group aspect-square rounded-lg overflow-hidden cursor-pointer bg-gray-100 border border-gray-200 hover:border-blue-400 transition-colors"
|
||||
onClick={() => onInsertImage(img)}
|
||||
title="点击插入到文章"
|
||||
>
|
||||
<img
|
||||
src={`${API_BASE_URL.replace('/api', '')}${img.thumb_path || img.file_path}`}
|
||||
alt={img.original_name}
|
||||
className="w-full h-full object-cover"
|
||||
loading="lazy"
|
||||
/>
|
||||
<div className="absolute inset-0 bg-black/50 opacity-0 group-hover:opacity-100 transition-opacity flex items-center justify-center">
|
||||
<svg className="w-6 h-6 text-white" fill="none" viewBox="0 0 24 24" stroke="currentColor">
|
||||
<path strokeLinecap="round" strokeLinejoin="round" strokeWidth={2} d="M12 4v16m8-8H4" />
|
||||
</svg>
|
||||
</div>
|
||||
</div>
|
||||
))}
|
||||
</div>
|
||||
<p className="text-xs text-gray-500">点击图片插入到文章末尾</p>
|
||||
</div>
|
||||
)}
|
||||
|
||||
<div className="bg-blue-50 rounded-lg p-3 border border-blue-100">
|
||||
<p className="text-xs font-medium text-blue-800 mb-1">使用说明</p>
|
||||
<ul className="text-xs text-blue-700 space-y-0.5">
|
||||
<li>1. 点击上传图片</li>
|
||||
<li>2. 点击缩略图插入文章</li>
|
||||
<li>3. Markdown 模式插入 <code className="bg-blue-100 px-1 rounded"></code></li>
|
||||
<li>4. HTML 模式插入图片标签</li>
|
||||
</ul>
|
||||
</div>
|
||||
</div>
|
||||
)
|
||||
}
|
||||
|
||||
// 标签选择器
|
||||
function TagSelector({ tags, selectedIds, onToggle }) {
|
||||
return (
|
||||
<div className="flex flex-wrap gap-2">
|
||||
{tags.map(tag => (
|
||||
<button
|
||||
key={tag.id}
|
||||
type="button"
|
||||
onClick={() => onToggle(tag.id)}
|
||||
className={`px-3 py-1.5 text-sm rounded-full border transition-all ${
|
||||
selectedIds.includes(tag.id)
|
||||
? 'bg-blue-500 text-white border-blue-500'
|
||||
: 'bg-white text-gray-700 border-gray-300 hover:border-blue-400 hover:text-blue-600'
|
||||
}`}
|
||||
>
|
||||
{tag.name}
|
||||
</button>
|
||||
))}
|
||||
</div>
|
||||
)
|
||||
}
|
||||
|
||||
export function PostEdit() {
|
||||
const { id } = useParams()
|
||||
const navigate = useNavigate()
|
||||
const isEdit = Boolean(id)
|
||||
const quillRef = useRef(null)
|
||||
|
||||
const [form, setForm] = useState({
|
||||
title: '',
|
||||
content: '',
|
||||
content_type: 'markdown',
|
||||
summary: '',
|
||||
category_id: '',
|
||||
tag_ids: [],
|
||||
is_published: true,
|
||||
is_draft: false
|
||||
})
|
||||
const [categories, setCategories] = useState([])
|
||||
const [tags, setTags] = useState([])
|
||||
const [loading, setLoading] = useState(false)
|
||||
const [saving, setSaving] = useState(false)
|
||||
const [uploadedImages, setUploadedImages] = useState([])
|
||||
|
||||
const user = JSON.parse(localStorage.getItem('user') || '{}')
|
||||
|
||||
useEffect(() => {
|
||||
fetchCategories()
|
||||
fetchTags()
|
||||
if (isEdit) {
|
||||
fetchPost()
|
||||
} else {
|
||||
// 新建文章时重置表单,防止从编辑页切换过来残留旧数据
|
||||
setForm({
|
||||
title: '',
|
||||
content: '',
|
||||
content_type: 'markdown',
|
||||
summary: '',
|
||||
category_id: '',
|
||||
tag_ids: [],
|
||||
is_published: true,
|
||||
is_draft: false
|
||||
})
|
||||
}
|
||||
}, [id])
|
||||
|
||||
const fetchCategories = async () => {
|
||||
try {
|
||||
const res = await categoriesApi.getCategories()
|
||||
setCategories(res.data)
|
||||
} catch (error) {
|
||||
console.error('获取分类失败', error)
|
||||
}
|
||||
}
|
||||
|
||||
const fetchTags = async () => {
|
||||
try {
|
||||
const res = await tagsApi.getTags()
|
||||
setTags(res.data)
|
||||
} catch (error) {
|
||||
console.error('获取标签失败', error)
|
||||
}
|
||||
}
|
||||
|
||||
const fetchPost = async () => {
|
||||
setLoading(true)
|
||||
try {
|
||||
const res = await postsApi.getPost(id)
|
||||
const post = res.data
|
||||
setForm({
|
||||
title: post.title,
|
||||
content: post.content,
|
||||
content_type: post.content_type || 'markdown',
|
||||
summary: post.summary || '',
|
||||
category_id: post.category_id || '',
|
||||
tag_ids: post.tags.map(t => t.id),
|
||||
is_published: post.is_published,
|
||||
is_draft: post.is_draft
|
||||
})
|
||||
} catch (error) {
|
||||
alert('获取文章失败')
|
||||
navigate('/admin/posts')
|
||||
} finally {
|
||||
setLoading(false)
|
||||
}
|
||||
}
|
||||
|
||||
const handleSubmit = async (e, isDraft = false) => {
|
||||
e.preventDefault()
|
||||
|
||||
if (!form.title.trim() || !form.content.trim()) {
|
||||
alert('请填写标题和内容')
|
||||
return
|
||||
}
|
||||
|
||||
setSaving(true)
|
||||
try {
|
||||
const data = {
|
||||
...form,
|
||||
category_id: form.category_id || null,
|
||||
is_draft: isDraft
|
||||
}
|
||||
|
||||
if (isEdit) {
|
||||
await postsApi.updatePost(id, data)
|
||||
} else {
|
||||
await postsApi.createPost(data)
|
||||
}
|
||||
|
||||
navigate('/admin/posts')
|
||||
} catch (error) {
|
||||
alert('保存失败: ' + (error.response?.data?.detail || '未知错误'))
|
||||
} finally {
|
||||
setSaving(false)
|
||||
}
|
||||
}
|
||||
|
||||
const handleChange = (e) => {
|
||||
const { name, value, type, checked } = e.target
|
||||
setForm(prev => ({
|
||||
...prev,
|
||||
[name]: type === 'checkbox' ? checked : value
|
||||
}))
|
||||
}
|
||||
|
||||
const handleTagToggle = (tagId) => {
|
||||
setForm(prev => ({
|
||||
...prev,
|
||||
tag_ids: prev.tag_ids.includes(tagId)
|
||||
? prev.tag_ids.filter(id => id !== tagId)
|
||||
: [...prev.tag_ids, tagId]
|
||||
}))
|
||||
}
|
||||
|
||||
// 插入图片:根据当前模式决定格式
|
||||
const insertImageToEditor = useCallback((image) => {
|
||||
if (form.content_type === 'html') {
|
||||
// HTML 模式:通过 Quill API 插入
|
||||
if (quillRef.current) {
|
||||
const quill = quillRef.current.getEditor()
|
||||
const range = quill.getSelection(true)
|
||||
const index = range ? range.index : quill.getLength()
|
||||
quill.insertEmbed(index, 'image', image.file_path, 'user')
|
||||
quill.setSelection(index + 1, 0, 'silent')
|
||||
}
|
||||
} else {
|
||||
// Markdown 模式:追加 markdown 图片语法
|
||||
const markdown = `\n\n`
|
||||
setForm(prev => ({
|
||||
...prev,
|
||||
content: prev.content + markdown
|
||||
}))
|
||||
}
|
||||
}, [form.content_type])
|
||||
|
||||
const handleLogout = async () => {
|
||||
localStorage.removeItem('token')
|
||||
await authApi.logout()
|
||||
localStorage.removeItem('user')
|
||||
window.location.href = '/login'
|
||||
}
|
||||
|
||||
const quillModules = {
|
||||
toolbar: [
|
||||
[{ header: [1, 2, 3, false] }],
|
||||
['bold', 'italic', 'underline', 'strike'],
|
||||
[{ list: 'ordered' }, { list: 'bullet' }],
|
||||
[{ indent: '-1' }, { indent: '+1' }],
|
||||
['link', 'image'],
|
||||
['blockquote', 'code-block'],
|
||||
[{ color: [] }, { background: [] }],
|
||||
['clean']
|
||||
]
|
||||
}
|
||||
|
||||
if (loading) {
|
||||
return (
|
||||
<AdminLayout user={user} onLogout={handleLogout}>
|
||||
<div className="p-6 w-full flex items-center justify-center min-h-[60vh]">
|
||||
<div className="text-center">
|
||||
<svg className="animate-spin h-8 w-8 text-blue-500 mx-auto mb-4" viewBox="0 0 24 24" fill="none">
|
||||
<circle className="opacity-25" cx="12" cy="12" r="10" stroke="currentColor" strokeWidth="4" />
|
||||
<path className="opacity-75" fill="currentColor" d="M4 12a8 8 0 018-8V0C5.373 0 0 5.373 0 12h4z" />
|
||||
</svg>
|
||||
<p className="text-gray-500">加载中...</p>
|
||||
</div>
|
||||
</div>
|
||||
</AdminLayout>
|
||||
)
|
||||
}
|
||||
|
||||
return (
|
||||
<AdminLayout user={user} onLogout={handleLogout}>
|
||||
<div className="p-6 w-full">
|
||||
<div className="mb-6">
|
||||
<h1 className="text-2xl font-semibold text-gray-900">
|
||||
{isEdit ? '编辑文章' : '写文章'}
|
||||
</h1>
|
||||
<p className="text-gray-500 mt-1">
|
||||
{isEdit ? '修改文章内容和设置' : '创建新的博客文章'}
|
||||
</p>
|
||||
</div>
|
||||
|
||||
<form onSubmit={(e) => handleSubmit(e, false)}>
|
||||
<div className="grid grid-cols-1 lg:grid-cols-3 gap-6">
|
||||
{/* 主编辑区 */}
|
||||
<div className="lg:col-span-2 space-y-6">
|
||||
<Card>
|
||||
<CardBody className="space-y-6">
|
||||
{/* 标题 */}
|
||||
<div>
|
||||
<Label htmlFor="title" required>文章标题</Label>
|
||||
<Input
|
||||
id="title"
|
||||
name="title"
|
||||
value={form.title}
|
||||
onChange={handleChange}
|
||||
placeholder="请输入文章标题"
|
||||
required
|
||||
/>
|
||||
</div>
|
||||
|
||||
{/* 格式切换 */}
|
||||
<div>
|
||||
<Label>编辑格式</Label>
|
||||
<div className="flex gap-2 mt-1">
|
||||
<button
|
||||
type="button"
|
||||
onClick={() => setForm(prev => ({
|
||||
...prev,
|
||||
content_type: 'markdown',
|
||||
// 从 HTML 切回 Markdown 时,如果 content 是空的段落标签,清空它
|
||||
content: /^<p\s*>(\s*|<br\s*\/?>)<\/p>\s*$/i.test(prev.content) ? '' : prev.content
|
||||
}))}
|
||||
className={`px-4 py-2 rounded-lg border text-sm font-medium transition-colors ${
|
||||
form.content_type === 'markdown'
|
||||
? 'bg-blue-500 text-white border-blue-500'
|
||||
: 'bg-white text-gray-700 border-gray-300 hover:border-blue-400'
|
||||
}`}
|
||||
>
|
||||
Markdown
|
||||
</button>
|
||||
<button
|
||||
type="button"
|
||||
onClick={() => setForm(prev => ({ ...prev, content_type: 'html' }))}
|
||||
className={`px-4 py-2 rounded-lg border text-sm font-medium transition-colors ${
|
||||
form.content_type === 'html'
|
||||
? 'bg-blue-500 text-white border-blue-500'
|
||||
: 'bg-white text-gray-700 border-gray-300 hover:border-blue-400'
|
||||
}`}
|
||||
>
|
||||
富文本 HTML
|
||||
</button>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
{/* 摘要 */}
|
||||
<div>
|
||||
<Label htmlFor="summary">摘要</Label>
|
||||
<Textarea
|
||||
id="summary"
|
||||
name="summary"
|
||||
value={form.summary}
|
||||
onChange={handleChange}
|
||||
rows={2}
|
||||
placeholder="文章摘要(可选,不填则自动截取正文前200字)"
|
||||
/>
|
||||
</div>
|
||||
|
||||
{/* 正文 - Markdown 模式 */}
|
||||
{form.content_type === 'markdown' && (
|
||||
<div>
|
||||
<Label required>正文内容(Markdown)</Label>
|
||||
<div className="mt-1 border border-gray-300 rounded-lg overflow-hidden" data-color-mode="light">
|
||||
<MDEditor
|
||||
value={/^<p\s*>(\s*|<br\s*\/?>)<\/p>\s*$/i.test(form.content) ? '' : form.content}
|
||||
onChange={(val) => setForm(prev => ({ ...prev, content: val || '' }))}
|
||||
height={500}
|
||||
preview="edit"
|
||||
/>
|
||||
</div>
|
||||
</div>
|
||||
)}
|
||||
|
||||
{/* 正文 - HTML 模式 */}
|
||||
{form.content_type === 'html' && (
|
||||
<div>
|
||||
<Label required>正文内容(富文本)</Label>
|
||||
<div className="mt-1">
|
||||
<ReactQuill
|
||||
ref={quillRef}
|
||||
theme="snow"
|
||||
value={form.content}
|
||||
onChange={(val) => setForm(prev => ({ ...prev, content: /^<p\s*>(\s*|<br\s*\/?>)<\/p>\s*$/i.test(val) ? '' : val }))}
|
||||
modules={quillModules}
|
||||
style={{ height: 450 }}
|
||||
/>
|
||||
</div>
|
||||
</div>
|
||||
)}
|
||||
</CardBody>
|
||||
</Card>
|
||||
</div>
|
||||
|
||||
{/* 侧边栏 */}
|
||||
<div className="space-y-6">
|
||||
<Card>
|
||||
<CardHeader>
|
||||
<div>
|
||||
<CardTitle>图片管理</CardTitle>
|
||||
<CardDescription>上传并插入图片到文章</CardDescription>
|
||||
</div>
|
||||
</CardHeader>
|
||||
<CardBody>
|
||||
<ImageUploader
|
||||
uploadedImages={uploadedImages}
|
||||
setUploadedImages={setUploadedImages}
|
||||
onInsertImage={insertImageToEditor}
|
||||
/>
|
||||
</CardBody>
|
||||
</Card>
|
||||
|
||||
<Card>
|
||||
<CardHeader>
|
||||
<div>
|
||||
<CardTitle>发布设置</CardTitle>
|
||||
<CardDescription>选择分类和标签</CardDescription>
|
||||
</div>
|
||||
</CardHeader>
|
||||
<CardBody className="space-y-6">
|
||||
<div>
|
||||
<Label htmlFor="category_id">分类</Label>
|
||||
<select
|
||||
id="category_id"
|
||||
name="category_id"
|
||||
value={form.category_id}
|
||||
onChange={handleChange}
|
||||
className="w-full px-3 py-2 border border-gray-300 rounded-lg bg-white focus:outline-none focus:ring-2 focus:ring-blue-500 focus:border-blue-500"
|
||||
>
|
||||
<option value="">未分类</option>
|
||||
{categories.map(cat => (
|
||||
<option key={cat.id} value={cat.id}>{cat.name}</option>
|
||||
))}
|
||||
</select>
|
||||
</div>
|
||||
|
||||
<div>
|
||||
<Label>标签</Label>
|
||||
<TagSelector
|
||||
tags={tags}
|
||||
selectedIds={form.tag_ids}
|
||||
onToggle={handleTagToggle}
|
||||
/>
|
||||
</div>
|
||||
</CardBody>
|
||||
<CardFooter className="flex-col gap-2">
|
||||
<Button
|
||||
type="submit"
|
||||
variant="primary"
|
||||
className="w-full"
|
||||
loading={saving}
|
||||
>
|
||||
<svg className="w-4 h-4 mr-2" fill="none" viewBox="0 0 24 24" stroke="currentColor">
|
||||
<path strokeLinecap="round" strokeLinejoin="round" strokeWidth={2} d="M5 13l4 4L19 7" />
|
||||
</svg>
|
||||
{saving ? '保存中...' : (isEdit ? '更新文章' : '发布文章')}
|
||||
</Button>
|
||||
|
||||
<Button
|
||||
type="button"
|
||||
variant="secondary"
|
||||
className="w-full"
|
||||
onClick={(e) => handleSubmit(e, true)}
|
||||
disabled={saving}
|
||||
>
|
||||
<svg className="w-4 h-4 mr-2" fill="none" viewBox="0 0 24 24" stroke="currentColor">
|
||||
<path strokeLinecap="round" strokeLinejoin="round" strokeWidth={2} d="M8 7H5a2 2 0 00-2 2v9a2 2 0 002 2h14a2 2 0 002-2V9a2 2 0 00-2-2h-3m-1 4l-4 4m0 0l-4-4m4 4V4" />
|
||||
</svg>
|
||||
保存为草稿
|
||||
</Button>
|
||||
|
||||
<Button
|
||||
type="button"
|
||||
variant="ghost"
|
||||
className="w-full"
|
||||
onClick={() => navigate('/admin/posts')}
|
||||
disabled={saving}
|
||||
>
|
||||
取消
|
||||
</Button>
|
||||
</CardFooter>
|
||||
</Card>
|
||||
</div>
|
||||
</div>
|
||||
</form>
|
||||
</div>
|
||||
</AdminLayout>
|
||||
)
|
||||
}
|
||||
|
||||
export default PostEdit
|
||||
@@ -0,0 +1,311 @@
|
||||
// 文章管理页面 - Preline UI 风格
|
||||
import { useState, useEffect } from 'react'
|
||||
import { useNavigate } from 'react-router-dom'
|
||||
import { AdminLayout } from '../components-preline/Sidebar'
|
||||
import { authApi } from '../api/auth'
|
||||
import { Card, CardHeader, CardTitle, CardDescription, CardBody } from '../components-preline/Card'
|
||||
import { Button } from '../components-preline/Button'
|
||||
import { Input } from '../components-preline/Input'
|
||||
import { postsApi } from '../api/posts'
|
||||
import { categoriesApi } from '../api/categories'
|
||||
|
||||
// 状态标签
|
||||
function StatusBadge({ isDraft }) {
|
||||
if (isDraft) {
|
||||
return (
|
||||
<span className="inline-flex items-center px-2.5 py-0.5 rounded-full text-xs font-medium bg-yellow-100 text-yellow-800">
|
||||
草稿
|
||||
</span>
|
||||
)
|
||||
}
|
||||
return (
|
||||
<span className="inline-flex items-center px-2.5 py-0.5 rounded-full text-xs font-medium bg-green-100 text-green-800">
|
||||
已发布
|
||||
</span>
|
||||
)
|
||||
}
|
||||
|
||||
// 格式标签
|
||||
function FormatBadge({ contentType }) {
|
||||
const isHtml = contentType === 'html'
|
||||
return (
|
||||
<span className={`inline-flex items-center px-2 py-0.5 rounded text-xs font-medium ${
|
||||
isHtml
|
||||
? 'bg-purple-50 text-purple-700 border border-purple-200'
|
||||
: 'bg-gray-100 text-gray-700 border border-gray-200'
|
||||
}`}>
|
||||
{isHtml ? 'HTML' : 'MD'}
|
||||
</span>
|
||||
)
|
||||
}
|
||||
|
||||
// 文章列表项
|
||||
function PostItem({ post, onEdit, onDelete }) {
|
||||
return (
|
||||
<div className="flex items-center gap-4 p-4 hover:bg-gray-50 transition-colors border-b border-gray-100 last:border-0">
|
||||
{/* 封面 */}
|
||||
<div className="w-16 h-16 rounded-lg bg-gray-100 flex-shrink-0 overflow-hidden border border-gray-200">
|
||||
{post.cover_image ? (
|
||||
<img
|
||||
src={post.cover_image}
|
||||
alt=""
|
||||
className="w-full h-full object-cover"
|
||||
/>
|
||||
) : (
|
||||
<div className="w-full h-full flex items-center justify-center text-2xl bg-gradient-to-br from-blue-50 to-indigo-50">
|
||||
📝
|
||||
</div>
|
||||
)}
|
||||
</div>
|
||||
|
||||
{/* 信息 */}
|
||||
<div className="flex-1 min-w-0">
|
||||
<h4 className="font-medium text-gray-900 truncate">{post.title}</h4>
|
||||
<div className="flex items-center gap-3 text-sm text-gray-500 mt-1">
|
||||
<span>{new Date(post.created_at).toLocaleDateString('zh-CN')}</span>
|
||||
<span className="text-gray-300">|</span>
|
||||
<span className="flex items-center gap-1">
|
||||
<svg className="w-4 h-4" fill="none" viewBox="0 0 24 24" stroke="currentColor">
|
||||
<path strokeLinecap="round" strokeLinejoin="round" strokeWidth={2} d="M15 12a3 3 0 11-6 0 3 3 0 016 0z" />
|
||||
<path strokeLinecap="round" strokeLinejoin="round" strokeWidth={2} d="M2.458 12C3.732 7.943 7.523 5 12 5c4.478 0 8.268 2.943 9.542 7-1.274 4.057-5.064 7-9.542 7-4.477 0-8.268-2.943-9.542-7z" />
|
||||
</svg>
|
||||
{post.view_count || 0}
|
||||
</span>
|
||||
{post.category_name && (
|
||||
<>
|
||||
<span className="text-gray-300">|</span>
|
||||
<span className="inline-flex items-center px-2 py-0.5 rounded text-xs font-medium bg-blue-50 text-blue-700">
|
||||
{post.category_name}
|
||||
</span>
|
||||
</>
|
||||
)}
|
||||
<span className="text-gray-300">|</span>
|
||||
<FormatBadge contentType={post.content_type} />
|
||||
<span className="text-gray-300">|</span>
|
||||
<StatusBadge isDraft={post.is_draft} />
|
||||
</div>
|
||||
</div>
|
||||
|
||||
{/* 操作 */}
|
||||
<div className="flex items-center gap-2">
|
||||
<Button
|
||||
variant="secondary"
|
||||
size="sm"
|
||||
onClick={() => onEdit(post.id)}
|
||||
>
|
||||
<svg className="w-4 h-4 mr-1" fill="none" viewBox="0 0 24 24" stroke="currentColor">
|
||||
<path strokeLinecap="round" strokeLinejoin="round" strokeWidth={2} d="M11 5H6a2 2 0 00-2 2v11a2 2 0 002 2h11a2 2 0 002-2v-5m-1.414-9.414a2 2 0 112.828 2.828L11.828 15H9v-2.828l8.586-8.586z" />
|
||||
</svg>
|
||||
编辑
|
||||
</Button>
|
||||
<Button
|
||||
variant="danger"
|
||||
size="sm"
|
||||
onClick={() => onDelete(post.id)}
|
||||
>
|
||||
<svg className="w-4 h-4 mr-1" fill="none" viewBox="0 0 24 24" stroke="currentColor">
|
||||
<path strokeLinecap="round" strokeLinejoin="round" strokeWidth={2} d="M19 7l-.867 12.142A2 2 0 0116.138 21H7.862a2 2 0 01-1.995-1.858L5 7m5 4v6m4-6v6m1-10V4a1 1 0 00-1-1h-4a1 1 0 00-1 1v3M4 7h16" />
|
||||
</svg>
|
||||
删除
|
||||
</Button>
|
||||
</div>
|
||||
</div>
|
||||
)
|
||||
}
|
||||
|
||||
export function Posts() {
|
||||
const [posts, setPosts] = useState([])
|
||||
const [loading, setLoading] = useState(true)
|
||||
const [search, setSearch] = useState('')
|
||||
const [categoryId, setCategoryId] = useState('')
|
||||
const [categories, setCategories] = useState([])
|
||||
const navigate = useNavigate()
|
||||
|
||||
// 获取当前用户信息
|
||||
const user = JSON.parse(localStorage.getItem('user') || '{}')
|
||||
|
||||
useEffect(() => {
|
||||
fetchPosts()
|
||||
fetchCategories()
|
||||
}, [])
|
||||
|
||||
useEffect(() => {
|
||||
fetchPosts()
|
||||
}, [categoryId])
|
||||
|
||||
const fetchPosts = async () => {
|
||||
try {
|
||||
setLoading(true)
|
||||
const params = { limit: 100 }
|
||||
if (categoryId) params.category_id = categoryId
|
||||
const res = await postsApi.getPosts(params)
|
||||
setPosts(res.data)
|
||||
} catch (error) {
|
||||
console.error('获取文章失败:', error)
|
||||
} finally {
|
||||
setLoading(false)
|
||||
}
|
||||
}
|
||||
|
||||
const fetchCategories = async () => {
|
||||
try {
|
||||
const res = await categoriesApi.getCategories()
|
||||
setCategories(res.data)
|
||||
} catch (error) {
|
||||
console.error('获取分类失败:', error)
|
||||
}
|
||||
}
|
||||
|
||||
const handleDelete = async (id) => {
|
||||
if (!confirm('确定要删除这篇文章吗?')) return
|
||||
|
||||
try {
|
||||
await postsApi.deletePost(id)
|
||||
fetchPosts()
|
||||
} catch (error) {
|
||||
alert('删除失败')
|
||||
}
|
||||
}
|
||||
|
||||
const handleLogout = async () => {
|
||||
localStorage.removeItem('token')
|
||||
await authApi.logout()
|
||||
localStorage.removeItem('user')
|
||||
window.location.href = '/login'
|
||||
}
|
||||
|
||||
const filteredPosts = posts.filter(post =>
|
||||
post.title.toLowerCase().includes(search.toLowerCase())
|
||||
)
|
||||
|
||||
return (
|
||||
<AdminLayout user={user} onLogout={handleLogout}>
|
||||
<div className="p-6 w-full">
|
||||
{/* 页面标题 */}
|
||||
<div className="mb-6">
|
||||
<h1 className="text-2xl font-semibold text-gray-900">文章管理</h1>
|
||||
<p className="text-gray-500 mt-1">管理您的博客文章</p>
|
||||
</div>
|
||||
|
||||
<Card>
|
||||
<CardHeader
|
||||
action={
|
||||
<div className="flex items-center gap-3">
|
||||
<div className="w-64 relative">
|
||||
<div className="absolute inset-y-0 left-0 pl-3 flex items-center pointer-events-none">
|
||||
<svg className="w-5 h-5 text-gray-400" fill="none" viewBox="0 0 24 24" stroke="currentColor">
|
||||
<path strokeLinecap="round" strokeLinejoin="round" strokeWidth={2} d="M21 21l-6-6m2-5a7 7 0 11-14 0 7 7 0 0114 0z" />
|
||||
</svg>
|
||||
</div>
|
||||
<Input
|
||||
placeholder="搜索文章..."
|
||||
value={search}
|
||||
onChange={(e) => setSearch(e.target.value)}
|
||||
className="pl-10"
|
||||
/>
|
||||
</div>
|
||||
<select
|
||||
value={categoryId}
|
||||
onChange={(e) => setCategoryId(e.target.value)}
|
||||
className="py-2 px-3 pr-8 border border-gray-300 rounded-lg text-sm focus:ring-2 focus:ring-blue-500 focus:border-blue-500 bg-white appearance-none cursor-pointer"
|
||||
style={{
|
||||
backgroundImage: `url("data:image/svg+xml,%3csvg xmlns='http://www.w3.org/2000/svg' fill='none' viewBox='0 0 20 20'%3e%3cpath stroke='%236b7280' stroke-linecap='round' stroke-linejoin='round' stroke-width='1.5' d='M6 8l4 4 4-4'/%3e%3c/svg%3e")`,
|
||||
backgroundPosition: 'right 0.5rem center',
|
||||
backgroundRepeat: 'no-repeat',
|
||||
backgroundSize: '1.5em 1.5em'
|
||||
}}
|
||||
>
|
||||
<option value="">全部分类</option>
|
||||
{categories.map(cat => (
|
||||
<option key={cat.id} value={cat.id}>{cat.name} ({cat.post_count})</option>
|
||||
))}
|
||||
</select>
|
||||
<Button
|
||||
variant="secondary"
|
||||
onClick={() => navigate('/admin/crawl')}
|
||||
>
|
||||
<svg className="w-4 h-4 mr-2" fill="none" viewBox="0 0 24 24" stroke="currentColor">
|
||||
<path strokeLinecap="round" strokeLinejoin="round" strokeWidth={2} d="M21 12a9 9 0 01-9 9m9-9a9 9 0 00-9-9m9 9H3m9 9a9 9 0 01-9-9m9 9c1.657 0 3-4.03 3-9s-1.343-9-3-9m0 18c-1.657 0-3-4.03-3-9s1.343-9 3-9m-9 9a9 9 0 019-9" />
|
||||
</svg>
|
||||
采集文章
|
||||
</Button>
|
||||
<Button
|
||||
variant="secondary"
|
||||
onClick={() => navigate('/admin/wechat-crawl')}
|
||||
>
|
||||
<svg className="w-4 h-4 mr-2" fill="none" viewBox="0 0 24 24" stroke="currentColor">
|
||||
<path strokeLinecap="round" strokeLinejoin="round" strokeWidth={2} d="M8 12h.01M12 12h.01M16 12h.01M21 12c0 4.418-4.03 8-9 8a9.863 9.863 0 01-4.255-.949L3 20l1.395-3.72C3.512 15.042 3 13.574 3 12c0-4.418 4.03-8 9-8s9 3.582 9 8z" />
|
||||
</svg>
|
||||
公众号采集
|
||||
</Button>
|
||||
<Button
|
||||
variant="secondary"
|
||||
onClick={() => navigate('/admin/universal-crawl')}
|
||||
>
|
||||
<svg className="w-4 h-4 mr-2" fill="none" viewBox="0 0 24 24" stroke="currentColor">
|
||||
<path strokeLinecap="round" strokeLinejoin="round" strokeWidth={2} d="M21 12a9 9 0 01-9 9m9-9a9 9 0 00-9-9m9 9H3m9 9a9 9 0 01-9-9m9 9c1.657 0 3-4.03 3-9s-1.343-9-3-9m0 18c-1.657 0-3-4.03-3-9s1.343-9 3-9m-9 9a9 9 0 019-9" />
|
||||
</svg>
|
||||
通用采集
|
||||
</Button>
|
||||
<Button
|
||||
variant="primary"
|
||||
onClick={() => navigate('/admin/posts/new')}
|
||||
>
|
||||
<svg className="w-4 h-4 mr-2" fill="none" viewBox="0 0 24 24" stroke="currentColor">
|
||||
<path strokeLinecap="round" strokeLinejoin="round" strokeWidth={2} d="M12 4v16m8-8H4" />
|
||||
</svg>
|
||||
写文章
|
||||
</Button>
|
||||
</div>
|
||||
}
|
||||
>
|
||||
<div>
|
||||
<CardTitle>文章列表</CardTitle>
|
||||
<CardDescription>共 {posts.length} 篇文章</CardDescription>
|
||||
</div>
|
||||
</CardHeader>
|
||||
|
||||
<CardBody className="p-0">
|
||||
{loading ? (
|
||||
<div className="flex items-center justify-center py-12">
|
||||
<svg className="animate-spin h-5 w-5 text-gray-400" viewBox="0 0 24 24" fill="none">
|
||||
<circle className="opacity-25" cx="12" cy="12" r="10" stroke="currentColor" strokeWidth="4" />
|
||||
<path className="opacity-75" fill="currentColor" d="M4 12a8 8 0 018-8V0C5.373 0 0 5.373 0 12h4z" />
|
||||
</svg>
|
||||
<span className="ml-2 text-gray-500">加载中...</span>
|
||||
</div>
|
||||
) : filteredPosts.length === 0 ? (
|
||||
<div className="text-center py-12">
|
||||
<div className="w-12 h-12 bg-gray-100 rounded-full flex items-center justify-center mx-auto mb-3">
|
||||
<svg className="w-6 h-6 text-gray-400" fill="none" viewBox="0 0 24 24" stroke="currentColor">
|
||||
<path strokeLinecap="round" strokeLinejoin="round" strokeWidth={2} d="M9 12h6m-6 4h6m2 5H7a2 2 0 01-2-2V5a2 2 0 012-2h5.586a1 1 0 01.707.293l5.414 5.414a1 1 0 01.293.707V19a2 2 0 01-2 2z" />
|
||||
</svg>
|
||||
</div>
|
||||
<p className="text-gray-500 mb-4">暂无文章</p>
|
||||
<Button
|
||||
variant="primary"
|
||||
onClick={() => navigate('/admin/posts/new')}
|
||||
>
|
||||
写第一篇文章
|
||||
</Button>
|
||||
</div>
|
||||
) : (
|
||||
<div className="divide-y divide-gray-100">
|
||||
{filteredPosts.map(post => (
|
||||
<PostItem
|
||||
key={post.id}
|
||||
post={post}
|
||||
onEdit={(id) => navigate(`/admin/posts/edit/${id}`)}
|
||||
onDelete={handleDelete}
|
||||
/>
|
||||
))}
|
||||
</div>
|
||||
)}
|
||||
</CardBody>
|
||||
</Card>
|
||||
</div>
|
||||
</AdminLayout>
|
||||
)
|
||||
}
|
||||
|
||||
export default Posts
|
||||
@@ -0,0 +1,588 @@
|
||||
// 文章采集编辑页面 - Preline UI 风格
|
||||
import { useState, useEffect } from 'react'
|
||||
import { useNavigate } from 'react-router-dom'
|
||||
import { AdminLayout } from '../components-preline/Sidebar'
|
||||
import { authApi } from '../api/auth'
|
||||
import { Card, CardHeader, CardTitle, CardDescription, CardBody, CardFooter } from '../components-preline/Card'
|
||||
import { Button } from '../components-preline/Button'
|
||||
import { Input, Textarea, Label, FormError } from '../components-preline/Input'
|
||||
import { postsApi } from '../api/posts'
|
||||
import { categoriesApi } from '../api/categories'
|
||||
import { tagsApi } from '../api/tags'
|
||||
import { API_BASE_URL } from '../api/config'
|
||||
|
||||
// 错误弹窗组件
|
||||
function ErrorModal({ message, onClose, onClear }) {
|
||||
if (!message) return null
|
||||
|
||||
return (
|
||||
<div className="fixed inset-0 bg-black/50 flex items-center justify-center z-50 p-4">
|
||||
<div className="bg-white rounded-xl shadow-xl max-w-md w-full p-6">
|
||||
<div className="flex items-center gap-3 mb-4">
|
||||
<div className="w-12 h-12 bg-red-100 rounded-full flex items-center justify-center">
|
||||
<svg className="w-6 h-6 text-red-600" fill="none" viewBox="0 0 24 24" stroke="currentColor">
|
||||
<path strokeLinecap="round" strokeLinejoin="round" strokeWidth={2} d="M6 18L18 6M6 6l12 12" />
|
||||
</svg>
|
||||
</div>
|
||||
<h3 className="text-lg font-semibold text-gray-900">采集失败</h3>
|
||||
</div>
|
||||
<p className="text-gray-600 mb-6 leading-relaxed">
|
||||
{message}
|
||||
</p>
|
||||
<div className="flex gap-3">
|
||||
<Button
|
||||
onClick={onClose}
|
||||
variant="primary"
|
||||
className="flex-1"
|
||||
>
|
||||
确定
|
||||
</Button>
|
||||
<Button
|
||||
onClick={() => {
|
||||
onClose()
|
||||
onClear()
|
||||
}}
|
||||
variant="secondary"
|
||||
>
|
||||
清空链接
|
||||
</Button>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
)
|
||||
}
|
||||
|
||||
export function UniversalCrawlEdit() {
|
||||
const navigate = useNavigate()
|
||||
|
||||
// 获取当前用户信息
|
||||
const user = JSON.parse(localStorage.getItem('user') || '{}')
|
||||
|
||||
// 采集步骤
|
||||
const [step, setStep] = useState('input') // input -> crawling -> edit
|
||||
const [crawlUrl, setCrawlUrl] = useState('')
|
||||
const [crawling, setCrawling] = useState(false)
|
||||
const [crawlError, setCrawlError] = useState('')
|
||||
|
||||
// 表单数据
|
||||
const [form, setForm] = useState({
|
||||
title: '',
|
||||
content: '',
|
||||
summary: '',
|
||||
category_id: '',
|
||||
tag_ids: [],
|
||||
is_published: false,
|
||||
is_draft: true
|
||||
})
|
||||
|
||||
// 采集的图片
|
||||
const [crawledImages, setCrawledImages] = useState([])
|
||||
|
||||
// 分类和标签
|
||||
const [categories, setCategories] = useState([])
|
||||
const [tags, setTags] = useState([])
|
||||
|
||||
// 保存状态
|
||||
const [saving, setSaving] = useState(false)
|
||||
|
||||
// 错误弹窗
|
||||
const [showErrorModal, setShowErrorModal] = useState(false)
|
||||
const [errorModalMessage, setErrorModalMessage] = useState('')
|
||||
|
||||
// 加载分类和标签,并清空之前的状态
|
||||
useEffect(() => {
|
||||
// 清空表单状态,防止显示之前缓存的数据
|
||||
setForm({
|
||||
title: '',
|
||||
content: '',
|
||||
summary: '',
|
||||
category_id: '',
|
||||
tag_ids: [],
|
||||
is_published: false,
|
||||
is_draft: true
|
||||
})
|
||||
setCrawledImages([])
|
||||
setStep('input')
|
||||
setCrawlError('')
|
||||
|
||||
const loadData = async () => {
|
||||
try {
|
||||
const [catRes, tagRes] = await Promise.all([
|
||||
categoriesApi.getCategories(),
|
||||
tagsApi.getTags()
|
||||
])
|
||||
setCategories(catRes.data)
|
||||
setTags(tagRes.data)
|
||||
} catch (error) {
|
||||
console.error('加载数据失败:', error)
|
||||
}
|
||||
}
|
||||
loadData()
|
||||
}, [])
|
||||
|
||||
// 开始采集
|
||||
const handleCrawl = async (e) => {
|
||||
e.preventDefault()
|
||||
|
||||
if (!crawlUrl.trim()) {
|
||||
alert('请输入文章链接')
|
||||
return
|
||||
}
|
||||
|
||||
if (!crawlUrl.startsWith('http://') && !crawlUrl.startsWith('https://')) {
|
||||
alert('请输入有效的URL(以 http:// 或 https:// 开头)')
|
||||
return
|
||||
}
|
||||
|
||||
setCrawling(true)
|
||||
setCrawlError('')
|
||||
|
||||
try {
|
||||
const token = localStorage.getItem('token')
|
||||
// 添加随机数防止缓存
|
||||
const nocache = Date.now()
|
||||
|
||||
// 构造请求头:有 token 则带 Bearer,同时启用 credentials 以支持 SSO Cookie 认证
|
||||
const headers = {
|
||||
'Content-Type': 'application/json',
|
||||
'Cache-Control': 'no-cache, no-store, must-revalidate',
|
||||
'Pragma': 'no-cache'
|
||||
}
|
||||
if (token) {
|
||||
headers['Authorization'] = `Bearer ${token}`
|
||||
}
|
||||
|
||||
const response = await fetch(`${API_BASE_URL}/universal-crawl/fetch?_=${nocache}`, {
|
||||
method: 'POST',
|
||||
headers,
|
||||
body: JSON.stringify({ url: crawlUrl }),
|
||||
credentials: 'include'
|
||||
})
|
||||
|
||||
const data = await response.json()
|
||||
|
||||
if (!data.success) {
|
||||
const errorMsg = data.error || '采集失败,请检查链接是否有效'
|
||||
setCrawlError(errorMsg)
|
||||
setErrorModalMessage(errorMsg)
|
||||
setShowErrorModal(true)
|
||||
setCrawling(false)
|
||||
return
|
||||
}
|
||||
|
||||
// 填充表单
|
||||
setForm({
|
||||
title: data.title || '',
|
||||
content: data.content || '',
|
||||
summary: data.summary || '',
|
||||
category_id: '',
|
||||
tag_ids: [],
|
||||
is_published: false,
|
||||
is_draft: true
|
||||
})
|
||||
|
||||
// 设置图片
|
||||
setCrawledImages(data.images || [])
|
||||
|
||||
// 进入编辑步骤
|
||||
setStep('edit')
|
||||
|
||||
} catch (error) {
|
||||
const errorMsg = '采集失败: ' + (error.message || '网络错误,请稍后重试')
|
||||
setCrawlError(errorMsg)
|
||||
setErrorModalMessage(errorMsg)
|
||||
setShowErrorModal(true)
|
||||
} finally {
|
||||
setCrawling(false)
|
||||
}
|
||||
}
|
||||
|
||||
// 保存文章
|
||||
const handleSubmit = async (e, isDraft = false) => {
|
||||
e.preventDefault()
|
||||
|
||||
if (!form.title.trim() || !form.content.trim()) {
|
||||
alert('请填写标题和内容')
|
||||
return
|
||||
}
|
||||
|
||||
setSaving(true)
|
||||
try {
|
||||
const data = {
|
||||
...form,
|
||||
category_id: form.category_id || null,
|
||||
is_draft: isDraft,
|
||||
is_published: !isDraft
|
||||
}
|
||||
|
||||
await postsApi.createPost(data)
|
||||
navigate('/admin/posts')
|
||||
} catch (error) {
|
||||
alert('保存失败: ' + (error.response?.data?.detail || '未知错误'))
|
||||
} finally {
|
||||
setSaving(false)
|
||||
}
|
||||
}
|
||||
|
||||
// 在内容中插入图片
|
||||
const insertImageToContent = (imagePath) => {
|
||||
const imageMarkdown = `\n\n\n\n`
|
||||
setForm({
|
||||
...form,
|
||||
content: form.content + imageMarkdown
|
||||
})
|
||||
}
|
||||
|
||||
// 取消/返回
|
||||
const handleCancel = () => {
|
||||
if (confirm('确定要取消吗?未保存的内容将丢失。')) {
|
||||
navigate('/admin/posts')
|
||||
}
|
||||
}
|
||||
|
||||
// 退出登录
|
||||
const handleLogout = async () => {
|
||||
localStorage.removeItem('token')
|
||||
await authApi.logout()
|
||||
localStorage.removeItem('user')
|
||||
window.location.href = '/login'
|
||||
}
|
||||
|
||||
// 输入URL界面
|
||||
if (step === 'input') {
|
||||
return (
|
||||
<AdminLayout user={user} onLogout={handleLogout}>
|
||||
<ErrorModal
|
||||
message={showErrorModal ? errorModalMessage : ''}
|
||||
onClose={() => setShowErrorModal(false)}
|
||||
onClear={() => setCrawlUrl('')}
|
||||
/>
|
||||
|
||||
<div className="p-6 w-full">
|
||||
{/* 页面标题 */}
|
||||
<div className="mb-6">
|
||||
<h1 className="text-2xl font-semibold text-gray-900">通用采集</h1>
|
||||
<p className="text-gray-500 mt-1">从网页自动采集文章内容(增强反爬能力)</p>
|
||||
</div>
|
||||
|
||||
<Card>
|
||||
<CardHeader>
|
||||
<div>
|
||||
<CardTitle>从网页自动采集</CardTitle>
|
||||
<CardDescription>输入文章链接,自动提取标题、正文和图片,自动处理编码和数学公式</CardDescription>
|
||||
</div>
|
||||
</CardHeader>
|
||||
<CardBody>
|
||||
<form onSubmit={handleCrawl} className="space-y-6">
|
||||
<div>
|
||||
<Label htmlFor="url">文章链接 URL</Label>
|
||||
<Input
|
||||
id="url"
|
||||
type="url"
|
||||
value={crawlUrl}
|
||||
onChange={(e) => setCrawlUrl(e.target.value)}
|
||||
placeholder="https://example.com/article"
|
||||
disabled={crawling}
|
||||
required
|
||||
/>
|
||||
<p className="text-sm text-gray-500 mt-1">
|
||||
支持各类网站的反爬场景采集
|
||||
</p>
|
||||
</div>
|
||||
|
||||
{crawlError && (
|
||||
<div className="bg-red-50 border border-red-200 rounded-lg p-4">
|
||||
<div className="flex items-center gap-2">
|
||||
<svg className="w-5 h-5 text-red-500" fill="none" viewBox="0 0 24 24" stroke="currentColor">
|
||||
<path strokeLinecap="round" strokeLinejoin="round" strokeWidth={2} d="M12 8v4m0 4h.01M21 12a9 9 0 11-18 0 9 9 0 0118 0z" />
|
||||
</svg>
|
||||
<span className="font-medium text-red-800">采集失败</span>
|
||||
</div>
|
||||
<p className="text-red-600 mt-1 text-sm">{crawlError}</p>
|
||||
</div>
|
||||
)}
|
||||
|
||||
<div className="flex gap-3">
|
||||
<Button
|
||||
type="submit"
|
||||
variant="primary"
|
||||
disabled={crawling}
|
||||
loading={crawling}
|
||||
>
|
||||
{crawling ? '采集中...' : '开始采集'}
|
||||
</Button>
|
||||
<Button
|
||||
type="button"
|
||||
variant="secondary"
|
||||
onClick={handleCancel}
|
||||
disabled={crawling}
|
||||
>
|
||||
取消
|
||||
</Button>
|
||||
</div>
|
||||
|
||||
{crawling && (
|
||||
<div className="text-center py-8">
|
||||
<div className="inline-flex items-center justify-center w-16 h-16 bg-blue-50 rounded-full mb-4">
|
||||
<svg className="animate-spin w-8 h-8 text-blue-600" viewBox="0 0 24 24" fill="none">
|
||||
<circle className="opacity-25" cx="12" cy="12" r="10" stroke="currentColor" strokeWidth="4" />
|
||||
<path className="opacity-75" fill="currentColor" d="M4 12a8 8 0 018-8V0C5.373 0 0 5.373 0 12h4z" />
|
||||
</svg>
|
||||
</div>
|
||||
<p className="text-gray-500">正在分析网页内容...</p>
|
||||
</div>
|
||||
)}
|
||||
</form>
|
||||
</CardBody>
|
||||
</Card>
|
||||
|
||||
<Card className="mt-6">
|
||||
<CardHeader>
|
||||
<div>
|
||||
<CardTitle>使用说明</CardTitle>
|
||||
<CardDescription>采集功能的使用注意事项</CardDescription>
|
||||
</div>
|
||||
</CardHeader>
|
||||
<CardBody>
|
||||
<ul className="space-y-3 text-sm text-gray-600">
|
||||
<li className="flex items-start gap-2">
|
||||
<svg className="w-5 h-5 text-blue-500 flex-shrink-0 mt-0.5" fill="none" viewBox="0 0 24 24" stroke="currentColor">
|
||||
<path strokeLinecap="round" strokeLinejoin="round" strokeWidth={2} d="M13 16h-1v-4h-1m1-4h.01M21 12a9 9 0 11-18 0 9 9 0 0118 0z" />
|
||||
</svg>
|
||||
<span>支持各类网站、技术博客、学术论文等公开内容的增强采集</span>
|
||||
</li>
|
||||
<li className="flex items-start gap-2">
|
||||
<svg className="w-5 h-5 text-blue-500 flex-shrink-0 mt-0.5" fill="none" viewBox="0 0 24 24" stroke="currentColor">
|
||||
<path strokeLinecap="round" strokeLinejoin="round" strokeWidth={2} d="M13 16h-1v-4h-1m1-4h.01M21 12a9 9 0 11-18 0 9 9 0 0118 0z" />
|
||||
</svg>
|
||||
<span>采集后需要人工编辑确认内容准确性</span>
|
||||
</li>
|
||||
<li className="flex items-start gap-2">
|
||||
<svg className="w-5 h-5 text-blue-500 flex-shrink-0 mt-0.5" fill="none" viewBox="0 0 24 24" stroke="currentColor">
|
||||
<path strokeLinecap="round" strokeLinejoin="round" strokeWidth={2} d="M13 16h-1v-4h-1m1-4h.01M21 12a9 9 0 11-18 0 9 9 0 0118 0z" />
|
||||
</svg>
|
||||
<span>系统会自动提取标题、正文和图片</span>
|
||||
</li>
|
||||
<li className="flex items-start gap-2">
|
||||
<svg className="w-5 h-5 text-blue-500 flex-shrink-0 mt-0.5" fill="none" viewBox="0 0 24 24" stroke="currentColor">
|
||||
<path strokeLinecap="round" strokeLinejoin="round" strokeWidth={2} d="M13 16h-1v-4h-1m1-4h.01M21 12a9 9 0 11-18 0 9 9 0 0118 0z" />
|
||||
</svg>
|
||||
<span>采集的内容默认保存为草稿,需要手动发布</span>
|
||||
</li>
|
||||
<li className="flex items-start gap-2">
|
||||
<svg className="w-5 h-5 text-blue-500 flex-shrink-0 mt-0.5" fill="none" viewBox="0 0 24 24" stroke="currentColor">
|
||||
<path strokeLinecap="round" strokeLinejoin="round" strokeWidth={2} d="M13 16h-1v-4h-1m1-4h.01M21 12a9 9 0 11-18 0 9 9 0 0118 0z" />
|
||||
</svg>
|
||||
<span>请尊重原作者版权,仅用于个人学习参考</span>
|
||||
</li>
|
||||
</ul>
|
||||
</CardBody>
|
||||
</Card>
|
||||
</div>
|
||||
</AdminLayout>
|
||||
)
|
||||
}
|
||||
|
||||
// 编辑界面
|
||||
return (
|
||||
<AdminLayout user={user} onLogout={handleLogout}>
|
||||
<div className="p-6 w-full">
|
||||
{/* 页面标题 */}
|
||||
<div className="mb-6 flex items-center justify-between">
|
||||
<div>
|
||||
<h1 className="text-2xl font-semibold text-gray-900">编辑通用采集内容</h1>
|
||||
<p className="text-gray-500 mt-1">确认并编辑通用采集的文章内容</p>
|
||||
</div>
|
||||
<div className="flex gap-3">
|
||||
<Button onClick={handleCancel} variant="secondary">
|
||||
取消
|
||||
</Button>
|
||||
<Button
|
||||
onClick={(e) => handleSubmit(e, true)}
|
||||
variant="secondary"
|
||||
disabled={saving}
|
||||
>
|
||||
{saving ? '保存中...' : '保存草稿'}
|
||||
</Button>
|
||||
<Button
|
||||
onClick={(e) => handleSubmit(e, false)}
|
||||
variant="primary"
|
||||
disabled={saving}
|
||||
>
|
||||
{saving ? '发布中...' : '发布文章'}
|
||||
</Button>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<div className="grid grid-cols-1 lg:grid-cols-3 gap-6">
|
||||
{/* 左侧:主要内容 */}
|
||||
<div className="lg:col-span-2 space-y-6">
|
||||
<Card>
|
||||
<CardHeader>
|
||||
<div>
|
||||
<CardTitle>文章内容</CardTitle>
|
||||
<CardDescription>编辑文章标题、摘要和正文</CardDescription>
|
||||
</div>
|
||||
</CardHeader>
|
||||
<CardBody className="space-y-6">
|
||||
<div>
|
||||
<Label htmlFor="title">文章标题 <span className="text-red-500">*</span></Label>
|
||||
<Input
|
||||
id="title"
|
||||
value={form.title}
|
||||
onChange={(e) => setForm({...form, title: e.target.value})}
|
||||
placeholder="请输入标题"
|
||||
required
|
||||
/>
|
||||
</div>
|
||||
|
||||
<div>
|
||||
<Label htmlFor="summary">文章摘要</Label>
|
||||
<Textarea
|
||||
id="summary"
|
||||
value={form.summary}
|
||||
onChange={(e) => setForm({...form, summary: e.target.value})}
|
||||
placeholder="简短描述文章内容(可选)"
|
||||
rows={3}
|
||||
/>
|
||||
</div>
|
||||
|
||||
<div>
|
||||
<Label htmlFor="content">正文内容 <span className="text-red-500">*</span></Label>
|
||||
<Textarea
|
||||
id="content"
|
||||
value={form.content}
|
||||
onChange={(e) => setForm({...form, content: e.target.value})}
|
||||
placeholder="支持 Markdown 格式"
|
||||
rows={20}
|
||||
required
|
||||
/>
|
||||
</div>
|
||||
</CardBody>
|
||||
</Card>
|
||||
</div>
|
||||
|
||||
{/* 右侧:设置和图片 */}
|
||||
<div className="space-y-6">
|
||||
{/* 分类和标签 */}
|
||||
<Card>
|
||||
<CardHeader>
|
||||
<div>
|
||||
<CardTitle>文章设置</CardTitle>
|
||||
<CardDescription>设置分类和标签</CardDescription>
|
||||
</div>
|
||||
</CardHeader>
|
||||
<CardBody className="space-y-4">
|
||||
<div>
|
||||
<Label htmlFor="category">分类</Label>
|
||||
<select
|
||||
id="category"
|
||||
value={form.category_id}
|
||||
onChange={(e) => setForm({...form, category_id: e.target.value})}
|
||||
className="w-full px-3 py-2 border border-gray-300 rounded-lg focus:ring-2 focus:ring-blue-500 focus:border-blue-500"
|
||||
>
|
||||
<option value="">未分类</option>
|
||||
{categories.map(cat => (
|
||||
<option key={cat.id} value={cat.id}>{cat.name}</option>
|
||||
))}
|
||||
</select>
|
||||
</div>
|
||||
|
||||
<div>
|
||||
<Label>标签</Label>
|
||||
<div className="max-h-40 overflow-y-auto border border-gray-300 rounded-lg p-3 space-y-2">
|
||||
{tags.map(tag => (
|
||||
<label key={tag.id} htmlFor={`tag-${tag.id}`} className="flex items-center gap-2 cursor-pointer hover:bg-gray-50 p-1 rounded">
|
||||
<input
|
||||
id={`tag-${tag.id}`}
|
||||
type="checkbox"
|
||||
checked={form.tag_ids.includes(tag.id)}
|
||||
onChange={(e) => {
|
||||
if (e.target.checked) {
|
||||
setForm({...form, tag_ids: [...form.tag_ids, tag.id]})
|
||||
} else {
|
||||
setForm({...form, tag_ids: form.tag_ids.filter(id => id !== tag.id)})
|
||||
}
|
||||
}}
|
||||
className="rounded border-gray-300 text-blue-600 focus:ring-blue-500"
|
||||
/>
|
||||
<span className="text-sm text-gray-700">{tag.name}</span>
|
||||
</label>
|
||||
))}
|
||||
</div>
|
||||
</div>
|
||||
</CardBody>
|
||||
</Card>
|
||||
|
||||
{/* 采集的图片 */}
|
||||
{crawledImages.length > 0 && (
|
||||
<Card>
|
||||
<CardHeader>
|
||||
<div>
|
||||
<CardTitle>采集的图片</CardTitle>
|
||||
<CardDescription>共 {crawledImages.length} 张图片,点击插入到文章</CardDescription>
|
||||
</div>
|
||||
</CardHeader>
|
||||
<CardBody>
|
||||
<div className="grid grid-cols-2 gap-3">
|
||||
{crawledImages.map((img, index) => {
|
||||
const displayUrl = img.local_path || img.original_url
|
||||
const insertUrl = img.local_path || img.original_url
|
||||
|
||||
return (
|
||||
<div key={index} className="relative group rounded-lg overflow-hidden border border-gray-200">
|
||||
<img
|
||||
src={displayUrl.startsWith('/uploads/') ? `${API_BASE_URL.replace('/api', '')}${displayUrl}` : displayUrl}
|
||||
alt={`图片${index + 1}`}
|
||||
className="w-full h-24 object-cover cursor-pointer"
|
||||
onClick={() => insertImageToContent(insertUrl)}
|
||||
/>
|
||||
<div
|
||||
className="absolute inset-0 bg-black/50 opacity-0 group-hover:opacity-100 flex items-center justify-center text-white text-xs cursor-pointer transition-opacity"
|
||||
onClick={() => insertImageToContent(insertUrl)}
|
||||
>
|
||||
点击插入
|
||||
</div>
|
||||
{img.id && (
|
||||
<div className="absolute top-1 right-1 bg-green-500 text-white text-[10px] px-1.5 py-0.5 rounded">
|
||||
✓ 已保存
|
||||
</div>
|
||||
)}
|
||||
</div>
|
||||
)
|
||||
})}
|
||||
</div>
|
||||
<p className="text-xs text-gray-500 mt-3">
|
||||
点击图片可插入到文章末尾(带✓的已保存到图库)
|
||||
</p>
|
||||
</CardBody>
|
||||
</Card>
|
||||
)}
|
||||
|
||||
{/* 来源信息 */}
|
||||
<Card>
|
||||
<CardHeader>
|
||||
<div>
|
||||
<CardTitle>来源</CardTitle>
|
||||
<CardDescription>文章来源链接</CardDescription>
|
||||
</div>
|
||||
</CardHeader>
|
||||
<CardBody>
|
||||
<a
|
||||
href={crawlUrl}
|
||||
target="_blank"
|
||||
rel="noopener noreferrer"
|
||||
className="text-sm text-blue-600 hover:text-blue-800 break-all hover:underline"
|
||||
>
|
||||
{crawlUrl}
|
||||
</a>
|
||||
</CardBody>
|
||||
</Card>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
</AdminLayout>
|
||||
)
|
||||
}
|
||||
|
||||
export default UniversalCrawlEdit
|
||||
@@ -0,0 +1,436 @@
|
||||
// 微信公众号文章采集页面
|
||||
import { useState, useEffect } from 'react'
|
||||
import { useNavigate } from 'react-router-dom'
|
||||
import { AdminLayout } from '../components-preline/Sidebar'
|
||||
import { Card, CardHeader, CardTitle, CardDescription, CardBody } from '../components-preline/Card'
|
||||
import { Button } from '../components-preline/Button'
|
||||
import { Input, Textarea, Label } from '../components-preline/Input'
|
||||
import api from '../api/config'
|
||||
|
||||
export function WechatCrawlEdit() {
|
||||
const navigate = useNavigate()
|
||||
const [step, setStep] = useState('input') // input | preview | saving | done
|
||||
const [url, setUrl] = useState('')
|
||||
const [loading, setLoading] = useState(false)
|
||||
const [error, setError] = useState('')
|
||||
|
||||
// 预览数据
|
||||
const [title, setTitle] = useState('')
|
||||
const [content, setContent] = useState('')
|
||||
const [summary, setSummary] = useState('')
|
||||
const [author, setAuthor] = useState('')
|
||||
const [coverImage, setCoverImage] = useState('')
|
||||
const [sourceUrl, setSourceUrl] = useState('')
|
||||
const [crawledImages, setCrawledImages] = useState([])
|
||||
|
||||
// 分类和标签
|
||||
const [categories, setCategories] = useState([])
|
||||
const [categoryId, setCategoryId] = useState('')
|
||||
const [tagInput, setTagInput] = useState('')
|
||||
const [saving, setSaving] = useState(false)
|
||||
|
||||
// 获取分类列表
|
||||
useEffect(() => {
|
||||
api.get('/categories').then(res => {
|
||||
setCategories(res.data || [])
|
||||
}).catch(() => {})
|
||||
}, [])
|
||||
|
||||
const handleCrawl = async () => {
|
||||
setError('')
|
||||
if (!url.trim()) {
|
||||
setError('请输入文章链接')
|
||||
return
|
||||
}
|
||||
if (!url.includes('mp.weixin.qq.com')) {
|
||||
setError('请输入微信公众号文章链接')
|
||||
return
|
||||
}
|
||||
setLoading(true)
|
||||
try {
|
||||
const res = await api.post('/wechat-crawl/preview', { url: url.trim() })
|
||||
const data = res.data
|
||||
setTitle(data.title || '')
|
||||
setContent(data.content_md || '')
|
||||
setSummary(data.summary || '')
|
||||
setAuthor(data.author || '')
|
||||
setCoverImage(data.cover_image || '')
|
||||
setSourceUrl(data.source_url || '')
|
||||
setCrawledImages(data.images || [])
|
||||
setStep('preview')
|
||||
} catch (err) {
|
||||
setError(err.response?.data?.detail || '采集失败,请检查链接是否有效')
|
||||
} finally {
|
||||
setLoading(false)
|
||||
}
|
||||
}
|
||||
|
||||
const savePost = async (asDraft = false) => {
|
||||
if (!title.trim()) {
|
||||
setError('请输入文章标题')
|
||||
return
|
||||
}
|
||||
if (!content.trim()) {
|
||||
setError('请输入文章内容')
|
||||
return
|
||||
}
|
||||
|
||||
setSaving(true)
|
||||
setError('')
|
||||
|
||||
try {
|
||||
const tagNames = tagInput.split(/[,,]/).map(t => t.trim()).filter(Boolean)
|
||||
await api.post('/wechat-crawl/save', {
|
||||
title: title.trim(),
|
||||
content,
|
||||
summary: summary.trim(),
|
||||
cover_image: coverImage,
|
||||
category_id: categoryId ? parseInt(categoryId) : null,
|
||||
tag_names: tagNames,
|
||||
source_url: sourceUrl,
|
||||
author: author,
|
||||
is_draft: asDraft,
|
||||
})
|
||||
|
||||
setStep('done')
|
||||
} catch (err) {
|
||||
console.error('保存失败:', err)
|
||||
setError(err.response?.data?.detail || '保存失败,请重试')
|
||||
} finally {
|
||||
setSaving(false)
|
||||
}
|
||||
}
|
||||
|
||||
const handleSaveDraft = () => savePost(true)
|
||||
const handlePublish = () => savePost(false)
|
||||
|
||||
const handleCancel = () => {
|
||||
navigate('/admin/posts')
|
||||
}
|
||||
|
||||
const handleReset = () => {
|
||||
setStep('input')
|
||||
setUrl('')
|
||||
setTitle('')
|
||||
setContent('')
|
||||
setSummary('')
|
||||
setAuthor('')
|
||||
setCoverImage('')
|
||||
setSourceUrl('')
|
||||
setCrawledImages([])
|
||||
setCategoryId('')
|
||||
setTagInput('')
|
||||
setError('')
|
||||
}
|
||||
|
||||
// 将图片插入正文光标位置
|
||||
const insertImageIntoContent = (src) => {
|
||||
const textarea = document.getElementById('article-content')
|
||||
if (!textarea) return
|
||||
|
||||
const imageMarkdown = `\n\n\n\n`
|
||||
const start = textarea.selectionStart
|
||||
const end = textarea.selectionEnd
|
||||
const newContent = content.substring(0, start) + imageMarkdown + content.substring(end)
|
||||
setContent(newContent)
|
||||
|
||||
// 重新设置光标位置
|
||||
setTimeout(() => {
|
||||
textarea.focus()
|
||||
const newCursorPosition = start + imageMarkdown.length
|
||||
textarea.setSelectionRange(newCursorPosition, newCursorPosition)
|
||||
}, 0)
|
||||
}
|
||||
|
||||
return (
|
||||
<AdminLayout>
|
||||
{/* 步骤1:输入 URL */}
|
||||
{step === 'input' && (
|
||||
<div className="p-6">
|
||||
<div className="max-w-2xl mx-auto">
|
||||
{/* 错误提示 */}
|
||||
{error && (
|
||||
<div className="mb-4 bg-red-50 border border-red-200 text-red-700 px-4 py-3 rounded-lg text-sm">
|
||||
{error}
|
||||
</div>
|
||||
)}
|
||||
|
||||
<Card>
|
||||
<CardHeader>
|
||||
<CardTitle>公众号文章采集</CardTitle>
|
||||
<CardDescription>输入微信公众号文章链接,自动采集并入库</CardDescription>
|
||||
</CardHeader>
|
||||
<CardBody>
|
||||
<div className="space-y-4">
|
||||
<div>
|
||||
<Label>文章链接</Label>
|
||||
<Input
|
||||
placeholder="https://mp.weixin.qq.com/s/xxxxxx"
|
||||
value={url}
|
||||
onChange={(e) => setUrl(e.target.value)}
|
||||
onKeyDown={(e) => e.key === 'Enter' && handleCrawl()}
|
||||
/>
|
||||
<p className="text-xs text-gray-500 mt-1">支持 mp.weixin.qq.com 域名</p>
|
||||
</div>
|
||||
<div className="flex items-center gap-3">
|
||||
<Button
|
||||
variant="primary"
|
||||
onClick={handleCrawl}
|
||||
disabled={loading}
|
||||
>
|
||||
{loading ? (
|
||||
<>
|
||||
<svg className="animate-spin -ml-1 mr-2 h-4 w-4 text-white" fill="none" viewBox="0 0 24 24">
|
||||
<circle className="opacity-25" cx="12" cy="12" r="10" stroke="currentColor" strokeWidth="4" />
|
||||
<path className="opacity-75" fill="currentColor" d="M4 12a8 8 0 018-8V0C5.373 0 0 5.373 0 12h4z" />
|
||||
</svg>
|
||||
采集中...
|
||||
</>
|
||||
) : (
|
||||
<>
|
||||
<svg className="w-4 h-4 mr-2" fill="none" viewBox="0 0 24 24" stroke="currentColor">
|
||||
<path strokeLinecap="round" strokeLinejoin="round" strokeWidth={2} d="M7 16a4 4 0 01-.88-7.903A5 5 0 1115.9 6L16 6a5 5 0 011 9.9M15 13l-3-3m0 0l-3 3m3-3v12" />
|
||||
</svg>
|
||||
开始采集
|
||||
</>
|
||||
)}
|
||||
</Button>
|
||||
<Button variant="secondary" onClick={() => navigate('/admin/posts')}>
|
||||
返回文章列表
|
||||
</Button>
|
||||
</div>
|
||||
</div>
|
||||
</CardBody>
|
||||
</Card>
|
||||
</div>
|
||||
</div>
|
||||
)}
|
||||
|
||||
{/* 步骤2:预览编辑 */}
|
||||
{step === 'preview' && (
|
||||
<div className="p-6">
|
||||
{/* 错误提示 */}
|
||||
{error && (
|
||||
<div className="mb-4 bg-red-50 border border-red-200 text-red-700 px-4 py-3 rounded-lg text-sm">
|
||||
{error}
|
||||
</div>
|
||||
)}
|
||||
|
||||
{/* 顶部操作栏 */}
|
||||
<div className="mb-6 flex items-center justify-between">
|
||||
<Button variant="ghost" onClick={() => navigate('/admin/posts')} className="flex items-center gap-2">
|
||||
<svg className="w-4 h-4" fill="none" viewBox="0 0 24 24" stroke="currentColor">
|
||||
<path strokeLinecap="round" strokeLinejoin="round" strokeWidth={2} d="M10 19l-7-7m0 0l7-7m-7 7h18" />
|
||||
</svg>
|
||||
返回文章列表
|
||||
</Button>
|
||||
<div className="flex items-center gap-3">
|
||||
<Button variant="secondary" onClick={handleSaveDraft} disabled={saving}>
|
||||
{saving ? '保存中...' : '保存草稿'}
|
||||
</Button>
|
||||
<Button variant="primary" onClick={handlePublish} disabled={saving}>
|
||||
{saving ? '发布中...' : '发布文章'}
|
||||
</Button>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<div className="grid grid-cols-1 lg:grid-cols-[1fr_384px] gap-6">
|
||||
{/* 左侧:文章内容 */}
|
||||
<div className="space-y-6">
|
||||
<Card>
|
||||
<CardBody className="p-6">
|
||||
<div className="space-y-5">
|
||||
{/* 文章标题 */}
|
||||
<div>
|
||||
<Label className="text-sm font-medium text-gray-700 mb-1.5 block">
|
||||
文章标题 <span className="text-red-500">*</span>
|
||||
</Label>
|
||||
<Input
|
||||
value={title}
|
||||
onChange={(e) => setTitle(e.target.value)}
|
||||
placeholder="请输入文章标题"
|
||||
/>
|
||||
</div>
|
||||
|
||||
{/* 文章摘要 */}
|
||||
<div>
|
||||
<Label className="text-sm font-medium text-gray-700 mb-1.5 block">
|
||||
文章摘要
|
||||
</Label>
|
||||
<Textarea
|
||||
rows={3}
|
||||
value={summary}
|
||||
onChange={(e) => setSummary(e.target.value)}
|
||||
placeholder="请输入文章摘要..."
|
||||
/>
|
||||
</div>
|
||||
|
||||
{/* 公众号/作者 */}
|
||||
<div>
|
||||
<Label className="text-sm font-medium text-gray-700 mb-1.5 block">
|
||||
公众号/作者
|
||||
</Label>
|
||||
<Input
|
||||
value={author}
|
||||
onChange={(e) => setAuthor(e.target.value)}
|
||||
placeholder="公众号名称"
|
||||
/>
|
||||
</div>
|
||||
|
||||
{/* 来源链接 */}
|
||||
<div>
|
||||
<Label className="text-sm font-medium text-gray-700 mb-1.5 block">
|
||||
来源链接
|
||||
</Label>
|
||||
<Input
|
||||
value={sourceUrl}
|
||||
onChange={(e) => setSourceUrl(e.target.value)}
|
||||
placeholder="原文链接"
|
||||
/>
|
||||
</div>
|
||||
|
||||
{/* 文章内容 */}
|
||||
<div>
|
||||
<Label className="text-sm font-medium text-gray-700 mb-1.5 block">
|
||||
文章内容 <span className="text-red-500">*</span>
|
||||
</Label>
|
||||
<Textarea
|
||||
id="article-content"
|
||||
rows={25}
|
||||
value={content}
|
||||
onChange={(e) => setContent(e.target.value)}
|
||||
placeholder="请输入文章内容..."
|
||||
className="font-mono text-sm"
|
||||
/>
|
||||
</div>
|
||||
</div>
|
||||
</CardBody>
|
||||
</Card>
|
||||
</div>
|
||||
|
||||
{/* 右侧:文章设置 */}
|
||||
<div className="space-y-6">
|
||||
{/* 文章设置 */}
|
||||
<Card>
|
||||
<CardHeader>
|
||||
<CardTitle>文章设置</CardTitle>
|
||||
</CardHeader>
|
||||
<CardBody className="p-6">
|
||||
<div className="space-y-5">
|
||||
{/* 分类 */}
|
||||
<div>
|
||||
<Label className="text-sm font-medium text-gray-700 mb-1.5 block">
|
||||
分类
|
||||
</Label>
|
||||
<select
|
||||
className="w-full border border-gray-300 rounded-lg px-3 py-2 text-sm focus:outline-none focus:ring-2 focus:ring-blue-500 focus:border-blue-500 bg-white"
|
||||
value={categoryId}
|
||||
onChange={(e) => setCategoryId(e.target.value)}
|
||||
>
|
||||
<option value="">选择分类</option>
|
||||
{categories.map(category => (
|
||||
<option key={category.id} value={category.id}>{category.name}</option>
|
||||
))}
|
||||
</select>
|
||||
</div>
|
||||
|
||||
{/* 标签 */}
|
||||
<div>
|
||||
<Label className="text-sm font-medium text-gray-700 mb-1.5 block">
|
||||
标签
|
||||
</Label>
|
||||
<Input
|
||||
value={tagInput}
|
||||
onChange={(e) => setTagInput(e.target.value)}
|
||||
placeholder="用逗号分隔多个标签"
|
||||
/>
|
||||
<p className="text-xs text-gray-500 mt-1">例如:技术, 教程, 笔记</p>
|
||||
</div>
|
||||
|
||||
{/* 封面图 */}
|
||||
{coverImage && (
|
||||
<div>
|
||||
<Label className="text-sm font-medium text-gray-700 mb-1.5 block">
|
||||
封面图
|
||||
</Label>
|
||||
<div className="border border-gray-200 rounded-lg overflow-hidden">
|
||||
<img
|
||||
src={coverImage}
|
||||
alt="封面图"
|
||||
className="w-full h-40 object-cover"
|
||||
/>
|
||||
</div>
|
||||
</div>
|
||||
)}
|
||||
</div>
|
||||
</CardBody>
|
||||
</Card>
|
||||
|
||||
{/* 采集的图片 */}
|
||||
<Card>
|
||||
<CardHeader>
|
||||
<CardTitle>采集的图片</CardTitle>
|
||||
<CardDescription>点击缩略图可插入到正文中</CardDescription>
|
||||
</CardHeader>
|
||||
<CardBody className="p-6">
|
||||
{crawledImages.length === 0 ? (
|
||||
<div className="text-center py-6 text-gray-500 text-sm">
|
||||
未采集到图片
|
||||
</div>
|
||||
) : (
|
||||
<div className="grid grid-cols-3 gap-2">
|
||||
{crawledImages.map((image, index) => (
|
||||
<button
|
||||
key={index}
|
||||
onClick={() => insertImageIntoContent(image.original_url)}
|
||||
className="relative aspect-square border border-gray-200 rounded-lg overflow-hidden hover:border-blue-500 hover:ring-2 hover:ring-blue-200 transition-all cursor-pointer"
|
||||
title="点击插入正文"
|
||||
>
|
||||
<img
|
||||
src={image.original_url}
|
||||
alt={image.description || `图片 ${index + 1}`}
|
||||
className="w-full h-full object-cover"
|
||||
loading="lazy"
|
||||
/>
|
||||
</button>
|
||||
))}
|
||||
</div>
|
||||
)}
|
||||
</CardBody>
|
||||
</Card>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
)}
|
||||
|
||||
{/* 步骤3:完成 */}
|
||||
{step === 'done' && (
|
||||
<div className="p-6">
|
||||
<div className="max-w-lg mx-auto">
|
||||
<Card>
|
||||
<CardBody className="text-center py-12">
|
||||
<div className="w-16 h-16 bg-green-100 rounded-full flex items-center justify-center mx-auto mb-4">
|
||||
<svg className="w-8 h-8 text-green-600" fill="none" viewBox="0 0 24 24" stroke="currentColor">
|
||||
<path strokeLinecap="round" strokeLinejoin="round" strokeWidth={2} d="M5 13l4 4L19 7" />
|
||||
</svg>
|
||||
</div>
|
||||
<h3 className="text-xl font-semibold text-gray-900 mb-2">文章已保存</h3>
|
||||
<p className="text-gray-500 mb-6">公众号文章已成功采集并入库</p>
|
||||
<div className="flex items-center justify-center gap-3">
|
||||
<Button variant="primary" onClick={() => navigate('/admin/posts')}>
|
||||
返回文章列表
|
||||
</Button>
|
||||
<Button variant="secondary" onClick={handleReset}>
|
||||
继续采集
|
||||
</Button>
|
||||
</div>
|
||||
</CardBody>
|
||||
</Card>
|
||||
</div>
|
||||
</div>
|
||||
)}
|
||||
</AdminLayout>
|
||||
)
|
||||
}
|
||||
|
||||
export default WechatCrawlEdit
|
||||
@@ -0,0 +1,316 @@
|
||||
// 分类管理页面 - Preline UI 风格
|
||||
import { useState, useEffect } from 'react'
|
||||
import { AdminLayout } from '../../components-preline/Sidebar'
|
||||
import { authApi } from '../../api/auth'
|
||||
import { Card, CardHeader, CardTitle, CardDescription, CardBody, CardFooter } from '../../components-preline/Card'
|
||||
import { Button } from '../../components-preline/Button'
|
||||
import { Input, Textarea, Label } from '../../components-preline/Input'
|
||||
import { categoriesApi } from '../../api/categories'
|
||||
|
||||
// 分类列表项
|
||||
function CategoryItem({ category, isEditing, onEdit, onDelete }) {
|
||||
return (
|
||||
<div className={`flex items-center justify-between p-4 border-b border-gray-100 last:border-0 transition-colors ${
|
||||
isEditing ? 'bg-blue-50' : 'hover:bg-gray-50'
|
||||
}`}>
|
||||
<div className="flex-1 min-w-0">
|
||||
<div className="flex items-center gap-3">
|
||||
<div className="w-10 h-10 bg-blue-100 rounded-lg flex items-center justify-center">
|
||||
<svg className="w-5 h-5 text-blue-600" fill="none" viewBox="0 0 24 24" stroke="currentColor">
|
||||
<path strokeLinecap="round" strokeLinejoin="round" strokeWidth={2} d="M3 7v10a2 2 0 002 2h14a2 2 0 002-2V9a2 2 0 00-2-2h-6l-2-2H5a2 2 0 00-2 2z" />
|
||||
</svg>
|
||||
</div>
|
||||
<div>
|
||||
<div className="flex items-center gap-2">
|
||||
<h4 className="font-medium text-gray-900">{category.name}</h4>
|
||||
<span className="inline-flex items-center px-2 py-0.5 rounded-full text-xs font-medium bg-gray-100 text-gray-700">
|
||||
{category.post_count || 0} 篇
|
||||
</span>
|
||||
</div>
|
||||
{category.description && (
|
||||
<p className="text-sm text-gray-500 mt-0.5 truncate">
|
||||
{category.description}
|
||||
</p>
|
||||
)}
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<div className="flex items-center gap-2 ml-4">
|
||||
<Button
|
||||
variant="secondary"
|
||||
size="sm"
|
||||
onClick={() => onEdit(category)}
|
||||
>
|
||||
<svg className="w-4 h-4 mr-1" fill="none" viewBox="0 0 24 24" stroke="currentColor">
|
||||
<path strokeLinecap="round" strokeLinejoin="round" strokeWidth={2} d="M11 5H6a2 2 0 00-2 2v11a2 2 0 002 2h11a2 2 0 002-2v-5m-1.414-9.414a2 2 0 112.828 2.828L11.828 15H9v-2.828l8.586-8.586z" />
|
||||
</svg>
|
||||
编辑
|
||||
</Button>
|
||||
<Button
|
||||
variant="danger"
|
||||
size="sm"
|
||||
onClick={() => onDelete(category)}
|
||||
>
|
||||
<svg className="w-4 h-4 mr-1" fill="none" viewBox="0 0 24 24" stroke="currentColor">
|
||||
<path strokeLinecap="round" strokeLinejoin="round" strokeWidth={2} d="M19 7l-.867 12.142A2 2 0 0116.138 21H7.862a2 2 0 01-1.995-1.858L5 7m5 4v6m4-6v6m1-10V4a1 1 0 00-1-1h-4a1 1 0 00-1 1v3M4 7h16" />
|
||||
</svg>
|
||||
删除
|
||||
</Button>
|
||||
</div>
|
||||
</div>
|
||||
)
|
||||
}
|
||||
|
||||
export function Categories() {
|
||||
const [categories, setCategories] = useState([])
|
||||
const [loading, setLoading] = useState(true)
|
||||
const [editingId, setEditingId] = useState(null)
|
||||
const [form, setForm] = useState({ name: '', description: '' })
|
||||
const [saving, setSaving] = useState(false)
|
||||
|
||||
// 获取当前用户信息
|
||||
const user = JSON.parse(localStorage.getItem('user') || '{}')
|
||||
|
||||
useEffect(() => {
|
||||
fetchCategories()
|
||||
}, [])
|
||||
|
||||
const fetchCategories = async () => {
|
||||
try {
|
||||
const res = await categoriesApi.getCategories()
|
||||
setCategories(res.data)
|
||||
} catch (error) {
|
||||
alert('获取分类失败')
|
||||
} finally {
|
||||
setLoading(false)
|
||||
}
|
||||
}
|
||||
|
||||
const handleSubmit = async (e) => {
|
||||
e.preventDefault()
|
||||
|
||||
if (!form.name.trim()) {
|
||||
alert('请输入分类名称')
|
||||
return
|
||||
}
|
||||
|
||||
setSaving(true)
|
||||
try {
|
||||
if (editingId) {
|
||||
await categoriesApi.updateCategory(editingId, form)
|
||||
} else {
|
||||
await categoriesApi.createCategory(form)
|
||||
}
|
||||
setForm({ name: '', description: '' })
|
||||
setEditingId(null)
|
||||
fetchCategories()
|
||||
} catch (error) {
|
||||
alert(error.response?.data?.detail || '保存失败')
|
||||
} finally {
|
||||
setSaving(false)
|
||||
}
|
||||
}
|
||||
|
||||
const handleEdit = (category) => {
|
||||
setEditingId(category.id)
|
||||
setForm({
|
||||
name: category.name,
|
||||
description: category.description || ''
|
||||
})
|
||||
}
|
||||
|
||||
const handleDelete = async (category) => {
|
||||
const msg = category?.post_count > 0
|
||||
? `该分类下有 ${category.post_count} 篇文章,删除后这些文章将变为未分类。确定删除吗?`
|
||||
: '确定要删除这个分类吗?'
|
||||
|
||||
if (!confirm(msg)) return
|
||||
|
||||
try {
|
||||
await categoriesApi.deleteCategory(category.id)
|
||||
if (editingId === category.id) {
|
||||
handleCancel()
|
||||
}
|
||||
fetchCategories()
|
||||
} catch (error) {
|
||||
alert('删除失败: ' + (error.response?.data?.detail || '未知错误'))
|
||||
}
|
||||
}
|
||||
|
||||
const handleCancel = () => {
|
||||
setEditingId(null)
|
||||
setForm({ name: '', description: '' })
|
||||
}
|
||||
|
||||
const handleLogout = async () => {
|
||||
localStorage.removeItem('token')
|
||||
await authApi.logout()
|
||||
localStorage.removeItem('user')
|
||||
window.location.href = '/login'
|
||||
}
|
||||
|
||||
return (
|
||||
<AdminLayout user={user} onLogout={handleLogout}>
|
||||
<div className="p-6 w-full">
|
||||
{/* 页面标题 */}
|
||||
<div className="mb-6">
|
||||
<h1 className="text-2xl font-semibold text-gray-900">分类管理</h1>
|
||||
<p className="text-gray-500 mt-1">管理博客文章分类(最多 25 个)</p>
|
||||
</div>
|
||||
|
||||
<div className="grid grid-cols-1 lg:grid-cols-3 gap-6">
|
||||
{/* 分类列表 */}
|
||||
<div className="lg:col-span-2">
|
||||
<Card>
|
||||
<CardHeader>
|
||||
<div>
|
||||
<CardTitle>分类列表</CardTitle>
|
||||
<CardDescription>共 {categories.length} 个分类,最多 25 个</CardDescription>
|
||||
</div>
|
||||
</CardHeader>
|
||||
<CardBody className="p-0">
|
||||
{loading ? (
|
||||
<div className="flex items-center justify-center py-12">
|
||||
<svg className="animate-spin h-5 w-5 text-gray-400" viewBox="0 0 24 24" fill="none">
|
||||
<circle className="opacity-25" cx="12" cy="12" r="10" stroke="currentColor" strokeWidth="4" />
|
||||
<path className="opacity-75" fill="currentColor" d="M4 12a8 8 0 018-8V0C5.373 0 0 5.373 0 12h4z" />
|
||||
</svg>
|
||||
<span className="ml-2 text-gray-500">加载中...</span>
|
||||
</div>
|
||||
) : categories.length === 0 ? (
|
||||
<div className="text-center py-12">
|
||||
<div className="w-16 h-16 bg-gray-100 rounded-full flex items-center justify-center mx-auto mb-4">
|
||||
<svg className="w-8 h-8 text-gray-400" fill="none" viewBox="0 0 24 24" stroke="currentColor">
|
||||
<path strokeLinecap="round" strokeLinejoin="round" strokeWidth={2} d="M3 7v10a2 2 0 002 2h14a2 2 0 002-2V9a2 2 0 00-2-2h-6l-2-2H5a2 2 0 00-2 2z" />
|
||||
</svg>
|
||||
</div>
|
||||
<p className="text-gray-500">暂无分类,请在右侧添加</p>
|
||||
</div>
|
||||
) : (
|
||||
<div className="divide-y divide-gray-100">
|
||||
{categories.map(cat => (
|
||||
<CategoryItem
|
||||
key={cat.id}
|
||||
category={cat}
|
||||
isEditing={editingId === cat.id}
|
||||
onEdit={handleEdit}
|
||||
onDelete={handleDelete}
|
||||
/>
|
||||
))}
|
||||
</div>
|
||||
)}
|
||||
</CardBody>
|
||||
</Card>
|
||||
</div>
|
||||
|
||||
{/* 添加/编辑表单 */}
|
||||
<div>
|
||||
<Card>
|
||||
<CardHeader>
|
||||
<div>
|
||||
<CardTitle>{editingId ? '编辑分类' : '添加分类'}</CardTitle>
|
||||
<CardDescription>{editingId ? '修改分类信息' : '创建新的文章分类'}</CardDescription>
|
||||
</div>
|
||||
</CardHeader>
|
||||
<CardBody>
|
||||
<form onSubmit={handleSubmit} className="space-y-4">
|
||||
<div>
|
||||
<Label htmlFor="category_name">
|
||||
分类名称 <span className="text-red-500">*</span>
|
||||
</Label>
|
||||
<Input
|
||||
id="category_name"
|
||||
value={form.name}
|
||||
onChange={(e) => setForm({ ...form, name: e.target.value })}
|
||||
placeholder="如:技术笔记"
|
||||
maxLength={50}
|
||||
required
|
||||
/>
|
||||
</div>
|
||||
|
||||
<div>
|
||||
<Label htmlFor="category_description">分类描述</Label>
|
||||
<Textarea
|
||||
id="category_description"
|
||||
value={form.description}
|
||||
onChange={(e) => setForm({ ...form, description: e.target.value })}
|
||||
placeholder="可选,简短描述该分类的内容"
|
||||
rows={3}
|
||||
maxLength={200}
|
||||
/>
|
||||
<p className="text-xs text-gray-500 mt-1">最多 200 字</p>
|
||||
</div>
|
||||
</form>
|
||||
</CardBody>
|
||||
<CardFooter>
|
||||
{editingId && (
|
||||
<Button
|
||||
variant="secondary"
|
||||
onClick={handleCancel}
|
||||
>
|
||||
取消编辑
|
||||
</Button>
|
||||
)}
|
||||
<Button
|
||||
variant="primary"
|
||||
onClick={handleSubmit}
|
||||
loading={saving}
|
||||
disabled={!editingId && categories.length >= 25}
|
||||
className="ml-auto"
|
||||
>
|
||||
{saving ? '保存中...' : (editingId ? '更新分类' : '添加分类')}
|
||||
</Button>
|
||||
</CardFooter>
|
||||
|
||||
{!editingId && categories.length >= 25 && (
|
||||
<div className="px-6 pb-6">
|
||||
<div className="bg-yellow-50 border border-yellow-200 rounded-lg p-3 flex items-center gap-2">
|
||||
<svg className="w-5 h-5 text-yellow-600 flex-shrink-0" fill="none" viewBox="0 0 24 24" stroke="currentColor">
|
||||
<path strokeLinecap="round" strokeLinejoin="round" strokeWidth={2} d="M12 9v2m0 4h.01m-6.938 4h13.856c1.54 0 2.502-1.667 1.732-3L13.732 4c-.77-1.333-2.694-1.333-3.464 0L3.34 16c-.77 1.333.192 3 1.732 3z" />
|
||||
</svg>
|
||||
<span className="text-sm text-yellow-800">已达到分类数量上限(25个)</span>
|
||||
</div>
|
||||
</div>
|
||||
)}
|
||||
</Card>
|
||||
|
||||
{/* 提示信息 */}
|
||||
<Card className="mt-6 bg-blue-50 border-blue-100">
|
||||
<CardBody>
|
||||
<div className="flex items-start gap-3">
|
||||
<svg className="w-5 h-5 text-blue-600 flex-shrink-0 mt-0.5" fill="none" viewBox="0 0 24 24" stroke="currentColor">
|
||||
<path strokeLinecap="round" strokeLinejoin="round" strokeWidth={2} d="M13 16h-1v-4h-1m1-4h.01M21 12a9 9 0 11-18 0 9 9 0 0118 0z" />
|
||||
</svg>
|
||||
<div>
|
||||
<p className="font-medium text-gray-900 mb-1">使用说明</p>
|
||||
<ul className="space-y-1.5 text-sm text-gray-600">
|
||||
<li className="flex items-center gap-1">
|
||||
<span className="w-1 h-1 bg-gray-400 rounded-full"></span>
|
||||
最多可创建 25 个分类
|
||||
</li>
|
||||
<li className="flex items-center gap-1">
|
||||
<span className="w-1 h-1 bg-gray-400 rounded-full"></span>
|
||||
删除分类不会删除文章
|
||||
</li>
|
||||
<li className="flex items-center gap-1">
|
||||
<span className="w-1 h-1 bg-gray-400 rounded-full"></span>
|
||||
文章将变为未分类状态
|
||||
</li>
|
||||
<li className="flex items-center gap-1">
|
||||
<span className="w-1 h-1 bg-gray-400 rounded-full"></span>
|
||||
分类名称不能重复
|
||||
</li>
|
||||
</ul>
|
||||
</div>
|
||||
</div>
|
||||
</CardBody>
|
||||
</Card>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
</AdminLayout>
|
||||
)
|
||||
}
|
||||
|
||||
export default Categories
|
||||
@@ -0,0 +1,505 @@
|
||||
// 图片管理页面 - Preline UI 风格
|
||||
import { useState, useEffect, useRef } from 'react'
|
||||
import { AdminLayout } from '../../components-preline/Sidebar'
|
||||
import { authApi } from '../../api/auth'
|
||||
import { Card, CardHeader, CardTitle, CardDescription, CardBody, CardFooter } from '../../components-preline/Card'
|
||||
import { Button } from '../../components-preline/Button'
|
||||
import api, { API_BASE_URL } from '../../api/config'
|
||||
|
||||
// 图片网格项
|
||||
function ImageGridItem({ image, onClick, getImageUrl, formatFileSize }) {
|
||||
return (
|
||||
<div
|
||||
className="group relative aspect-square rounded-lg overflow-hidden cursor-pointer bg-gray-100 border border-gray-200 hover:border-blue-400 hover:shadow-md transition-all"
|
||||
onClick={() => onClick(image)}
|
||||
>
|
||||
{/* 缩略图 */}
|
||||
<img
|
||||
src={image.thumb_path ? getImageUrl(image.thumb_path) : getImageUrl(image.file_path)}
|
||||
alt={image.original_name}
|
||||
className="w-full h-full object-cover transition-transform duration-300 group-hover:scale-105"
|
||||
loading="lazy"
|
||||
/>
|
||||
|
||||
{/* 悬停遮罩 */}
|
||||
<div className="absolute inset-0 bg-gradient-to-t from-black/80 via-black/40 to-transparent opacity-0 group-hover:opacity-100 transition-opacity flex flex-col items-center justify-end pb-4 text-white text-xs">
|
||||
<p className="truncate w-full px-2 text-center font-medium mb-1">
|
||||
{image.original_name}
|
||||
</p>
|
||||
<div className="flex items-center gap-2 text-gray-300">
|
||||
<span>{formatFileSize(image.file_size)}</span>
|
||||
{image.width && image.height && (
|
||||
<span>• {image.width}×{image.height}</span>
|
||||
)}
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
)
|
||||
}
|
||||
|
||||
// 图片预览弹窗
|
||||
function ImagePreviewModal({ image, onClose, onCopyMarkdown, onCopyUrl, onDelete, getImageUrl, formatFileSize }) {
|
||||
if (!image) return null
|
||||
|
||||
return (
|
||||
<div
|
||||
className="fixed inset-0 bg-black/70 backdrop-blur-sm z-50 flex items-center justify-center p-4"
|
||||
onClick={onClose}
|
||||
>
|
||||
<div
|
||||
className="bg-white rounded-xl shadow-2xl max-w-4xl w-full max-h-[90vh] overflow-hidden"
|
||||
onClick={(e) => e.stopPropagation()}
|
||||
>
|
||||
{/* 图片 */}
|
||||
<div className="bg-gray-100 flex items-center justify-center p-6 min-h-[300px]">
|
||||
<img
|
||||
src={getImageUrl(image.file_path)}
|
||||
alt={image.original_name}
|
||||
className="max-w-full max-h-[50vh] object-contain rounded-lg shadow-lg"
|
||||
/>
|
||||
</div>
|
||||
|
||||
{/* 信息栏 */}
|
||||
<div className="p-6 border-t border-gray-100">
|
||||
<div className="flex flex-col md:flex-row md:items-center md:justify-between gap-4">
|
||||
<div>
|
||||
<h3 className="font-semibold text-gray-900 text-lg truncate max-w-md" title={image.original_name}>
|
||||
{image.original_name}
|
||||
</h3>
|
||||
<div className="flex items-center gap-3 text-sm text-gray-500 mt-1">
|
||||
<span className="flex items-center gap-1">
|
||||
<svg className="w-4 h-4" fill="none" viewBox="0 0 24 24" stroke="currentColor">
|
||||
<path strokeLinecap="round" strokeLinejoin="round" strokeWidth={2} d="M4 7v10c0 2.21 3.582 4 8 4s8-1.79 8-4V7M4 7c0 2.21 3.582 4 8 4s8-1.79 8-4M4 7c0-2.21 3.582-4 8-4s8 1.79 8 4m0 5c0 2.21-3.582 4-8 4s-8-1.79-8-4" />
|
||||
</svg>
|
||||
{formatFileSize(image.file_size)}
|
||||
</span>
|
||||
{image.width && image.height && (
|
||||
<span className="flex items-center gap-1">
|
||||
<svg className="w-4 h-4" fill="none" viewBox="0 0 24 24" stroke="currentColor">
|
||||
<path strokeLinecap="round" strokeLinejoin="round" strokeWidth={2} d="M4 16l4.586-4.586a2 2 0 012.828 0L16 16m-2-2l1.586-1.586a2 2 0 012.828 0L20 14m-6-6h.01M6 20h12a2 2 0 002-2V6a2 2 0 00-2-2H6a2 2 0 00-2 2v12a2 2 0 002 2z" />
|
||||
</svg>
|
||||
{image.width}×{image.height}
|
||||
</span>
|
||||
)}
|
||||
<span className="flex items-center gap-1">
|
||||
<svg className="w-4 h-4" fill="none" viewBox="0 0 24 24" stroke="currentColor">
|
||||
<path strokeLinecap="round" strokeLinejoin="round" strokeWidth={2} d="M8 7V3m8 4V3m-9 8h10M5 21h14a2 2 0 002-2V7a2 2 0 00-2-2H5a2 2 0 00-2 2v12a2 2 0 002 2z" />
|
||||
</svg>
|
||||
{new Date(image.created_at).toLocaleString('zh-CN')}
|
||||
</span>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<div className="flex gap-2 flex-wrap">
|
||||
<Button
|
||||
variant="secondary"
|
||||
size="sm"
|
||||
onClick={() => onCopyMarkdown(image)}
|
||||
>
|
||||
<svg className="w-4 h-4 mr-1" fill="none" viewBox="0 0 24 24" stroke="currentColor">
|
||||
<path strokeLinecap="round" strokeLinejoin="round" strokeWidth={2} d="M9 12h6m-6 4h6m2 5H7a2 2 0 01-2-2V5a2 2 0 012-2h5.586a1 1 0 01.707.293l5.414 5.414a1 1 0 01.293.707V19a2 2 0 01-2 2z" />
|
||||
</svg>
|
||||
Markdown
|
||||
</Button>
|
||||
<Button
|
||||
variant="secondary"
|
||||
size="sm"
|
||||
onClick={() => onCopyUrl(image)}
|
||||
>
|
||||
<svg className="w-4 h-4 mr-1" fill="none" viewBox="0 0 24 24" stroke="currentColor">
|
||||
<path strokeLinecap="round" strokeLinejoin="round" strokeWidth={2} d="M13.828 10.172a4 4 0 00-5.656 0l-4 4a4 4 0 105.656 5.656l1.102-1.101m-.758-4.899a4 4 0 005.656 0l4-4a4 4 0 00-5.656-5.656l-1.1 1.1" />
|
||||
</svg>
|
||||
URL
|
||||
</Button>
|
||||
<Button
|
||||
variant="danger"
|
||||
size="sm"
|
||||
onClick={() => onDelete(image.id)}
|
||||
>
|
||||
<svg className="w-4 h-4 mr-1" fill="none" viewBox="0 0 24 24" stroke="currentColor">
|
||||
<path strokeLinecap="round" strokeLinejoin="round" strokeWidth={2} d="M19 7l-.867 12.142A2 2 0 0116.138 21H7.862a2 2 0 01-1.995-1.858L5 7m5 4v6m4-6v6m1-10V4a1 1 0 00-1-1h-4a1 1 0 00-1 1v3M4 7h16" />
|
||||
</svg>
|
||||
删除
|
||||
</Button>
|
||||
<Button
|
||||
variant="ghost"
|
||||
size="sm"
|
||||
onClick={onClose}
|
||||
>
|
||||
关闭
|
||||
</Button>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
{/* Markdown 预览 */}
|
||||
<div className="mt-4 p-3 bg-gray-50 border border-gray-200 rounded-lg">
|
||||
<p className="text-xs text-gray-500 mb-1 font-medium">Markdown 格式</p>
|
||||
<code className="text-sm font-mono text-gray-700 break-all">
|
||||
{``}
|
||||
</code>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
)
|
||||
}
|
||||
|
||||
export function Images() {
|
||||
const [images, setImages] = useState([])
|
||||
const [loading, setLoading] = useState(true)
|
||||
const [uploading, setUploading] = useState(false)
|
||||
const [selectedImage, setSelectedImage] = useState(null)
|
||||
const [page, setPage] = useState(0)
|
||||
const [hasMore, setHasMore] = useState(true)
|
||||
const limit = 20
|
||||
const fileInputRef = useRef(null)
|
||||
|
||||
// 清理统计
|
||||
const [cleanupStats, setCleanupStats] = useState(null)
|
||||
const [cleaning, setCleaning] = useState(false)
|
||||
|
||||
// 获取当前用户信息
|
||||
const user = JSON.parse(localStorage.getItem('user') || '{}')
|
||||
|
||||
// 获取图片列表
|
||||
const fetchImages = async (skip = 0, append = false) => {
|
||||
try {
|
||||
setLoading(true)
|
||||
const response = await api.get(`/images?skip=${skip}&limit=${limit}`)
|
||||
|
||||
const data = response.data
|
||||
|
||||
if (append) {
|
||||
setImages(prev => [...prev, ...data.items])
|
||||
} else {
|
||||
setImages(data.items)
|
||||
}
|
||||
|
||||
setHasMore(data.items.length === limit && (skip + data.items.length) < data.total)
|
||||
} catch (error) {
|
||||
alert('获取图片失败: ' + error.message)
|
||||
} finally {
|
||||
setLoading(false)
|
||||
}
|
||||
}
|
||||
|
||||
useEffect(() => {
|
||||
fetchImages()
|
||||
}, [])
|
||||
|
||||
// 获取清理统计
|
||||
const fetchCleanupStats = async () => {
|
||||
try {
|
||||
const response = await api.get('/images/usage-stats')
|
||||
const data = response.data
|
||||
setCleanupStats(data)
|
||||
} catch (error) {
|
||||
// 静默失败,不影响主功能
|
||||
}
|
||||
}
|
||||
|
||||
useEffect(() => {
|
||||
fetchCleanupStats()
|
||||
}, [images])
|
||||
|
||||
// 上传图片
|
||||
const handleUpload = async (e) => {
|
||||
const files = e.target.files
|
||||
if (!files || files.length === 0) return
|
||||
|
||||
setUploading(true)
|
||||
const formData = new FormData()
|
||||
for (let i = 0; i < files.length; i++) {
|
||||
formData.append('files', files[i])
|
||||
}
|
||||
|
||||
try {
|
||||
const response = await api.post('/images/upload-multiple', formData)
|
||||
|
||||
const data = response.data
|
||||
|
||||
if (data.uploaded && data.uploaded.length > 0) {
|
||||
setImages(prev => [...data.uploaded, ...prev])
|
||||
alert(`成功上传 ${data.uploaded.length} 张图片`)
|
||||
}
|
||||
|
||||
if (data.errors && data.errors.length > 0) {
|
||||
alert('部分上传失败: ' + data.errors.join(', '))
|
||||
}
|
||||
} catch (error) {
|
||||
alert('上传失败: ' + error.message)
|
||||
} finally {
|
||||
setUploading(false)
|
||||
if (fileInputRef.current) {
|
||||
fileInputRef.current.value = ''
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// 删除图片
|
||||
const handleDelete = async (imageId) => {
|
||||
if (!confirm('确定要删除这张图片吗?')) return
|
||||
|
||||
try {
|
||||
await api.delete(`/images/${imageId}`)
|
||||
|
||||
setImages(prev => prev.filter(img => img.id !== imageId))
|
||||
if (selectedImage?.id === imageId) {
|
||||
setSelectedImage(null)
|
||||
}
|
||||
} catch (error) {
|
||||
alert('删除失败: ' + error.message)
|
||||
}
|
||||
}
|
||||
|
||||
// 复制 Markdown 格式
|
||||
const copyMarkdown = (image) => {
|
||||
const markdown = ``
|
||||
navigator.clipboard.writeText(markdown).then(() => {
|
||||
alert('已复制 Markdown: ' + markdown)
|
||||
}).catch(() => {
|
||||
// 使用 requestAnimationFrame 确保不在 React 渲染周期内操作 DOM
|
||||
requestAnimationFrame(() => {
|
||||
const textarea = document.createElement('textarea')
|
||||
textarea.value = markdown
|
||||
textarea.style.cssText = 'position:fixed;left:-9999px;opacity:0;'
|
||||
document.body.appendChild(textarea)
|
||||
textarea.select()
|
||||
try {
|
||||
document.execCommand('copy')
|
||||
alert('已复制 Markdown: ' + markdown)
|
||||
} catch (e) {
|
||||
console.error('复制失败:', e)
|
||||
}
|
||||
// 延迟移除避免竞态
|
||||
setTimeout(() => {
|
||||
if (textarea.parentNode) {
|
||||
textarea.parentNode.removeChild(textarea)
|
||||
}
|
||||
}, 0)
|
||||
})
|
||||
})
|
||||
}
|
||||
|
||||
// 复制 URL
|
||||
const copyUrl = (image) => {
|
||||
const url = `${API_BASE_URL.replace('/api', '')}${image.file_path}`
|
||||
navigator.clipboard.writeText(url).then(() => {
|
||||
alert('已复制 URL: ' + url)
|
||||
})
|
||||
}
|
||||
|
||||
// 清理未使用图片
|
||||
const handleCleanup = async () => {
|
||||
if (!cleanupStats || cleanupStats.unused_images === 0) {
|
||||
alert('没有可清理的未使用图片')
|
||||
return
|
||||
}
|
||||
|
||||
const msg = `确定要清理 ${cleanupStats.unused_images} 张未使用的图片吗?\n将释放约 ${cleanupStats.unused_space_mb} MB 空间。\n\n⚠️ 注意:此操作不可恢复!`
|
||||
if (!confirm(msg)) return
|
||||
|
||||
setCleaning(true)
|
||||
try {
|
||||
const response = await api.post('/images/cleanup-unused')
|
||||
const data = response.data
|
||||
alert(`✅ ${data.message}\n释放空间: ${data.freed_space_mb} MB`)
|
||||
fetchImages()
|
||||
fetchCleanupStats()
|
||||
} catch (error) {
|
||||
alert('清理失败: ' + error.message)
|
||||
} finally {
|
||||
setCleaning(false)
|
||||
}
|
||||
}
|
||||
|
||||
// 加载更多
|
||||
const loadMore = () => {
|
||||
const nextPage = page + 1
|
||||
setPage(nextPage)
|
||||
fetchImages(nextPage * limit, true)
|
||||
}
|
||||
|
||||
// 格式化文件大小
|
||||
const formatFileSize = (bytes) => {
|
||||
if (bytes < 1024) return bytes + ' B'
|
||||
if (bytes < 1024 * 1024) return (bytes / 1024).toFixed(1) + ' KB'
|
||||
return (bytes / (1024 * 1024)).toFixed(1) + ' MB'
|
||||
}
|
||||
|
||||
// 获取图片完整 URL
|
||||
const getImageUrl = (path) => {
|
||||
return `${API_BASE_URL.replace('/api', '')}${path}`
|
||||
}
|
||||
|
||||
const handleLogout = async () => {
|
||||
localStorage.removeItem('token')
|
||||
await authApi.logout()
|
||||
localStorage.removeItem('user')
|
||||
window.location.href = '/login'
|
||||
}
|
||||
|
||||
return (
|
||||
<AdminLayout user={user} onLogout={handleLogout}>
|
||||
<div className="p-6 w-full">
|
||||
{/* 页面标题 */}
|
||||
<div className="mb-6">
|
||||
<h1 className="text-2xl font-semibold text-gray-900">图片管理</h1>
|
||||
<p className="text-gray-500 mt-1">上传、管理和清理博客图片</p>
|
||||
</div>
|
||||
|
||||
<div className="space-y-6">
|
||||
{/* 上传区域 */}
|
||||
<Card>
|
||||
<CardBody>
|
||||
<input
|
||||
type="file"
|
||||
ref={fileInputRef}
|
||||
onChange={handleUpload}
|
||||
accept="image/jpeg,image/png,image/gif,image/webp,image/svg+xml"
|
||||
multiple
|
||||
className="hidden"
|
||||
/>
|
||||
<div className="flex flex-col sm:flex-row items-start sm:items-center justify-between gap-4">
|
||||
<div className="flex items-start gap-4">
|
||||
<div className="w-12 h-12 bg-blue-100 rounded-xl flex items-center justify-center flex-shrink-0">
|
||||
<svg className="w-6 h-6 text-blue-600" fill="none" viewBox="0 0 24 24" stroke="currentColor">
|
||||
<path strokeLinecap="round" strokeLinejoin="round" strokeWidth={2} d="M7 16a4 4 0 01-.88-7.903A5 5 0 1115.9 6L16 6a5 5 0 011 9.9M15 13l-3-3m0 0l-3 3m3-3v12" />
|
||||
</svg>
|
||||
</div>
|
||||
<div>
|
||||
<h3 className="font-semibold text-gray-900">上传新图片</h3>
|
||||
<p className="text-sm text-gray-500 mt-0.5">
|
||||
支持 JPG、PNG、GIF、WebP、SVG,单张最大 10MB,自动生成缩略图
|
||||
</p>
|
||||
</div>
|
||||
</div>
|
||||
<Button
|
||||
onClick={() => fileInputRef.current?.click()}
|
||||
loading={uploading}
|
||||
>
|
||||
<svg className="w-4 h-4 mr-2" fill="none" viewBox="0 0 24 24" stroke="currentColor">
|
||||
<path strokeLinecap="round" strokeLinejoin="round" strokeWidth={2} d="M12 4v16m8-8H4" />
|
||||
</svg>
|
||||
{uploading ? '上传中...' : '选择图片'}
|
||||
</Button>
|
||||
</div>
|
||||
</CardBody>
|
||||
</Card>
|
||||
|
||||
{/* 清理统计警告 */}
|
||||
{cleanupStats && cleanupStats.unused_images > 0 && (
|
||||
<Card className="bg-yellow-50 border-yellow-200">
|
||||
<CardBody>
|
||||
<div className="flex flex-col sm:flex-row items-start sm:items-center justify-between gap-4">
|
||||
<div className="flex items-start gap-4">
|
||||
<div className="w-12 h-12 bg-yellow-100 rounded-xl flex items-center justify-center flex-shrink-0">
|
||||
<svg className="w-6 h-6 text-yellow-600" fill="none" viewBox="0 0 24 24" stroke="currentColor">
|
||||
<path strokeLinecap="round" strokeLinejoin="round" strokeWidth={2} d="M19 7l-.867 12.142A2 2 0 0116.138 21H7.862a2 2 0 01-1.995-1.858L5 7m5 4v6m4-6v6m1-10V4a1 1 0 00-1-1h-4a1 1 0 00-1 1v3M4 7h16" />
|
||||
</svg>
|
||||
</div>
|
||||
<div>
|
||||
<h3 className="font-semibold text-yellow-800">发现未使用图片</h3>
|
||||
<p className="text-sm text-yellow-700 mt-0.5">
|
||||
共有 {cleanupStats.unused_images} 张图片未被引用,占用 {cleanupStats.unused_space_mb} MB 空间
|
||||
</p>
|
||||
</div>
|
||||
</div>
|
||||
<Button
|
||||
onClick={handleCleanup}
|
||||
loading={cleaning}
|
||||
className="bg-yellow-500 hover:bg-yellow-600 text-white"
|
||||
>
|
||||
<svg className="w-4 h-4 mr-2" fill="none" viewBox="0 0 24 24" stroke="currentColor">
|
||||
<path strokeLinecap="round" strokeLinejoin="round" strokeWidth={2} d="M19 7l-.867 12.142A2 2 0 0116.138 21H7.862a2 2 0 01-1.995-1.858L5 7m5 4v6m4-6v6m1-10V4a1 1 0 00-1-1h-4a1 1 0 00-1 1v3M4 7h16" />
|
||||
</svg>
|
||||
一键清理
|
||||
</Button>
|
||||
</div>
|
||||
</CardBody>
|
||||
</Card>
|
||||
)}
|
||||
|
||||
{/* 图片网格 */}
|
||||
<Card>
|
||||
<CardHeader>
|
||||
<div className="flex items-center justify-between">
|
||||
<div>
|
||||
<CardTitle>图片库</CardTitle>
|
||||
<CardDescription>
|
||||
共 {images.length} 张图片
|
||||
{cleanupStats && (
|
||||
<span className="ml-2 text-gray-400">
|
||||
· 已使用 {cleanupStats.used_images} 张 · 未使用 {cleanupStats.unused_images} 张
|
||||
</span>
|
||||
)}
|
||||
</CardDescription>
|
||||
</div>
|
||||
</div>
|
||||
</CardHeader>
|
||||
<CardBody>
|
||||
{loading && images.length === 0 ? (
|
||||
<div className="flex items-center justify-center py-16">
|
||||
<svg className="animate-spin h-8 w-8 text-gray-300" viewBox="0 0 24 24" fill="none">
|
||||
<circle className="opacity-25" cx="12" cy="12" r="10" stroke="currentColor" strokeWidth="4" />
|
||||
<path className="opacity-75" fill="currentColor" d="M4 12a8 8 0 018-8V0C5.373 0 0 5.373 0 12h4z" />
|
||||
</svg>
|
||||
</div>
|
||||
) : images.length === 0 ? (
|
||||
<div className="text-center py-16">
|
||||
<div className="w-20 h-20 bg-gray-100 rounded-full flex items-center justify-center mx-auto mb-4">
|
||||
<svg className="w-10 h-10 text-gray-400" fill="none" viewBox="0 0 24 24" stroke="currentColor">
|
||||
<path strokeLinecap="round" strokeLinejoin="round" strokeWidth={2} d="M4 16l4.586-4.586a2 2 0 012.828 0L16 16m-2-2l1.586-1.586a2 2 0 012.828 0L20 14m-6-6h.01M6 20h12a2 2 0 002-2V6a2 2 0 00-2-2H6a2 2 0 00-2 2v12a2 2 0 002 2z" />
|
||||
</svg>
|
||||
</div>
|
||||
<p className="text-gray-500 mb-2">暂无图片</p>
|
||||
<p className="text-sm text-gray-400">点击上方按钮上传图片</p>
|
||||
</div>
|
||||
) : (
|
||||
<>
|
||||
<div className="grid grid-cols-2 sm:grid-cols-3 md:grid-cols-4 lg:grid-cols-5 xl:grid-cols-6 gap-4">
|
||||
{images.map((image) => (
|
||||
<ImageGridItem
|
||||
key={image.id}
|
||||
image={image}
|
||||
onClick={setSelectedImage}
|
||||
getImageUrl={getImageUrl}
|
||||
formatFileSize={formatFileSize}
|
||||
/>
|
||||
))}
|
||||
</div>
|
||||
|
||||
{/* 加载更多 */}
|
||||
{hasMore && (
|
||||
<div className="text-center mt-8">
|
||||
<Button
|
||||
variant="secondary"
|
||||
onClick={loadMore}
|
||||
loading={loading}
|
||||
>
|
||||
{loading ? '加载中...' : '加载更多'}
|
||||
</Button>
|
||||
</div>
|
||||
)}
|
||||
</>
|
||||
)}
|
||||
</CardBody>
|
||||
</Card>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
{/* 图片预览弹窗 */}
|
||||
<ImagePreviewModal
|
||||
image={selectedImage}
|
||||
onClose={() => setSelectedImage(null)}
|
||||
onCopyMarkdown={copyMarkdown}
|
||||
onCopyUrl={copyUrl}
|
||||
onDelete={handleDelete}
|
||||
getImageUrl={getImageUrl}
|
||||
formatFileSize={formatFileSize}
|
||||
/>
|
||||
</AdminLayout>
|
||||
)
|
||||
}
|
||||
|
||||
export default Images
|
||||
@@ -0,0 +1,525 @@
|
||||
import { useState, useEffect, useRef, useCallback } from 'react'
|
||||
import { AdminLayout } from '../../components-preline/Sidebar'
|
||||
|
||||
const WS_URL = 'ws://129.211.173.87:8765/'
|
||||
const WS_TOKEN='nSQApLIL7Z6-jufdxVk8hz8yRG_YLgLoH6_hdiMMWGU'
|
||||
const MAX_IMAGES = 4
|
||||
const MAX_IMAGE_SIZE = 8 * 1024 * 1024 // 8 MB
|
||||
const MAX_RETRIES = 3
|
||||
const RETRY_DELAYS = [1000, 2000, 4000]
|
||||
|
||||
// ═══ 模块级持久状态(切换页面不丢失) ═══
|
||||
let persistentWs = null
|
||||
let persistentMessages = []
|
||||
let persistentConnected = false
|
||||
let persistentConnecting = false
|
||||
let persistentError = null
|
||||
let persistentChatId = null
|
||||
let persistentAutoRetry = true
|
||||
let retryCount = 0
|
||||
let retryTimer = null
|
||||
let currentReply = ''
|
||||
let isStreaming = false
|
||||
let streamEnded = false
|
||||
let changeListeners = new Set()
|
||||
|
||||
function notifyChanges() {
|
||||
// 浅拷贝避免引用问题
|
||||
changeListeners.forEach(fn => fn())
|
||||
}
|
||||
|
||||
function getState() {
|
||||
return {
|
||||
messages: persistentMessages,
|
||||
connected: persistentConnected,
|
||||
connecting: persistentConnecting,
|
||||
error: persistentError,
|
||||
chatId: persistentChatId,
|
||||
autoRetry: persistentAutoRetry,
|
||||
}
|
||||
}
|
||||
|
||||
// ═══ 图标组件 ═══
|
||||
function IconBot({ className }) {
|
||||
return (
|
||||
<svg className={className} viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2" strokeLinecap="round" strokeLinejoin="round">
|
||||
<rect x="3" y="11" width="18" height="10" rx="2" />
|
||||
<circle cx="12" cy="5" r="2" />
|
||||
<path d="M12 7v4" />
|
||||
<line x1="8" y1="16" x2="8" y2="16.01" />
|
||||
<line x1="16" y1="16" x2="16" y2="16.01" />
|
||||
</svg>
|
||||
)
|
||||
}
|
||||
|
||||
function IconUser({ className }) {
|
||||
return (
|
||||
<svg className={className} viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2" strokeLinecap="round" strokeLinejoin="round">
|
||||
<path d="M20 21v-2a4 4 0 0 0-4-4H8a4 4 0 0 0-4 4v2" />
|
||||
<circle cx="12" cy="7" r="4" />
|
||||
</svg>
|
||||
)
|
||||
}
|
||||
|
||||
function IconSend({ className }) {
|
||||
return (
|
||||
<svg className={className} viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2" strokeLinecap="round" strokeLinejoin="round">
|
||||
<line x1="22" y1="2" x2="11" y2="13" />
|
||||
<polygon points="22 2 15 22 11 13 2 9 22 2" />
|
||||
</svg>
|
||||
)
|
||||
}
|
||||
|
||||
function IconWifi({ className }) {
|
||||
return (
|
||||
<svg className={className} viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2" strokeLinecap="round" strokeLinejoin="round">
|
||||
<path d="M5 12.55a11 11 0 0 1 14.08 0" />
|
||||
<path d="M1.42 9a16 16 0 0 1 21.16 0" />
|
||||
<path d="M8.53 16.11a6 6 0 0 1 6.95 0" />
|
||||
<line x1="12" y1="20" x2="12.01" y2="20" />
|
||||
</svg>
|
||||
)
|
||||
}
|
||||
|
||||
function IconWifiOff({ className }) {
|
||||
return (
|
||||
<svg className={className} viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2" strokeLinecap="round" strokeLinejoin="round">
|
||||
<line x1="1" y1="1" x2="23" y2="23" />
|
||||
<path d="M16.72 11.06A10.94 10.94 0 0 1 19 12.55" />
|
||||
<path d="M5 12.55a10.94 10.94 0 0 1 5.17-2.39" />
|
||||
<path d="M10.71 5.05A16 16 0 0 1 22.58 9" />
|
||||
<path d="M1.42 9a15.91 15.91 0 0 1 4.7-2.88" />
|
||||
<path d="M8.53 16.11a6 6 0 0 1 6.95 0" />
|
||||
<line x1="12" y1="20" x2="12.01" y2="20" />
|
||||
</svg>
|
||||
)
|
||||
}
|
||||
|
||||
function IconAlert({ className }) {
|
||||
return (
|
||||
<svg className={className} viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2" strokeLinecap="round" strokeLinejoin="round">
|
||||
<circle cx="12" cy="12" r="10" />
|
||||
<line x1="12" y1="8" x2="12" y2="12" />
|
||||
<line x1="12" y1="16" x2="12.01" y2="16" />
|
||||
</svg>
|
||||
)
|
||||
}
|
||||
|
||||
function IconLoader({ className }) {
|
||||
return (
|
||||
<svg className={`${className} animate-spin`} viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2" strokeLinecap="round" strokeLinejoin="round">
|
||||
<path d="M21 12a9 9 0 1 1-6.219-8.56" />
|
||||
</svg>
|
||||
)
|
||||
}
|
||||
|
||||
// ═══ 模块级的连接/断开/重试逻辑 ═══
|
||||
function doPersistentConnect(isRetry = false) {
|
||||
// 关闭旧连接(如果在 CONNECTING 状态也关掉,防止 "closed before established" 警告)
|
||||
if (persistentWs) {
|
||||
// 移除旧的事件处理,防止旧 onclose 触发后覆盖新连接状态
|
||||
persistentWs.onopen = null
|
||||
persistentWs.onmessage = null
|
||||
persistentWs.onerror = null
|
||||
persistentWs.onclose = null
|
||||
if (persistentWs.readyState === WebSocket.CONNECTING || persistentWs.readyState === WebSocket.OPEN) {
|
||||
persistentWs.close()
|
||||
}
|
||||
persistentWs = null
|
||||
}
|
||||
persistentConnecting = true
|
||||
persistentError = null
|
||||
if (!isRetry) {
|
||||
retryCount = 0
|
||||
persistentAutoRetry = true
|
||||
}
|
||||
notifyChanges()
|
||||
|
||||
const url = `${WS_URL}?client_id=blog-admin&token=${encodeURIComponent(WS_TOKEN)}`
|
||||
const ws = new WebSocket(url)
|
||||
persistentWs = ws
|
||||
const thisWs = ws // 闭包捕获,防止后续 handler 引用到被替换的 persistentWs
|
||||
|
||||
thisWs.onopen = () => {
|
||||
if (persistentWs !== thisWs) return // 不是当前连接,忽略
|
||||
persistentConnecting = false
|
||||
persistentConnected = true
|
||||
persistentError = null
|
||||
streamEnded = false
|
||||
retryCount = 0
|
||||
if (retryTimer) { clearTimeout(retryTimer); retryTimer = null }
|
||||
notifyChanges()
|
||||
}
|
||||
|
||||
thisWs.onmessage = (event) => {
|
||||
if (persistentWs !== thisWs) return
|
||||
try {
|
||||
const data = JSON.parse(event.data)
|
||||
if (data.event === 'ready') {
|
||||
persistentChatId = data.chat_id
|
||||
notifyChanges()
|
||||
return
|
||||
}
|
||||
if (data.event === 'delta') {
|
||||
if (streamEnded) return
|
||||
isStreaming = true
|
||||
currentReply += data.text || ''
|
||||
persistentMessages = persistentMessages.map((m, i, arr) => {
|
||||
if (i === arr.length - 1 && m.role === 'bot' && !m.done)
|
||||
return { ...m, content: currentReply }
|
||||
return m
|
||||
})
|
||||
if (!persistentMessages.length || persistentMessages[persistentMessages.length - 1].role !== 'bot' || persistentMessages[persistentMessages.length - 1].done) {
|
||||
persistentMessages = [...persistentMessages, { role: 'bot', content: currentReply, done: false }]
|
||||
}
|
||||
notifyChanges()
|
||||
}
|
||||
if (data.event === 'message') {
|
||||
const botText = data.text || ''
|
||||
persistentMessages = persistentMessages.map((m, i, arr) => {
|
||||
if (i === arr.length - 1 && m.role === 'bot' && !m.done)
|
||||
return { ...m, content: m.content + botText, done: true }
|
||||
return m
|
||||
})
|
||||
notifyChanges()
|
||||
}
|
||||
if (data.event === 'stream_end') {
|
||||
isStreaming = false
|
||||
streamEnded = true
|
||||
currentReply = ''
|
||||
persistentMessages = persistentMessages.map((m, i, arr) => {
|
||||
if (i === arr.length - 1 && m.role === 'bot')
|
||||
return { ...m, done: true }
|
||||
return m
|
||||
})
|
||||
notifyChanges()
|
||||
}
|
||||
if (data.event === 'error') {
|
||||
persistentError = data.detail || 'WebSocket error'
|
||||
notifyChanges()
|
||||
}
|
||||
} catch (e) {}
|
||||
}
|
||||
|
||||
thisWs.onerror = () => {
|
||||
if (persistentWs !== thisWs) return
|
||||
persistentConnecting = false
|
||||
persistentConnected = false
|
||||
notifyChanges()
|
||||
}
|
||||
|
||||
thisWs.onclose = () => {
|
||||
if (persistentWs !== thisWs) return
|
||||
persistentConnecting = false
|
||||
persistentConnected = false
|
||||
persistentChatId = null
|
||||
if (persistentAutoRetry) {
|
||||
schedulePersistentRetry()
|
||||
}
|
||||
notifyChanges()
|
||||
}
|
||||
}
|
||||
|
||||
function schedulePersistentRetry() {
|
||||
if (!persistentAutoRetry) return
|
||||
if (retryCount >= MAX_RETRIES) {
|
||||
persistentAutoRetry = false
|
||||
persistentError = `自动连接失败(已重试 ${MAX_RETRIES} 次),请检查服务状态后手动连接`
|
||||
persistentConnecting = false
|
||||
notifyChanges()
|
||||
return
|
||||
}
|
||||
const delay = RETRY_DELAYS[retryCount] || 4000
|
||||
const attempt = retryCount + 1
|
||||
persistentError = `连接失败,${delay / 1000} 秒后自动重试...(${attempt}/${MAX_RETRIES})`
|
||||
retryCount = attempt
|
||||
notifyChanges()
|
||||
if (retryTimer) clearTimeout(retryTimer)
|
||||
retryTimer = setTimeout(() => {
|
||||
doPersistentConnect(true)
|
||||
}, delay)
|
||||
}
|
||||
|
||||
function skipPersistentRetry() {
|
||||
persistentAutoRetry = false
|
||||
if (retryTimer) { clearTimeout(retryTimer); retryTimer = null }
|
||||
persistentConnecting = false
|
||||
persistentError = null
|
||||
if (persistentWs) {
|
||||
persistentWs.onopen = null
|
||||
persistentWs.onmessage = null
|
||||
persistentWs.onerror = null
|
||||
persistentWs.onclose = null
|
||||
persistentWs.close()
|
||||
persistentWs = null
|
||||
}
|
||||
notifyChanges()
|
||||
}
|
||||
|
||||
function disconnectPersistent() {
|
||||
persistentAutoRetry = false
|
||||
if (retryTimer) { clearTimeout(retryTimer); retryTimer = null }
|
||||
if (persistentWs) {
|
||||
persistentWs.onopen = null
|
||||
persistentWs.onmessage = null
|
||||
persistentWs.onerror = null
|
||||
persistentWs.onclose = null
|
||||
persistentWs.close()
|
||||
persistentWs = null
|
||||
}
|
||||
persistentConnected = false
|
||||
persistentConnecting = false
|
||||
persistentChatId = null
|
||||
notifyChanges()
|
||||
}
|
||||
|
||||
export function NanobotChat() {
|
||||
// 组件本地状态(只存放输入框和图片这类 UI 状态)
|
||||
const [input, setInput] = useState('')
|
||||
const [selectedImages, setSelectedImages] = useState([])
|
||||
const fileInputRef = useRef(null)
|
||||
const pasteAreaRef = useRef(null)
|
||||
const messagesEndRef = useRef(null)
|
||||
|
||||
// 订阅模块级持久状态
|
||||
const [state, setState] = useState(getState)
|
||||
useEffect(() => {
|
||||
const listener = () => setState(getState())
|
||||
changeListeners.add(listener)
|
||||
// 首次挂载时如果还没连接,自动连接
|
||||
if (!persistentWs && !persistentConnecting) {
|
||||
doPersistentConnect(false)
|
||||
}
|
||||
return () => {
|
||||
changeListeners.delete(listener)
|
||||
// 不在这里断开!保持 WebSocket 存活
|
||||
}
|
||||
}, [])
|
||||
|
||||
const { messages, connected, connecting, error, chatId, autoRetry } = state
|
||||
|
||||
// 滚动到底部
|
||||
useEffect(() => {
|
||||
messagesEndRef.current?.scrollIntoView({ behavior: 'smooth' })
|
||||
}, [messages])
|
||||
|
||||
// 图片处理
|
||||
const readFileAsDataURL = (file) => {
|
||||
return new Promise((resolve, reject) => {
|
||||
const reader = new FileReader()
|
||||
reader.onload = () => resolve(reader.result)
|
||||
reader.onerror = reject
|
||||
reader.readAsDataURL(file)
|
||||
})
|
||||
}
|
||||
|
||||
const handleImageSelect = async (files) => {
|
||||
const imageFiles = Array.from(files).filter(f => f.type.startsWith('image/'))
|
||||
if (imageFiles.length === 0) return
|
||||
const availableSlots = MAX_IMAGES - selectedImages.length
|
||||
if (availableSlots <= 0) {
|
||||
persistentError = `最多只能上传 ${MAX_IMAGES} 张图片`; notifyChanges(); return
|
||||
}
|
||||
const toAdd = imageFiles.slice(0, availableSlots)
|
||||
if (toAdd.some(f => f.size > MAX_IMAGE_SIZE)) {
|
||||
persistentError = '单张图片不能超过 8 MB'; notifyChanges(); return
|
||||
}
|
||||
setSelectedImages(prev => [...prev, ...toAdd])
|
||||
}
|
||||
|
||||
const removeImage = (index) => setSelectedImages(prev => prev.filter((_, i) => i !== index))
|
||||
|
||||
const handlePaste = (e) => {
|
||||
if (!e.clipboardData) return
|
||||
const items = e.clipboardData.items || e.clipboardData.files
|
||||
const files = []
|
||||
if (items) {
|
||||
for (const item of items) {
|
||||
if (item.kind === 'file' && item.type.startsWith('image/')) {
|
||||
const file = item.getAsFile()
|
||||
if (file) files.push(file)
|
||||
}
|
||||
}
|
||||
}
|
||||
if (files.length > 0) { e.preventDefault(); handleImageSelect(files) }
|
||||
}
|
||||
|
||||
const handleFileInputChange = (e) => { handleImageSelect(e.target.files); e.target.value = '' }
|
||||
|
||||
const handleSend = async () => {
|
||||
const text = input.trim()
|
||||
if ((!text && selectedImages.length === 0) || !connected || !chatId || !persistentWs) return
|
||||
|
||||
let media = []
|
||||
if (selectedImages.length > 0) {
|
||||
try {
|
||||
media = await Promise.all(selectedImages.map(readFileAsDataURL))
|
||||
} catch {
|
||||
persistentError = '图片读取失败,请重试'; notifyChanges(); return
|
||||
}
|
||||
}
|
||||
|
||||
const displayContent = text || (selectedImages.length > 1 ? `[${selectedImages.length} 张图片]` : '[图片]')
|
||||
persistentMessages = [...persistentMessages, { role: 'user', content: displayContent, images: media, done: true }]
|
||||
setInput('')
|
||||
setSelectedImages([])
|
||||
notifyChanges()
|
||||
|
||||
const payload = { type: 'message', chat_id: chatId, content: text }
|
||||
if (media.length > 0) payload.media = media.map(url => ({ data_url: url }))
|
||||
persistentWs.send(JSON.stringify(payload))
|
||||
}
|
||||
|
||||
const handleKeyDown = async (e) => {
|
||||
if (e.key === 'Enter' && !e.shiftKey) { e.preventDefault(); await handleSend() }
|
||||
}
|
||||
|
||||
return (
|
||||
<AdminLayout>
|
||||
<div className="h-[calc(100vh-1px)] flex flex-col bg-preline-card rounded-xl border border-preline-border shadow-sm m-6 overflow-hidden">
|
||||
{/* Header */}
|
||||
<div className="flex items-center justify-between px-6 py-4 border-b border-preline-border bg-preline-card">
|
||||
<div className="flex items-center gap-3">
|
||||
<div className="w-9 h-9 rounded-lg bg-preline-primary-light flex items-center justify-center">
|
||||
<IconBot className="w-5 h-5 text-preline-primary" />
|
||||
</div>
|
||||
<div>
|
||||
<h1 className="text-base font-semibold text-preline-text">Nanobot 助手</h1>
|
||||
<p className="text-xs text-preline-text-secondary">基于 WebSocket 的实时对话</p>
|
||||
</div>
|
||||
</div>
|
||||
<div className="flex items-center gap-3">
|
||||
{connected ? (
|
||||
<span className="flex items-center gap-1.5 text-xs font-medium text-preline-success-text bg-preline-success-bg px-2.5 py-1 rounded-full border border-preline-success-border">
|
||||
<IconWifi className="w-3.5 h-3.5" /> 已连接
|
||||
</span>
|
||||
) : connecting ? (
|
||||
<span className="flex items-center gap-1.5 text-xs font-medium text-preline-warning-text bg-preline-warning-bg px-2.5 py-1 rounded-full border border-preline-warning-border">
|
||||
<IconLoader className="w-3.5 h-3.5" /> 自动连接中...
|
||||
</span>
|
||||
) : autoRetry ? (
|
||||
<span className="flex items-center gap-1.5 text-xs font-medium text-preline-warning-text bg-preline-warning-bg px-2.5 py-1 rounded-full border border-preline-warning-border">
|
||||
<IconLoader className="w-3.5 h-3.5" /> 重连中...
|
||||
</span>
|
||||
) : (
|
||||
<span className="flex items-center gap-1.5 text-xs font-medium text-preline-danger bg-preline-danger-bg px-2.5 py-1 rounded-full border border-preline-danger-border">
|
||||
<IconWifiOff className="w-3.5 h-3.5" /> 连接失败
|
||||
</span>
|
||||
)}
|
||||
{!connected ? (
|
||||
<button
|
||||
onClick={autoRetry ? skipPersistentRetry : () => doPersistentConnect(false)}
|
||||
disabled={connecting}
|
||||
className="text-xs font-medium bg-preline-primary text-white px-3.5 py-1.5 rounded-lg hover:bg-preline-primary-hover disabled:opacity-50 disabled:cursor-not-allowed transition-colors"
|
||||
>
|
||||
{connecting ? '连接中...' : (autoRetry ? '跳过' : '手动连接')}
|
||||
</button>
|
||||
) : (
|
||||
<button
|
||||
onClick={disconnectPersistent}
|
||||
className="text-xs font-medium bg-preline-card text-preline-gray-700 px-3.5 py-1.5 rounded-lg border border-preline-gray-300 hover:bg-preline-bg transition-colors"
|
||||
>
|
||||
断开
|
||||
</button>
|
||||
)}
|
||||
</div>
|
||||
</div>
|
||||
|
||||
{/* Messages */}
|
||||
<div className="flex-1 overflow-y-auto px-6 py-5 space-y-5 bg-preline-bg">
|
||||
{messages.length === 0 && (
|
||||
<div className="flex flex-col items-center justify-center h-full text-preline-gray-400">
|
||||
<div className="w-14 h-14 rounded-2xl bg-preline-gray-100 flex items-center justify-center mb-4">
|
||||
<IconBot className="w-7 h-7 text-preline-gray-400" />
|
||||
</div>
|
||||
{connected ? (
|
||||
<p className="text-sm font-medium text-preline-text-secondary">已连接,发送消息开始对话</p>
|
||||
) : connecting ? (
|
||||
<p className="text-sm font-medium text-preline-text-secondary">正在自动连接 WebSocket...</p>
|
||||
) : autoRetry ? (
|
||||
<p className="text-sm font-medium text-preline-text-secondary">正在重连 WebSocket...</p>
|
||||
) : (
|
||||
<p className="text-sm font-medium text-preline-text-secondary">连接失败,请点击右上角「手动连接」</p>
|
||||
)}
|
||||
</div>
|
||||
)}
|
||||
{messages.map((msg, i) => (
|
||||
<div key={i} className={`flex gap-3 ${msg.role === 'user' ? 'flex-row-reverse' : ''}`}>
|
||||
<div className={`w-8 h-8 rounded-full flex items-center justify-center flex-shrink-0 ring-2 ring-white shadow-sm ${
|
||||
msg.role === 'user' ? 'bg-preline-primary text-white' : 'bg-preline-success text-white'
|
||||
}`}>
|
||||
{msg.role === 'user' ? <IconUser className="w-4 h-4" /> : <IconBot className="w-4 h-4" />}
|
||||
</div>
|
||||
<div className={`max-w-[70%] px-4 py-2.5 rounded-2xl text-sm leading-relaxed whitespace-pre-wrap break-words shadow-sm ${
|
||||
msg.role === 'user'
|
||||
? 'bg-preline-primary text-white rounded-br-md'
|
||||
: 'bg-preline-card text-preline-text border border-preline-border rounded-bl-md'
|
||||
}`}>
|
||||
{msg.content}
|
||||
{msg.images && msg.images.length > 0 && (
|
||||
<div className="flex flex-wrap gap-2 mt-2">
|
||||
{msg.images.map((url, idx) => (
|
||||
<img key={idx} src={url} alt={`img-${idx}`} className="max-w-[120px] max-h-[120px] object-cover rounded-lg border border-preline-card/30" />
|
||||
))}
|
||||
</div>
|
||||
)}
|
||||
<span className={`inline-block w-1.5 h-3.5 ml-1 rounded-sm ${msg.role === 'bot' && !msg.done ? 'bg-preline-success animate-pulse' : 'invisible'}`} />
|
||||
</div>
|
||||
</div>
|
||||
))}
|
||||
<div ref={messagesEndRef} />
|
||||
</div>
|
||||
|
||||
{/* Error */}
|
||||
{error && (
|
||||
<div className="px-6 py-3 bg-preline-danger-bg border-t border-preline-danger-border flex items-center gap-2 text-xs text-preline-danger font-medium">
|
||||
<IconAlert className="w-4 h-4 flex-shrink-0" />
|
||||
{error}
|
||||
</div>
|
||||
)}
|
||||
|
||||
{/* Input */}
|
||||
<div className="px-6 py-4 bg-preline-card border-t border-preline-border">
|
||||
{selectedImages.length > 0 && (
|
||||
<div className="flex gap-2 mb-3 overflow-x-auto pb-1">
|
||||
{selectedImages.map((file, idx) => (
|
||||
<div key={idx} className="relative group flex-shrink-0">
|
||||
<img src={URL.createObjectURL(file)} alt={`preview-${idx}`}
|
||||
className="w-16 h-16 object-cover rounded-lg border border-preline-border" />
|
||||
<button onClick={() => removeImage(idx)}
|
||||
className="absolute -top-1.5 -right-1.5 w-5 h-5 bg-preline-gray-800 text-white rounded-full text-xs flex items-center justify-center opacity-0 group-hover:opacity-100 transition-opacity shadow-sm"
|
||||
title="移除">×</button>
|
||||
</div>
|
||||
))}
|
||||
</div>
|
||||
)}
|
||||
<div className="flex gap-3">
|
||||
<div className="flex-1 relative">
|
||||
<textarea ref={pasteAreaRef} value={input}
|
||||
onChange={(e) => setInput(e.target.value)} onKeyDown={handleKeyDown} onPaste={handlePaste}
|
||||
disabled={!connected}
|
||||
placeholder={connected ? '输入消息,Ctrl+V 粘贴图片,按 Enter 发送...' : '请先连接 WebSocket'}
|
||||
rows={2}
|
||||
className="w-full resize-none rounded-xl border border-preline-gray-300 px-4 py-3 pr-10 text-sm text-preline-text placeholder-preline-gray-400 focus:outline-none focus:ring-2 focus:ring-preline-primary focus:border-transparent bg-preline-card disabled:bg-preline-bg disabled:text-preline-gray-400 transition-all" />
|
||||
<button onClick={() => fileInputRef.current?.click()}
|
||||
disabled={!connected || selectedImages.length >= MAX_IMAGES}
|
||||
className="absolute right-3 bottom-3 text-preline-gray-400 hover:text-preline-primary disabled:text-preline-gray-300 transition-colors" title="上传图片">
|
||||
<svg className="w-5 h-5" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2" strokeLinecap="round" strokeLinejoin="round">
|
||||
<rect x="3" y="3" width="18" height="18" rx="2" ry="2" /><circle cx="8.5" cy="8.5" r="1.5" /><polyline points="21 15 16 10 5 21" />
|
||||
</svg>
|
||||
</button>
|
||||
<input ref={fileInputRef} type="file" accept="image/png,image/jpeg,image/webp,image/gif" multiple
|
||||
className="hidden" onChange={handleFileInputChange} />
|
||||
</div>
|
||||
<button onClick={handleSend}
|
||||
disabled={!connected || (!input.trim() && selectedImages.length === 0)}
|
||||
className="self-end w-10 h-10 flex items-center justify-center rounded-xl bg-preline-primary text-white hover:bg-preline-primary-hover disabled:opacity-40 disabled:cursor-not-allowed transition-colors shadow-sm">
|
||||
<IconSend className="w-4 h-4" />
|
||||
</button>
|
||||
</div>
|
||||
<p className="text-[11px] text-preline-gray-400 mt-2">支持粘贴截图或点击 📎 上传,最多 {MAX_IMAGES} 张,每张 ≤ 8 MB</p>
|
||||
</div>
|
||||
</div>
|
||||
</AdminLayout>
|
||||
)
|
||||
}
|
||||
@@ -0,0 +1,776 @@
|
||||
// 博客设置页面 - Preline UI 风格
|
||||
import { useState, useEffect } from 'react'
|
||||
import { AdminLayout } from '../../components-preline/Sidebar'
|
||||
import { authApi } from '../../api/auth'
|
||||
import { Card, CardHeader, CardTitle, CardDescription, CardBody, CardFooter } from '../../components-preline/Card'
|
||||
import { Button } from '../../components-preline/Button'
|
||||
import { Input, Textarea, Select, Label, FormError, FormHelp } from '../../components-preline/Input'
|
||||
import { API_BASE_URL } from '../../api/config'
|
||||
import { generateShades, generateHarmony, randomPalette, hexToHsl, hslToHex, SHADE_STOPS } from '../../utils/colorPalette'
|
||||
|
||||
export function Settings() {
|
||||
const [activeTab, setActiveTab] = useState('general')
|
||||
const [loading, setLoading] = useState(true)
|
||||
const [saving, setSaving] = useState(false)
|
||||
const [message, setMessage] = useState('')
|
||||
|
||||
// 获取当前用户信息
|
||||
const user = JSON.parse(localStorage.getItem('user') || '{}')
|
||||
|
||||
// ============ 网站配色 ============
|
||||
const [baseColor, setBaseColor] = useState('#2563EB')
|
||||
const [shades, setShades] = useState({})
|
||||
const [harmony, setHarmony] = useState({})
|
||||
const [paletteMode, setPaletteMode] = useState('shades') // 'shades' | 'harmony'
|
||||
|
||||
// 博客设置
|
||||
const [settings, setSettings] = useState({
|
||||
blog_name: '侘寂屋',
|
||||
blog_description: '',
|
||||
welcome_message: '欢迎来到侘寂屋 👋 分享技术、生活与思考',
|
||||
banner_type: 'text',
|
||||
banner_images: '[]',
|
||||
theme: 'neobrutalism',
|
||||
layout: 'card',
|
||||
theme_colors: '{"primary":"#2563EB","secondary":"#06b6d4","bg":"#F8FAFC","text":"#0F172A","sidebar":"#1E293B"}'
|
||||
})
|
||||
|
||||
// 配色对象(由 theme_colors JSON 解析而来)
|
||||
const [colors, setColors] = useState({
|
||||
primary: '#2563EB',
|
||||
secondary: '#06b6d4',
|
||||
bg: '#F8FAFC',
|
||||
text: '#0F172A',
|
||||
sidebar: '#1E293B',
|
||||
})
|
||||
|
||||
// 密码修改
|
||||
const [passwordData, setPasswordData] = useState({
|
||||
old_password: '',
|
||||
new_password: '',
|
||||
confirm_password: ''
|
||||
})
|
||||
const [passwordError, setPasswordError] = useState('')
|
||||
|
||||
const token = localStorage.getItem('token')
|
||||
|
||||
// 注入完整主题变量到 CSS
|
||||
const injectThemeVars = (themeColors, shadeMap, harmonyMap) => {
|
||||
const root = document.documentElement
|
||||
|
||||
// 语义变量
|
||||
const semanticMap = {
|
||||
primary: '--color-primary',
|
||||
secondary: '--color-secondary',
|
||||
bg: '--color-bg',
|
||||
text: '--color-text',
|
||||
sidebar: '--color-sidebar',
|
||||
'sidebar-active': '--color-sidebar-active',
|
||||
border: '--color-border',
|
||||
card: '--color-card',
|
||||
}
|
||||
|
||||
// 色阶优先映射关键语义变量
|
||||
if (shadeMap) {
|
||||
if (shadeMap[500]) root.style.setProperty('--color-primary', shadeMap[500])
|
||||
if (shadeMap[600]) root.style.setProperty('--color-primary-hover', shadeMap[600])
|
||||
if (shadeMap[100]) root.style.setProperty('--color-primary-light', shadeMap[100])
|
||||
}
|
||||
|
||||
Object.entries(semanticMap).forEach(([key, cssVar]) => {
|
||||
if (key === 'primary' && shadeMap?.[500]) return // 已用色阶覆盖
|
||||
if (themeColors[key]) root.style.setProperty(cssVar, themeColors[key])
|
||||
})
|
||||
|
||||
// Primary 色阶 (50-950)
|
||||
if (shadeMap) {
|
||||
SHADE_STOPS.forEach(stop => {
|
||||
if (shadeMap[stop]) {
|
||||
root.style.setProperty(`--color-primary-${stop}`, shadeMap[stop])
|
||||
}
|
||||
})
|
||||
}
|
||||
|
||||
// Secondary 色阶 (50-950)
|
||||
if (themeColors.secondary) {
|
||||
const secondaryShades = generateShades(themeColors.secondary)
|
||||
SHADE_STOPS.forEach(stop => {
|
||||
root.style.setProperty(`--color-secondary-${stop}`, secondaryShades[stop])
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
useEffect(() => {
|
||||
fetchSettings()
|
||||
}, [])
|
||||
|
||||
const fetchSettings = async () => {
|
||||
try {
|
||||
const response = await fetch(`${API_BASE_URL}/settings`)
|
||||
if (response.ok) {
|
||||
const data = await response.json()
|
||||
setSettings(prev => ({ ...prev, ...data }))
|
||||
// 解析 theme_colors JSON
|
||||
if (data.theme_colors) {
|
||||
try {
|
||||
const parsed = JSON.parse(data.theme_colors)
|
||||
// 初始化网站配色
|
||||
const base = parsed.base || parsed.primary || '#2563EB'
|
||||
setColors(prev => ({ ...prev, ...parsed, primary: base }))
|
||||
const loadedShades = parsed.shades || generateShades(base)
|
||||
const loadedHarmony = parsed.harmony || generateHarmony(base)
|
||||
setBaseColor(base)
|
||||
setShades(loadedShades)
|
||||
setHarmony(loadedHarmony)
|
||||
// 加载后立即注入,刷新后配色不丢失
|
||||
injectThemeVars(parsed, loadedShades, loadedHarmony)
|
||||
} catch (e) {
|
||||
console.warn('theme_colors 解析失败', e)
|
||||
}
|
||||
}
|
||||
}
|
||||
} catch (error) {
|
||||
console.error('Failed to fetch settings:', error)
|
||||
} finally {
|
||||
setLoading(false)
|
||||
}
|
||||
}
|
||||
|
||||
const handleSave = async () => {
|
||||
setSaving(true)
|
||||
setMessage('')
|
||||
|
||||
// 把 colors + 网站配色数据合并到 settings.theme_colors
|
||||
const themeColorsPayload = {
|
||||
...colors,
|
||||
base: baseColor,
|
||||
shades,
|
||||
harmony,
|
||||
}
|
||||
const payload = {
|
||||
...settings,
|
||||
theme_colors: JSON.stringify(themeColorsPayload)
|
||||
}
|
||||
|
||||
try {
|
||||
const response = await fetch(`${API_BASE_URL}/settings`, {
|
||||
method: 'PUT',
|
||||
headers: {
|
||||
'Content-Type': 'application/json',
|
||||
'Authorization': `Bearer ${token}`
|
||||
},
|
||||
body: JSON.stringify(payload)
|
||||
})
|
||||
|
||||
if (response.ok) {
|
||||
setMessage('设置保存成功!配色已实时生效。')
|
||||
setSettings(payload)
|
||||
// 实时预览:立即把完整色阶注入 CSS 变量
|
||||
injectThemeVars({ ...colors, primary: baseColor }, shades, harmony)
|
||||
} else {
|
||||
setMessage('保存失败,请重试')
|
||||
}
|
||||
} catch (error) {
|
||||
setMessage('保存失败,请重试')
|
||||
} finally {
|
||||
setSaving(false)
|
||||
}
|
||||
}
|
||||
|
||||
const handlePasswordChange = async () => {
|
||||
setPasswordError('')
|
||||
|
||||
if (passwordData.new_password !== passwordData.confirm_password) {
|
||||
setPasswordError('两次输入的新密码不一致')
|
||||
return
|
||||
}
|
||||
|
||||
if (passwordData.new_password.length < 6) {
|
||||
setPasswordError('新密码至少需要6位')
|
||||
return
|
||||
}
|
||||
|
||||
try {
|
||||
const response = await fetch(`${API_BASE_URL}/auth/password`, {
|
||||
method: 'POST',
|
||||
headers: {
|
||||
'Content-Type': 'application/json',
|
||||
'Authorization': `Bearer ${token}`
|
||||
},
|
||||
body: JSON.stringify({
|
||||
old_password: passwordData.old_password,
|
||||
new_password: passwordData.new_password
|
||||
})
|
||||
})
|
||||
|
||||
if (response.ok) {
|
||||
setMessage('密码修改成功!')
|
||||
setPasswordData({ old_password: '', new_password: '', confirm_password: '' })
|
||||
setTimeout(() => setMessage(''), 3000)
|
||||
} else {
|
||||
const data = await response.json()
|
||||
setPasswordError(data.detail || '密码修改失败')
|
||||
}
|
||||
} catch (error) {
|
||||
setPasswordError('密码修改失败,请重试')
|
||||
}
|
||||
}
|
||||
|
||||
const handleLogout = async () => {
|
||||
localStorage.removeItem('token')
|
||||
await authApi.logout()
|
||||
localStorage.removeItem('user')
|
||||
window.location.href = '/login'
|
||||
}
|
||||
|
||||
// 标签页配置
|
||||
const tabs = [
|
||||
{ id: 'general', label: '基本设置', icon: '⚙️' },
|
||||
{ id: 'appearance', label: '外观设置', icon: '🎨' },
|
||||
{ id: 'color', label: '网站配色', icon: '🌈' },
|
||||
{ id: 'security', label: '安全设置', icon: '🔒' },
|
||||
]
|
||||
|
||||
if (loading) {
|
||||
return (
|
||||
<AdminLayout user={user} onLogout={handleLogout}>
|
||||
<div className="p-8 flex items-center justify-center min-h-[400px]">
|
||||
<div className="flex items-center gap-3 text-preline-text-secondary">
|
||||
<svg className="animate-spin h-5 w-5" viewBox="0 0 24 24" fill="none">
|
||||
<circle className="opacity-25" cx="12" cy="12" r="10" stroke="currentColor" strokeWidth="4" />
|
||||
<path className="opacity-75" fill="currentColor" d="M4 12a8 8 0 018-8V0C5.373 0 0 5.373 0 12h4z" />
|
||||
</svg>
|
||||
<span>加载中...</span>
|
||||
</div>
|
||||
</div>
|
||||
</AdminLayout>
|
||||
)
|
||||
}
|
||||
|
||||
return (
|
||||
<AdminLayout user={user} onLogout={handleLogout}>
|
||||
<div className="p-6 w-full">
|
||||
{/* 页面标题 */}
|
||||
<div className="mb-6">
|
||||
<h1 className="text-2xl font-semibold text-preline-text">系统设置</h1>
|
||||
<p className="text-preline-text-secondary mt-1">管理博客的基本信息、外观和安全设置</p>
|
||||
</div>
|
||||
|
||||
{/* 成功提示 */}
|
||||
{message && (
|
||||
<div className="mb-6 bg-preline-success-bg border border-preline-success-border rounded-lg p-4 flex items-center gap-3">
|
||||
<svg className="w-5 h-5 text-preline-success" fill="none" viewBox="0 0 24 24" stroke="currentColor">
|
||||
<path strokeLinecap="round" strokeLinejoin="round" strokeWidth={2} d="M5 13l4 4L19 7" />
|
||||
</svg>
|
||||
<span className="text-preline-success-text font-medium">{message}</span>
|
||||
</div>
|
||||
)}
|
||||
|
||||
{/* 标签页 */}
|
||||
<div className="mb-6 border-b border-preline-border">
|
||||
<nav className="flex gap-1">
|
||||
{tabs.map(tab => (
|
||||
<button
|
||||
key={tab.id}
|
||||
onClick={() => setActiveTab(tab.id)}
|
||||
className={`px-4 py-3 text-sm font-medium border-b-2 transition-colors duration-200 ${
|
||||
activeTab === tab.id
|
||||
? 'border-preline-primary-600 text-preline-primary-600'
|
||||
: 'border-transparent text-preline-text-secondary hover:text-preline-gray-700 hover:border-preline-gray-300'
|
||||
}`}
|
||||
>
|
||||
<span className="mr-2">{tab.icon}</span>
|
||||
{tab.label}
|
||||
</button>
|
||||
))}
|
||||
</nav>
|
||||
</div>
|
||||
|
||||
{/* 基本设置 */}
|
||||
{activeTab === 'general' && (
|
||||
<Card>
|
||||
<CardHeader>
|
||||
<div>
|
||||
<CardTitle>博客信息</CardTitle>
|
||||
<CardDescription>设置博客的基本信息,这些将显示在网站标题和描述中</CardDescription>
|
||||
</div>
|
||||
</CardHeader>
|
||||
<CardBody className="space-y-6">
|
||||
<div>
|
||||
<Label htmlFor="blog_name">博客名称</Label>
|
||||
<Input
|
||||
id="blog_name"
|
||||
value={settings.blog_name}
|
||||
onChange={(e) => setSettings({ ...settings, blog_name: e.target.value })}
|
||||
placeholder="输入博客名称"
|
||||
/>
|
||||
<FormHelp>显示在浏览器标签页和网站头部</FormHelp>
|
||||
</div>
|
||||
|
||||
<div>
|
||||
<Label htmlFor="blog_description">博客描述</Label>
|
||||
<Textarea
|
||||
id="blog_description"
|
||||
value={settings.blog_description}
|
||||
onChange={(e) => setSettings({ ...settings, blog_description: e.target.value })}
|
||||
placeholder="输入博客描述"
|
||||
rows={3}
|
||||
/>
|
||||
<FormHelp>用于 SEO 和社交媒体分享</FormHelp>
|
||||
</div>
|
||||
|
||||
<div>
|
||||
<Label htmlFor="welcome_message">欢迎语</Label>
|
||||
<Textarea
|
||||
id="welcome_message"
|
||||
value={settings.welcome_message}
|
||||
onChange={(e) => setSettings({ ...settings, welcome_message: e.target.value })}
|
||||
placeholder="输入首页欢迎语"
|
||||
rows={2}
|
||||
/>
|
||||
<FormHelp>显示在首页顶部的欢迎文字</FormHelp>
|
||||
</div>
|
||||
</CardBody>
|
||||
<CardFooter>
|
||||
<Button
|
||||
variant="secondary"
|
||||
onClick={() => fetchSettings()}
|
||||
disabled={saving}
|
||||
>
|
||||
重置
|
||||
</Button>
|
||||
<Button
|
||||
variant="primary"
|
||||
onClick={handleSave}
|
||||
loading={saving}
|
||||
>
|
||||
保存设置
|
||||
</Button>
|
||||
</CardFooter>
|
||||
</Card>
|
||||
)}
|
||||
|
||||
{/* 外观设置 */}
|
||||
{activeTab === 'appearance' && (
|
||||
<Card>
|
||||
<CardHeader>
|
||||
<div>
|
||||
<CardTitle>外观设置</CardTitle>
|
||||
<CardDescription>自定义博客的视觉风格</CardDescription>
|
||||
</div>
|
||||
</CardHeader>
|
||||
<CardBody className="space-y-6">
|
||||
<div>
|
||||
<Label htmlFor="layout">布局样式</Label>
|
||||
<Select
|
||||
id="layout"
|
||||
value={settings.layout}
|
||||
onChange={(e) => setSettings({ ...settings, layout: e.target.value })}
|
||||
>
|
||||
<option value="card">卡片布局</option>
|
||||
<option value="list">列表布局</option>
|
||||
<option value="magazine">杂志布局</option>
|
||||
</Select>
|
||||
<FormHelp>文章列表的展示方式</FormHelp>
|
||||
</div>
|
||||
|
||||
<div>
|
||||
<Label htmlFor="banner_type">首页横幅</Label>
|
||||
<Select
|
||||
id="banner_type"
|
||||
value={settings.banner_type}
|
||||
onChange={(e) => setSettings({ ...settings, banner_type: e.target.value })}
|
||||
>
|
||||
<option value="text">文字横幅</option>
|
||||
<option value="image">图片横幅</option>
|
||||
<option value="carousel">轮播横幅</option>
|
||||
<option value="none">不显示</option>
|
||||
</Select>
|
||||
<FormHelp>首页顶部横幅的展示方式</FormHelp>
|
||||
</div>
|
||||
|
||||
<hr className="border-preline-border" />
|
||||
|
||||
{/* 主题配色 */}
|
||||
<div>
|
||||
<h3 className="text-base font-semibold text-preline-text mb-1">主题配色</h3>
|
||||
<p className="text-sm text-preline-text-secondary mb-4">调整后台管理界面的配色方案,保存后刷新页面即可生效。</p>
|
||||
|
||||
<div className="grid grid-cols-1 sm:grid-cols-2 gap-5">
|
||||
{/* 主色 */}
|
||||
<div className="flex items-center gap-3">
|
||||
<input
|
||||
id="color-primary"
|
||||
type="color"
|
||||
value={colors.primary}
|
||||
onChange={(e) => setColors({ ...colors, primary: e.target.value })}
|
||||
className="w-10 h-10 rounded cursor-pointer border border-preline-gray-300 p-0.5"
|
||||
/>
|
||||
<div className="flex-1">
|
||||
<Label htmlFor="color-primary" className="mb-0">主色调</Label>
|
||||
<div className="text-xs text-preline-text-secondary font-mono mt-0.5">{colors.primary}</div>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
{/* 次色 */}
|
||||
<div className="flex items-center gap-3">
|
||||
<input
|
||||
id="color-secondary"
|
||||
type="color"
|
||||
value={colors.secondary}
|
||||
onChange={(e) => setColors({ ...colors, secondary: e.target.value })}
|
||||
className="w-10 h-10 rounded cursor-pointer border border-preline-gray-300 p-0.5"
|
||||
/>
|
||||
<div className="flex-1">
|
||||
<Label htmlFor="color-secondary" className="mb-0">次色调</Label>
|
||||
<div className="text-xs text-preline-text-secondary font-mono mt-0.5">{colors.secondary}</div>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
{/* 背景色 */}
|
||||
<div className="flex items-center gap-3">
|
||||
<input
|
||||
id="color-bg"
|
||||
type="color"
|
||||
value={colors.bg}
|
||||
onChange={(e) => setColors({ ...colors, bg: e.target.value })}
|
||||
className="w-10 h-10 rounded cursor-pointer border border-preline-gray-300 p-0.5"
|
||||
/>
|
||||
<div className="flex-1">
|
||||
<Label htmlFor="color-bg" className="mb-0">背景色</Label>
|
||||
<div className="text-xs text-preline-text-secondary font-mono mt-0.5">{colors.bg}</div>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
{/* 文字色 */}
|
||||
<div className="flex items-center gap-3">
|
||||
<input
|
||||
id="color-text"
|
||||
type="color"
|
||||
value={colors.text}
|
||||
onChange={(e) => setColors({ ...colors, text: e.target.value })}
|
||||
className="w-10 h-10 rounded cursor-pointer border border-preline-gray-300 p-0.5"
|
||||
/>
|
||||
<div className="flex-1">
|
||||
<Label htmlFor="color-text" className="mb-0">文字色</Label>
|
||||
<div className="text-xs text-preline-text-secondary font-mono mt-0.5">{colors.text}</div>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
{/* 侧边栏色 */}
|
||||
<div className="flex items-center gap-3">
|
||||
<input
|
||||
id="color-sidebar"
|
||||
type="color"
|
||||
value={colors.sidebar}
|
||||
onChange={(e) => setColors({ ...colors, sidebar: e.target.value })}
|
||||
className="w-10 h-10 rounded cursor-pointer border border-preline-gray-300 p-0.5"
|
||||
/>
|
||||
<div className="flex-1">
|
||||
<Label htmlFor="color-sidebar" className="mb-0">侧边栏背景</Label>
|
||||
<div className="text-xs text-preline-text-secondary font-mono mt-0.5">{colors.sidebar}</div>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
</CardBody>
|
||||
<CardFooter>
|
||||
<Button
|
||||
variant="secondary"
|
||||
onClick={() => fetchSettings()}
|
||||
disabled={saving}
|
||||
>
|
||||
重置
|
||||
</Button>
|
||||
<Button
|
||||
variant="primary"
|
||||
onClick={handleSave}
|
||||
loading={saving}
|
||||
>
|
||||
保存设置
|
||||
</Button>
|
||||
</CardFooter>
|
||||
</Card>
|
||||
)}
|
||||
|
||||
{/* 网站配色 */}
|
||||
{activeTab === 'color' && (
|
||||
<div className="space-y-6">
|
||||
{/* 基色控制 */}
|
||||
<Card>
|
||||
<CardHeader>
|
||||
<div>
|
||||
<CardTitle>配色生成器</CardTitle>
|
||||
<CardDescription>选择一个基色,自动生成 Tailwind 风格色阶与和谐配色</CardDescription>
|
||||
</div>
|
||||
</CardHeader>
|
||||
<CardBody className="space-y-6">
|
||||
<div className="flex flex-wrap items-center gap-4">
|
||||
<div className="flex items-center gap-3">
|
||||
<input
|
||||
type="color"
|
||||
value={baseColor}
|
||||
onChange={(e) => {
|
||||
const c = e.target.value
|
||||
setBaseColor(c)
|
||||
const newShades = generateShades(c)
|
||||
setShades(newShades)
|
||||
setHarmony(generateHarmony(c))
|
||||
setColors(prev => ({ ...prev, primary: c }))
|
||||
injectThemeVars({ ...colors, primary: c }, newShades, harmony)
|
||||
}}
|
||||
className="w-12 h-12 rounded-lg cursor-pointer border-2 border-preline-border p-1"
|
||||
/>
|
||||
<div>
|
||||
<div className="text-sm font-medium text-preline-text">基色</div>
|
||||
<div className="text-xs text-preline-text-secondary font-mono">{baseColor}</div>
|
||||
</div>
|
||||
</div>
|
||||
<input
|
||||
type="text"
|
||||
value={baseColor}
|
||||
onChange={(e) => {
|
||||
const c = e.target.value
|
||||
if (/^#[0-9A-Fa-f]{6}$/.test(c)) {
|
||||
setBaseColor(c)
|
||||
const newShades = generateShades(c)
|
||||
setShades(newShades)
|
||||
setHarmony(generateHarmony(c))
|
||||
setColors(prev => ({ ...prev, primary: c }))
|
||||
injectThemeVars({ ...colors, primary: c }, newShades, harmony)
|
||||
} else {
|
||||
setBaseColor(c)
|
||||
}
|
||||
}}
|
||||
className="px-3 py-2 border border-preline-gray-300 rounded-lg text-sm font-mono w-28"
|
||||
/>
|
||||
<Button
|
||||
variant="secondary"
|
||||
onClick={() => {
|
||||
const p = randomPalette()
|
||||
setBaseColor(p.base)
|
||||
setShades(p.shades)
|
||||
setHarmony(p.harmony)
|
||||
setColors(prev => ({ ...prev, primary: p.base }))
|
||||
injectThemeVars({ ...colors, primary: p.base }, p.shades, p.harmony)
|
||||
}}
|
||||
>
|
||||
🎲 随机配色
|
||||
</Button>
|
||||
</div>
|
||||
|
||||
{/* 模式切换 */}
|
||||
<div className="flex gap-2">
|
||||
<button
|
||||
onClick={() => setPaletteMode('shades')}
|
||||
className={`px-4 py-2 text-sm font-medium rounded-lg border transition-colors ${
|
||||
paletteMode === 'shades'
|
||||
? 'bg-preline-primary-600 text-white border-preline-primary-600'
|
||||
: 'bg-preline-card text-preline-gray-700 border-preline-gray-300 hover:bg-preline-gray-50'
|
||||
}`}
|
||||
>
|
||||
色阶 (Shades)
|
||||
</button>
|
||||
<button
|
||||
onClick={() => setPaletteMode('harmony')}
|
||||
className={`px-4 py-2 text-sm font-medium rounded-lg border transition-colors ${
|
||||
paletteMode === 'harmony'
|
||||
? 'bg-preline-primary-600 text-white border-preline-primary-600'
|
||||
: 'bg-preline-card text-preline-gray-700 border-preline-gray-300 hover:bg-preline-gray-50'
|
||||
}`}
|
||||
>
|
||||
和谐配色 (Harmony)
|
||||
</button>
|
||||
</div>
|
||||
</CardBody>
|
||||
</Card>
|
||||
|
||||
{/* 色阶预览 */}
|
||||
{paletteMode === 'shades' && (
|
||||
<Card>
|
||||
<CardHeader>
|
||||
<div>
|
||||
<CardTitle>Tailwind 色阶</CardTitle>
|
||||
<CardDescription>基于基色自动生成的 50-950 色阶,可直接用于 Tailwind CSS</CardDescription>
|
||||
</div>
|
||||
</CardHeader>
|
||||
<CardBody>
|
||||
<div className="space-y-2">
|
||||
{SHADE_STOPS.map((stop) => {
|
||||
const color = shades[stop] || baseColor
|
||||
const { l } = hexToHsl(color)
|
||||
const textColor = l > 55 ? '#000000' : '#ffffff'
|
||||
return (
|
||||
<div key={stop} className="flex items-center gap-3">
|
||||
<div className="w-12 text-xs text-preline-text-secondary font-mono text-right">{stop}</div>
|
||||
<div
|
||||
className="flex-1 h-10 rounded-lg flex items-center px-3 text-xs font-mono"
|
||||
style={{ backgroundColor: color, color: textColor }}
|
||||
>
|
||||
{color}
|
||||
</div>
|
||||
<button
|
||||
onClick={() => {
|
||||
navigator.clipboard.writeText(color)
|
||||
setMessage(`已复制 ${color}`)
|
||||
setTimeout(() => setMessage(''), 1500)
|
||||
}}
|
||||
className="text-xs text-preline-text-secondary hover:text-preline-primary-600 px-2"
|
||||
title="复制"
|
||||
>
|
||||
📋
|
||||
</button>
|
||||
</div>
|
||||
)
|
||||
})}
|
||||
</div>
|
||||
</CardBody>
|
||||
</Card>
|
||||
)}
|
||||
|
||||
{/* 和谐配色预览 */}
|
||||
{paletteMode === 'harmony' && (
|
||||
<Card>
|
||||
<CardHeader>
|
||||
<div>
|
||||
<CardTitle>和谐配色</CardTitle>
|
||||
<CardDescription>基于色彩理论生成的互补色、类比色、三角色等和谐组合</CardDescription>
|
||||
</div>
|
||||
</CardHeader>
|
||||
<CardBody>
|
||||
<div className="grid grid-cols-1 sm:grid-cols-2 lg:grid-cols-3 gap-4">
|
||||
{Object.entries(harmony).map(([name, color]) => {
|
||||
const labelMap = {
|
||||
complementary: '互补色',
|
||||
analogous1: '类比色 +30°',
|
||||
analogous2: '类比色 -30°',
|
||||
triadic1: '三角色 1',
|
||||
triadic2: '三角色 2',
|
||||
split1: '分裂互补 1',
|
||||
split2: '分裂互补 2',
|
||||
monoLight: '单色调亮',
|
||||
monoDark: '单色调暗',
|
||||
}
|
||||
const { l } = hexToHsl(color)
|
||||
const textColor = l > 55 ? '#000000' : '#ffffff'
|
||||
return (
|
||||
<div key={name} className="rounded-lg overflow-hidden border border-preline-border">
|
||||
<div
|
||||
className="h-20 flex items-end p-3 text-xs font-mono"
|
||||
style={{ backgroundColor: color, color: textColor }}
|
||||
>
|
||||
{color}
|
||||
</div>
|
||||
<div className="p-3 flex items-center justify-between bg-preline-card">
|
||||
<span className="text-sm font-medium text-preline-gray-700">{labelMap[name] || name}</span>
|
||||
<button
|
||||
onClick={() => {
|
||||
navigator.clipboard.writeText(color)
|
||||
setMessage(`已复制 ${color}`)
|
||||
setTimeout(() => setMessage(''), 1500)
|
||||
}}
|
||||
className="text-xs text-preline-text-secondary hover:text-preline-primary-600"
|
||||
>
|
||||
📋
|
||||
</button>
|
||||
</div>
|
||||
</div>
|
||||
)
|
||||
})}
|
||||
</div>
|
||||
</CardBody>
|
||||
</Card>
|
||||
)}
|
||||
|
||||
{/* 保存按钮 */}
|
||||
<Card>
|
||||
<CardFooter>
|
||||
<Button
|
||||
variant="secondary"
|
||||
onClick={() => fetchSettings()}
|
||||
disabled={saving}
|
||||
>
|
||||
重置
|
||||
</Button>
|
||||
<Button
|
||||
variant="primary"
|
||||
onClick={handleSave}
|
||||
loading={saving}
|
||||
>
|
||||
保存配色方案
|
||||
</Button>
|
||||
</CardFooter>
|
||||
</Card>
|
||||
</div>
|
||||
)}
|
||||
|
||||
{/* 安全设置 */}
|
||||
{activeTab === 'security' && (
|
||||
<Card>
|
||||
<CardHeader>
|
||||
<div>
|
||||
<CardTitle>修改密码</CardTitle>
|
||||
<CardDescription>定期更换密码可以提高账户安全性</CardDescription>
|
||||
</div>
|
||||
</CardHeader>
|
||||
<CardBody className="space-y-6">
|
||||
<div>
|
||||
<Label htmlFor="old_password">当前密码</Label>
|
||||
<Input
|
||||
id="old_password"
|
||||
type="password"
|
||||
value={passwordData.old_password}
|
||||
onChange={(e) => setPasswordData({ ...passwordData, old_password: e.target.value })}
|
||||
placeholder="输入当前密码"
|
||||
/>
|
||||
</div>
|
||||
|
||||
<div>
|
||||
<Label htmlFor="new_password">新密码</Label>
|
||||
<Input
|
||||
id="new_password"
|
||||
type="password"
|
||||
value={passwordData.new_password}
|
||||
onChange={(e) => setPasswordData({ ...passwordData, new_password: e.target.value })}
|
||||
placeholder="输入新密码(至少6位)"
|
||||
/>
|
||||
</div>
|
||||
|
||||
<div>
|
||||
<Label htmlFor="confirm_password">确认新密码</Label>
|
||||
<Input
|
||||
id="confirm_password"
|
||||
type="password"
|
||||
value={passwordData.confirm_password}
|
||||
onChange={(e) => setPasswordData({ ...passwordData, confirm_password: e.target.value })}
|
||||
placeholder="再次输入新密码"
|
||||
error={passwordError}
|
||||
/>
|
||||
{passwordError && <FormError>{passwordError}</FormError>}
|
||||
</div>
|
||||
</CardBody>
|
||||
<CardFooter>
|
||||
<Button
|
||||
variant="secondary"
|
||||
onClick={() => {
|
||||
setPasswordData({ old_password: '', new_password: '', confirm_password: '' })
|
||||
setPasswordError('')
|
||||
}}
|
||||
>
|
||||
重置
|
||||
</Button>
|
||||
<Button
|
||||
variant="primary"
|
||||
onClick={handlePasswordChange}
|
||||
>
|
||||
修改密码
|
||||
</Button>
|
||||
</CardFooter>
|
||||
</Card>
|
||||
)}
|
||||
</div>
|
||||
</AdminLayout>
|
||||
)
|
||||
}
|
||||
|
||||
export default Settings
|
||||
@@ -0,0 +1,211 @@
|
||||
/**
|
||||
* 配色工具 - 色阶生成与和谐配色
|
||||
* 参考 tailwindcolorshades + kigen.design 的配色算法
|
||||
*/
|
||||
|
||||
// ============ 基础转换函数 ============
|
||||
|
||||
function hexToRgb(hex) {
|
||||
const sanitized = hex.replace('#', '');
|
||||
const bigint = parseInt(sanitized, 16);
|
||||
const r = (bigint >> 16) & 255;
|
||||
const g = (bigint >> 8) & 255;
|
||||
const b = bigint & 255;
|
||||
return { r, g, b };
|
||||
}
|
||||
|
||||
function rgbToHex(r, g, b) {
|
||||
const toHex = (n) => {
|
||||
const hex = Math.round(n).toString(16);
|
||||
return hex.length === 1 ? '0' + hex : hex;
|
||||
};
|
||||
return `#${toHex(r)}${toHex(g)}${toHex(b)}`;
|
||||
}
|
||||
|
||||
function rgbToHsl(r, g, b) {
|
||||
r /= 255; g /= 255; b /= 255;
|
||||
const max = Math.max(r, g, b);
|
||||
const min = Math.min(r, g, b);
|
||||
let h, s, l = (max + min) / 2;
|
||||
|
||||
if (max === min) {
|
||||
h = s = 0;
|
||||
} else {
|
||||
const d = max - min;
|
||||
s = l > 0.5 ? d / (2 - max - min) : d / (max + min);
|
||||
switch (max) {
|
||||
case r: h = ((g - b) / d + (g < b ? 6 : 0)) / 6; break;
|
||||
case g: h = ((b - r) / d + 2) / 6; break;
|
||||
case b: h = ((r - g) / d + 4) / 6; break;
|
||||
}
|
||||
}
|
||||
return { h: h * 360, s: s * 100, l: l * 100 };
|
||||
}
|
||||
|
||||
function hslToRgb(h, s, l) {
|
||||
h /= 360; s /= 100; l /= 100;
|
||||
let r, g, b;
|
||||
|
||||
if (s === 0) {
|
||||
r = g = b = l;
|
||||
} else {
|
||||
const hue2rgb = (p, q, t) => {
|
||||
if (t < 0) t += 1;
|
||||
if (t > 1) t -= 1;
|
||||
if (t < 1/6) return p + (q - p) * 6 * t;
|
||||
if (t < 1/2) return q;
|
||||
if (t < 2/3) return p + (q - p) * (2/3 - t) * 6;
|
||||
return p;
|
||||
};
|
||||
const q = l < 0.5 ? l * (1 + s) : l + s - l * s;
|
||||
const p = 2 * l - q;
|
||||
r = hue2rgb(p, q, h + 1/3);
|
||||
g = hue2rgb(p, q, h);
|
||||
b = hue2rgb(p, q, h - 1/3);
|
||||
}
|
||||
return { r: r * 255, g: g * 255, b: b * 255 };
|
||||
}
|
||||
|
||||
function hexToHsl(hex) {
|
||||
const rgb = hexToRgb(hex);
|
||||
return rgbToHsl(rgb.r, rgb.g, rgb.b);
|
||||
}
|
||||
|
||||
function hslToHex(h, s, l) {
|
||||
const rgb = hslToRgb(h, s, l);
|
||||
return rgbToHex(rgb.r, rgb.g, rgb.b);
|
||||
}
|
||||
|
||||
// ============ 色阶生成 (Tailwind 风格) ============
|
||||
|
||||
const SHADE_STOPS = [50, 100, 200, 300, 400, 500, 600, 700, 800, 900, 950];
|
||||
|
||||
// Tailwind 默认色阶的亮度映射 (近似)
|
||||
const DEFAULT_LIGHTNESS_MAP = {
|
||||
50: 95.5,
|
||||
100: 91.0,
|
||||
200: 82.0,
|
||||
300: 72.5,
|
||||
400: 62.0,
|
||||
500: 52.0,
|
||||
600: 42.5,
|
||||
700: 33.0,
|
||||
800: 23.5,
|
||||
900: 14.0,
|
||||
950: 8.0,
|
||||
};
|
||||
|
||||
// 根据基色亮度自适应调整映射,让基色尽量对齐到 500
|
||||
function generateLightnessMap(baseL) {
|
||||
// 基色在 500 位置,计算偏移量
|
||||
const offset = baseL - DEFAULT_LIGHTNESS_MAP[500];
|
||||
const map = {};
|
||||
for (const stop of SHADE_STOPS) {
|
||||
let l = DEFAULT_LIGHTNESS_MAP[stop] + offset;
|
||||
// 限制在合理范围内
|
||||
if (stop <= 100) l = Math.min(l, 98);
|
||||
if (stop >= 900) l = Math.max(l, 3);
|
||||
map[stop] = Math.max(2, Math.min(98, l));
|
||||
}
|
||||
return map;
|
||||
}
|
||||
|
||||
function generateShades(baseHex) {
|
||||
const baseHsl = hexToHsl(baseHex);
|
||||
const lightnessMap = generateLightnessMap(baseHsl.l);
|
||||
const shades = {};
|
||||
|
||||
for (const stop of SHADE_STOPS) {
|
||||
let s = baseHsl.s;
|
||||
let l = lightnessMap[stop];
|
||||
|
||||
// 高亮区降低饱和度,避免过艳
|
||||
if (stop <= 100) {
|
||||
s = s * 0.4;
|
||||
} else if (stop <= 200) {
|
||||
s = s * 0.6;
|
||||
} else if (stop <= 300) {
|
||||
s = s * 0.8;
|
||||
}
|
||||
|
||||
// 极暗区略微降低饱和度,避免浑浊
|
||||
if (stop >= 900) {
|
||||
s = Math.min(s * 1.1, 100);
|
||||
}
|
||||
|
||||
shades[stop] = hslToHex(baseHsl.h, s, l);
|
||||
}
|
||||
|
||||
return shades;
|
||||
}
|
||||
|
||||
// ============ 和谐配色 (类似 kigen.design) ============
|
||||
|
||||
function generateHarmony(baseHex) {
|
||||
const { h, s, l } = hexToHsl(baseHex);
|
||||
|
||||
const harmonies = {
|
||||
// 互补色
|
||||
complementary: hslToHex((h + 180) % 360, Math.min(s * 0.95, 95), Math.max(l, 35)),
|
||||
// 类比色 (左)
|
||||
analogous1: hslToHex((h + 30) % 360, s * 0.9, l),
|
||||
// 类比色 (右)
|
||||
analogous2: hslToHex((h - 30 + 360) % 360, s * 0.9, l),
|
||||
// 三角色 1
|
||||
triadic1: hslToHex((h + 120) % 360, s * 0.9, Math.max(l, 30)),
|
||||
// 三角色 2
|
||||
triadic2: hslToHex((h + 240) % 360, s * 0.9, Math.max(l, 30)),
|
||||
// 分裂互补 1
|
||||
split1: hslToHex((h + 150) % 360, s * 0.85, Math.max(l, 30)),
|
||||
// 分裂互补 2
|
||||
split2: hslToHex((h + 210) % 360, s * 0.85, Math.max(l, 30)),
|
||||
// 单色调亮
|
||||
monoLight: hslToHex(h, s * 0.5, Math.min(l + 35, 95)),
|
||||
// 单色调暗
|
||||
monoDark: hslToHex(h, Math.min(s * 1.1, 100), Math.max(l - 25, 10)),
|
||||
};
|
||||
|
||||
return harmonies;
|
||||
}
|
||||
|
||||
// ============ 随机生成和谐基色 ============
|
||||
|
||||
function randomBaseColor() {
|
||||
const hue = Math.floor(Math.random() * 360);
|
||||
const sat = 55 + Math.floor(Math.random() * 35); // 55-90%
|
||||
const light = 45 + Math.floor(Math.random() * 20); // 45-65%
|
||||
return hslToHex(hue, sat, light);
|
||||
}
|
||||
|
||||
function randomPalette() {
|
||||
const base = randomBaseColor();
|
||||
return {
|
||||
base,
|
||||
shades: generateShades(base),
|
||||
harmony: generateHarmony(base),
|
||||
};
|
||||
}
|
||||
|
||||
// ============ 导出 ============
|
||||
|
||||
export {
|
||||
hexToRgb,
|
||||
rgbToHex,
|
||||
rgbToHsl,
|
||||
hslToRgb,
|
||||
hexToHsl,
|
||||
hslToHex,
|
||||
generateShades,
|
||||
generateHarmony,
|
||||
randomBaseColor,
|
||||
randomPalette,
|
||||
SHADE_STOPS,
|
||||
};
|
||||
|
||||
export default {
|
||||
generateShades,
|
||||
generateHarmony,
|
||||
randomPalette,
|
||||
hexToHsl,
|
||||
hslToHex,
|
||||
};
|
||||
Reference in New Issue
Block a user