优化页面、修复BUG
This commit is contained in:
87
client/scripts/migrate-api-response.mjs
Normal file
87
client/scripts/migrate-api-response.mjs
Normal file
@@ -0,0 +1,87 @@
|
||||
import fs from 'fs'
|
||||
import path from 'path'
|
||||
import { fileURLToPath } from 'url'
|
||||
|
||||
const __dirname = path.dirname(fileURLToPath(import.meta.url))
|
||||
const apiPath = path.join(__dirname, '../src/services/api.ts')
|
||||
let content = fs.readFileSync(apiPath, 'utf8')
|
||||
|
||||
// Remove errorData blocks after authFetch/fetch
|
||||
content = content.replace(
|
||||
/\s*if \(!response\.ok\) \{\s*const errorData = await response\.json\(\)\s*throw new Error\(errorData\.message \|\| '[^']*'\)\s*\}/g,
|
||||
''
|
||||
)
|
||||
|
||||
// Remove simple throw patterns
|
||||
content = content.replace(/\s*if \(!response\.ok\) throw new Error\('[^']*'\)/g, '')
|
||||
|
||||
// return data.result -> parseApiResponse
|
||||
content = content.replace(
|
||||
/const data = await response\.json\(\)\s*return data\.result/g,
|
||||
'return await parseApiResponse(response)'
|
||||
)
|
||||
|
||||
// return (data.result?.list || []) patterns
|
||||
content = content.replace(
|
||||
/const data = await response\.json\(\)\s*\/\/[^\n]*\n\s*return \(data\.result\?\.([^)]+)\)/g,
|
||||
'const data = await parseApiResponse<any>(response)\n return (data?.$1)'
|
||||
)
|
||||
|
||||
content = content.replace(
|
||||
/const data = await response\.json\(\)\s*return \(data\.result\?\.([^)]+)\)/g,
|
||||
'const data = await parseApiResponse<any>(response)\n return (data?.$1)'
|
||||
)
|
||||
|
||||
// return data.result || []
|
||||
content = content.replace(
|
||||
/const data = await response\.json\(\)\s*return data\.result \|\| \[\]/g,
|
||||
'return (await parseApiResponse<any[]>(response)) || []'
|
||||
)
|
||||
|
||||
// const result = data.result as X patterns - keep data line, fix next lines
|
||||
content = content.replace(
|
||||
/const data = await response\.json\(\)\s*const result = data\.result as/g,
|
||||
'const result = await parseApiResponse'
|
||||
)
|
||||
|
||||
// login block
|
||||
content = content.replace(
|
||||
/export const login = async \(credentials: LoginRequest\): Promise<LoginResponse> => \{[\s\S]*?\n\}/,
|
||||
`export const login = async (credentials: LoginRequest): Promise<LoginResponse> => {
|
||||
try {
|
||||
const response = await fetch(\`\${API_BASE}/admin/login\`, {
|
||||
method: 'POST',
|
||||
headers: { 'Content-Type': 'application/json' },
|
||||
body: JSON.stringify(credentials),
|
||||
})
|
||||
const result = await parseApiResponse<{ token: string; user: User; expire: number }>(response, {
|
||||
skipSessionExpired: true,
|
||||
})
|
||||
return {
|
||||
token: result.token,
|
||||
user: result.user,
|
||||
expire: result.expire,
|
||||
}
|
||||
} catch (error) {
|
||||
console.error('Login error:', error)
|
||||
throw error
|
||||
}
|
||||
}`
|
||||
)
|
||||
|
||||
// void returns that only had authFetch + ok check - add parseApiResponse
|
||||
content = content.replace(
|
||||
/(const response = await authFetch\([^)]+\)[\s\S]*?\))\s*\n(\s*\} catch)/g,
|
||||
(match, fetchPart, catchPart) => {
|
||||
if (match.includes('parseApiResponse') || match.includes('return await')) {
|
||||
return match
|
||||
}
|
||||
if (match.includes('method:')) {
|
||||
return `${fetchPart}\n await parseApiResponse(response)\n${catchPart}`
|
||||
}
|
||||
return match
|
||||
}
|
||||
)
|
||||
|
||||
fs.writeFileSync(apiPath, content)
|
||||
console.log('Migration complete')
|
||||
65
client/src/components/SearchSuggestDropdown.vue
Normal file
65
client/src/components/SearchSuggestDropdown.vue
Normal file
@@ -0,0 +1,65 @@
|
||||
<template>
|
||||
<div
|
||||
v-if="visible"
|
||||
class="absolute left-0 right-0 top-full mt-2 z-30 bg-[#121214] border border-white/10 rounded-xl shadow-2xl overflow-hidden"
|
||||
>
|
||||
<div v-if="history.length > 0" class="p-3 border-b border-white/5">
|
||||
<div class="flex items-center justify-between mb-2">
|
||||
<span class="text-xs text-art-muted uppercase tracking-wider">搜索历史</span>
|
||||
<button type="button" class="text-xs text-art-accent hover:text-white" @mousedown.prevent="emit('clear-history')">
|
||||
清空
|
||||
</button>
|
||||
</div>
|
||||
<div class="flex flex-wrap gap-2">
|
||||
<button
|
||||
v-for="item in history"
|
||||
:key="`history-${item}`"
|
||||
type="button"
|
||||
class="group inline-flex items-center gap-1 px-3 py-1.5 rounded-full bg-white/5 hover:bg-white/10 text-sm text-white/80"
|
||||
@mousedown.prevent="emit('select', item)"
|
||||
>
|
||||
<span>{{ item }}</span>
|
||||
<span
|
||||
class="text-white/30 hover:text-white"
|
||||
@mousedown.prevent.stop="emit('remove-history', item)"
|
||||
>×</span>
|
||||
</button>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<div class="p-3">
|
||||
<div class="text-xs text-art-muted uppercase tracking-wider mb-2">大家都在搜</div>
|
||||
<div v-if="loadingHot" class="text-sm text-art-muted py-2">加载中...</div>
|
||||
<div v-else-if="hotKeywords.length === 0" class="text-sm text-art-muted py-2">暂无热门搜索</div>
|
||||
<div v-else class="flex flex-wrap gap-2">
|
||||
<button
|
||||
v-for="item in hotKeywords"
|
||||
:key="`hot-${item.keyword}`"
|
||||
type="button"
|
||||
class="inline-flex items-center gap-2 px-3 py-1.5 rounded-full bg-art-accent/10 hover:bg-art-accent/20 text-sm text-art-accent"
|
||||
@mousedown.prevent="emit('select', item.keyword)"
|
||||
>
|
||||
<span>{{ item.keyword }}</span>
|
||||
<span class="text-xs opacity-60">{{ item.count }}</span>
|
||||
</button>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
</template>
|
||||
|
||||
<script setup lang="ts">
|
||||
import type { HotSearchKeyword } from '../services/api'
|
||||
|
||||
defineProps<{
|
||||
visible: boolean
|
||||
history: string[]
|
||||
hotKeywords: HotSearchKeyword[]
|
||||
loadingHot: boolean
|
||||
}>()
|
||||
|
||||
const emit = defineEmits<{
|
||||
select: [keyword: string]
|
||||
'remove-history': [keyword: string]
|
||||
'clear-history': []
|
||||
}>()
|
||||
</script>
|
||||
@@ -149,6 +149,7 @@
|
||||
</div>
|
||||
</div>
|
||||
</main>
|
||||
<SessionExpiredModal />
|
||||
</div>
|
||||
</template>
|
||||
|
||||
@@ -156,12 +157,15 @@
|
||||
import { ref, onMounted, onUnmounted, computed } from 'vue'
|
||||
import { useRouter, useRoute } from 'vue-router'
|
||||
import { useToast } from '../../composables/useToast'
|
||||
import { useAuth } from '../../composables/useAuth'
|
||||
import SessionExpiredModal from './SessionExpiredModal.vue'
|
||||
|
||||
const router = useRouter()
|
||||
const route = useRoute()
|
||||
const toast = useToast()
|
||||
const { logout, scheduleExpiryCheck, getUser, isAuthenticated } = useAuth()
|
||||
const isSidebarOpen = ref(true)
|
||||
const currentUser = ref(JSON.parse(localStorage.getItem('user') || '{}'))
|
||||
const currentUser = ref(getUser())
|
||||
|
||||
// Dropdown logic
|
||||
const isUserDropdownOpen = ref(false)
|
||||
@@ -286,10 +290,8 @@ const toggleSidebar = () => {
|
||||
}
|
||||
|
||||
const handleLogout = () => {
|
||||
localStorage.removeItem('token')
|
||||
localStorage.removeItem('user')
|
||||
logout()
|
||||
toast.showToast('退出登录成功', 'success')
|
||||
router.push('/login')
|
||||
}
|
||||
|
||||
// Helper to determine active state
|
||||
@@ -320,10 +322,11 @@ const currentRouteTitle = computed(() => {
|
||||
|
||||
// Check if user is authenticated
|
||||
onMounted(() => {
|
||||
const token = localStorage.getItem('token')
|
||||
if (!token) {
|
||||
if (!isAuthenticated()) {
|
||||
router.push('/login')
|
||||
return
|
||||
}
|
||||
scheduleExpiryCheck()
|
||||
document.addEventListener('click', closeDropdown)
|
||||
|
||||
// Auto open menu based on current route
|
||||
|
||||
@@ -1,86 +1,107 @@
|
||||
<template>
|
||||
<Teleport to="body">
|
||||
<div v-if="show" class="fixed inset-0 bg-black/50 flex items-center justify-center z-50" @click.self="handleClose">
|
||||
<div class="admin-card max-w-2xl w-full mx-4 max-h-[90vh] overflow-y-auto">
|
||||
<div class="flex items-center justify-between mb-6">
|
||||
<h2 class="text-xl font-serif italic text-white">附件详情</h2>
|
||||
<button @click="handleClose" class="text-white/40 hover:text-white transition-colors">
|
||||
<svg xmlns="http://www.w3.org/2000/svg" width="20" height="20" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round">
|
||||
<line x1="18" y1="6" x2="6" y2="18"></line>
|
||||
<line x1="6" y1="6" x2="18" y2="18"></line>
|
||||
</svg>
|
||||
</button>
|
||||
</div>
|
||||
|
||||
<div v-if="attachment" class="space-y-6">
|
||||
<!-- 图片预览 -->
|
||||
<div v-if="attachment.fileType === 'image'" class="w-full rounded-lg overflow-hidden bg-white/5">
|
||||
<img :src="attachment.fileUrl" :alt="attachment.originalName" class="w-full h-auto max-h-96 object-contain" />
|
||||
<div
|
||||
v-if="show"
|
||||
class="fixed inset-0 z-50 flex items-center justify-center bg-black/60 backdrop-blur-sm p-4"
|
||||
@click.self="handleClose"
|
||||
>
|
||||
<div class="admin-card max-w-3xl w-full mx-4 max-h-[92vh] overflow-hidden flex flex-col border border-white/10 shadow-2xl">
|
||||
<!-- Header -->
|
||||
<div class="flex items-start justify-between gap-4 px-6 py-4 border-b border-white/10 shrink-0">
|
||||
<div class="min-w-0">
|
||||
<h2 class="text-xl font-serif italic text-white">附件详情</h2>
|
||||
<p v-if="attachment" class="text-sm text-art-muted mt-1 truncate" :title="attachment.originalName">
|
||||
{{ attachment.originalName }}
|
||||
</p>
|
||||
</div>
|
||||
<button @click="handleClose" class="text-white/40 hover:text-white transition-colors shrink-0 p-1">
|
||||
<svg xmlns="http://www.w3.org/2000/svg" width="20" height="20" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2">
|
||||
<line x1="18" y1="6" x2="6" y2="18"></line>
|
||||
<line x1="6" y1="6" x2="18" y2="18"></line>
|
||||
</svg>
|
||||
</button>
|
||||
</div>
|
||||
|
||||
<!-- 文件信息 -->
|
||||
<div class="space-y-4">
|
||||
<div>
|
||||
<label class="block text-xs font-medium text-art-muted uppercase tracking-wider mb-2">文件名</label>
|
||||
<p class="text-white">{{ attachment.originalName }}</p>
|
||||
</div>
|
||||
|
||||
<div class="grid grid-cols-2 gap-4">
|
||||
<div>
|
||||
<label class="block text-xs font-medium text-art-muted uppercase tracking-wider mb-2">文件大小</label>
|
||||
<p class="text-white">{{ formatFileSize(attachment.fileSize) }}</p>
|
||||
</div>
|
||||
|
||||
<div>
|
||||
<label class="block text-xs font-medium text-art-muted uppercase tracking-wider mb-2">文件类型</label>
|
||||
<p class="text-white">{{ getFileTypeLabel(attachment.fileType) }}</p>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<div v-if="attachment.mimeType">
|
||||
<label class="block text-xs font-medium text-art-muted uppercase tracking-wider mb-2">MIME类型</label>
|
||||
<p class="text-white font-mono text-sm">{{ attachment.mimeType }}</p>
|
||||
</div>
|
||||
|
||||
<div>
|
||||
<label class="block text-xs font-medium text-art-muted uppercase tracking-wider mb-2">存储类型</label>
|
||||
<p class="text-white">{{ getStorageTypeLabel(attachment.storageType) }}</p>
|
||||
</div>
|
||||
|
||||
<div>
|
||||
<label class="block text-xs font-medium text-art-muted uppercase tracking-wider mb-2">分类</label>
|
||||
<CustomSelect
|
||||
v-model="localCategoryId"
|
||||
:options="categoryOptions"
|
||||
placeholder="无分类"
|
||||
/>
|
||||
</div>
|
||||
|
||||
<div>
|
||||
<label class="block text-xs font-medium text-art-muted uppercase tracking-wider mb-2">文件URL</label>
|
||||
<div class="flex gap-2">
|
||||
<input
|
||||
type="text"
|
||||
:value="attachment.fileUrl"
|
||||
readonly
|
||||
class="admin-input flex-1 font-mono text-sm"
|
||||
|
||||
<div v-if="attachment" class="overflow-y-auto custom-scrollbar flex-1">
|
||||
<!-- Media preview -->
|
||||
<div class="px-6 pt-6">
|
||||
<div class="rounded-xl overflow-hidden bg-black/40 border border-white/10 min-h-[200px] flex items-center justify-center">
|
||||
<img
|
||||
v-if="attachment.fileType === 'image'"
|
||||
:src="attachment.fileUrl"
|
||||
:alt="attachment.originalName"
|
||||
class="w-full max-h-[420px] object-contain"
|
||||
/>
|
||||
<button
|
||||
@click="handleCopyUrl"
|
||||
class="admin-btn-secondary px-4 whitespace-nowrap"
|
||||
>
|
||||
复制
|
||||
</button>
|
||||
<video
|
||||
v-else-if="attachment.fileType === 'video'"
|
||||
:src="attachment.fileUrl"
|
||||
controls
|
||||
preload="metadata"
|
||||
class="w-full max-h-[420px] bg-black"
|
||||
/>
|
||||
<div v-else class="flex flex-col items-center justify-center py-16 px-6 text-center">
|
||||
<div class="w-20 h-20 rounded-2xl bg-white/5 border border-white/10 flex items-center justify-center mb-4">
|
||||
<svg xmlns="http://www.w3.org/2000/svg" width="36" height="36" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="1.5" class="text-art-muted">
|
||||
<path d="M14 2H6a2 2 0 0 0-2 2v16a2 2 0 0 0 2 2h12a2 2 0 0 0 2-2V8z"></path>
|
||||
<polyline points="14 2 14 8 20 8"></polyline>
|
||||
</svg>
|
||||
</div>
|
||||
<p class="text-white font-medium mb-1">{{ attachment.originalName }}</p>
|
||||
<p class="text-sm text-art-muted">此文件类型暂不支持预览</p>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<div v-if="attachment.createdAt" class="text-xs text-art-muted">
|
||||
创建时间: {{ formatDate(attachment.createdAt) }}
|
||||
|
||||
<!-- Badges -->
|
||||
<div class="px-6 pt-4 flex flex-wrap gap-2">
|
||||
<span class="px-3 py-1 rounded-full text-xs font-medium border" :class="typeBadgeClass">
|
||||
{{ getFileTypeLabel(attachment.fileType) }}
|
||||
</span>
|
||||
<span class="px-3 py-1 rounded-full text-xs bg-white/5 text-art-muted border border-white/10">
|
||||
{{ formatFileSize(attachment.fileSize) }}
|
||||
</span>
|
||||
<span class="px-3 py-1 rounded-full text-xs bg-white/5 text-art-muted border border-white/10">
|
||||
{{ getStorageTypeLabel(attachment.storageType) }}
|
||||
</span>
|
||||
</div>
|
||||
|
||||
<!-- Meta grid -->
|
||||
<div class="px-6 py-5 grid sm:grid-cols-2 gap-4">
|
||||
<div class="rounded-lg bg-white/[0.03] border border-white/5 p-4">
|
||||
<label class="block text-xs font-medium text-art-muted uppercase tracking-wider mb-2">MIME 类型</label>
|
||||
<p class="text-white font-mono text-sm break-all">{{ attachment.mimeType || '—' }}</p>
|
||||
</div>
|
||||
<div class="rounded-lg bg-white/[0.03] border border-white/5 p-4">
|
||||
<label class="block text-xs font-medium text-art-muted uppercase tracking-wider mb-2">创建时间</label>
|
||||
<p class="text-white text-sm">{{ attachment.createdAt ? formatDate(attachment.createdAt) : '—' }}</p>
|
||||
</div>
|
||||
<div class="sm:col-span-2 rounded-lg bg-white/[0.03] border border-white/5 p-4">
|
||||
<label class="block text-xs font-medium text-art-muted uppercase tracking-wider mb-2">分类</label>
|
||||
<CustomSelect
|
||||
v-model="localCategoryId"
|
||||
:options="categoryOptions"
|
||||
placeholder="无分类"
|
||||
/>
|
||||
</div>
|
||||
<div class="sm:col-span-2 rounded-lg bg-white/[0.03] border border-white/5 p-4">
|
||||
<label class="block text-xs font-medium text-art-muted uppercase tracking-wider mb-2">文件 URL</label>
|
||||
<div class="flex gap-2">
|
||||
<input
|
||||
type="text"
|
||||
:value="attachment.fileUrl"
|
||||
readonly
|
||||
class="admin-input flex-1 font-mono text-sm"
|
||||
/>
|
||||
<button @click="handleCopyUrl" class="admin-btn-secondary px-4 whitespace-nowrap">
|
||||
复制
|
||||
</button>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<!-- 操作按钮 -->
|
||||
<div class="flex gap-3 pt-4 border-t border-white/10">
|
||||
|
||||
<!-- Footer -->
|
||||
<div class="flex gap-3 px-6 py-4 border-t border-white/10 shrink-0">
|
||||
<button @click="handleClose" class="admin-btn-secondary flex-1">
|
||||
取消
|
||||
</button>
|
||||
@@ -90,7 +111,6 @@
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
</Teleport>
|
||||
</template>
|
||||
|
||||
@@ -132,7 +152,6 @@ const emit = defineEmits<{
|
||||
const localCategoryId = ref<number>(0)
|
||||
const saving = ref(false)
|
||||
|
||||
// 计算属性:分类选项
|
||||
const categoryOptions = computed(() => {
|
||||
return [
|
||||
{ value: 0, label: '无分类' },
|
||||
@@ -140,7 +159,16 @@ const categoryOptions = computed(() => {
|
||||
]
|
||||
})
|
||||
|
||||
// 监听attachment变化,更新本地分类ID
|
||||
const typeBadgeClass = computed(() => {
|
||||
const map: Record<string, string> = {
|
||||
image: 'bg-emerald-500/10 text-emerald-300 border-emerald-500/30',
|
||||
video: 'bg-violet-500/10 text-violet-300 border-violet-500/30',
|
||||
document: 'bg-blue-500/10 text-blue-300 border-blue-500/30',
|
||||
other: 'bg-white/5 text-art-muted border-white/10'
|
||||
}
|
||||
return map[props.attachment?.fileType || 'other'] || map.other
|
||||
})
|
||||
|
||||
watch(() => props.attachment, (newAttachment) => {
|
||||
if (newAttachment) {
|
||||
localCategoryId.value = newAttachment.categoryId || 0
|
||||
@@ -155,7 +183,6 @@ const handleSave = () => {
|
||||
saving.value = true
|
||||
const categoryId = localCategoryId.value === 0 ? null : localCategoryId.value
|
||||
emit('save', { categoryId })
|
||||
// saving状态由父组件控制
|
||||
}
|
||||
|
||||
const handleCopyUrl = () => {
|
||||
@@ -183,8 +210,8 @@ const getFileTypeLabel = (fileType: string): string => {
|
||||
const getStorageTypeLabel = (storageType?: string): string => {
|
||||
const labels: Record<string, string> = {
|
||||
local: '本地存储',
|
||||
qcloud: '腾讯云COS',
|
||||
aliyun: '阿里云OSS',
|
||||
qcloud: '腾讯云 COS',
|
||||
aliyun: '阿里云 OSS',
|
||||
qiniu: '七牛云'
|
||||
}
|
||||
return labels[storageType || 'local'] || storageType || '本地存储'
|
||||
@@ -195,12 +222,15 @@ const formatDate = (timestamp: string | number): string => {
|
||||
return date.toLocaleString('zh-CN')
|
||||
}
|
||||
|
||||
// 暴露saving状态给父组件
|
||||
defineExpose({
|
||||
saving
|
||||
})
|
||||
defineExpose({ saving })
|
||||
</script>
|
||||
|
||||
<style scoped>
|
||||
/* 使用全局admin样式,无需额外样式 */
|
||||
.custom-scrollbar::-webkit-scrollbar {
|
||||
width: 4px;
|
||||
}
|
||||
.custom-scrollbar::-webkit-scrollbar-thumb {
|
||||
background: rgba(255, 255, 255, 0.1);
|
||||
border-radius: 2px;
|
||||
}
|
||||
</style>
|
||||
|
||||
@@ -187,7 +187,7 @@
|
||||
<script setup lang="ts">
|
||||
import { ref, computed } from 'vue'
|
||||
import { useToast } from '../../composables/useToast'
|
||||
import { API_BASE } from '../../services/api'
|
||||
import { API_BASE, authFetch, parseApiResponse } from '../../services/api'
|
||||
import AttachmentLibraryModal from './AttachmentLibraryModal.vue'
|
||||
|
||||
const props = withDefaults(defineProps<{
|
||||
@@ -365,22 +365,12 @@ const uploadSingleFile = async (file: File): Promise<string | null> => {
|
||||
}
|
||||
formData.append('storageType', 'local')
|
||||
|
||||
const token = localStorage.getItem('token')
|
||||
const response = await fetch(`${API_BASE}/admin/attachments/upload`, {
|
||||
const result = await parseApiResponse<{ fileUrl: string }>(await authFetch(`${API_BASE}/admin/attachments/upload`, {
|
||||
method: 'POST',
|
||||
headers: {
|
||||
...(token ? { Authorization: `Bearer ${token}` } : {})
|
||||
},
|
||||
headers: {},
|
||||
body: formData
|
||||
})
|
||||
|
||||
if (!response.ok) {
|
||||
const errorData = await response.json()
|
||||
throw new Error(errorData.message || '上传失败')
|
||||
}
|
||||
|
||||
const data = await response.json()
|
||||
return data.result.fileUrl
|
||||
}))
|
||||
return result.fileUrl
|
||||
} catch (err: any) {
|
||||
console.error('Upload error:', err)
|
||||
throw err
|
||||
|
||||
230
client/src/components/admin/PostHistoryModal.vue
Normal file
230
client/src/components/admin/PostHistoryModal.vue
Normal file
@@ -0,0 +1,230 @@
|
||||
<template>
|
||||
<Teleport to="body">
|
||||
<div
|
||||
v-if="isOpen"
|
||||
class="fixed inset-0 z-[9998] flex items-center justify-center bg-black/60 backdrop-blur-sm p-4"
|
||||
@click.self="emit('close')"
|
||||
>
|
||||
<div class="w-full max-w-4xl max-h-[85vh] bg-[#121214] border border-white/10 rounded-xl shadow-2xl flex flex-col overflow-hidden">
|
||||
<div class="flex items-center justify-between px-6 py-4 border-b border-white/10 shrink-0">
|
||||
<div>
|
||||
<h3 class="text-lg font-medium text-white">历史版本</h3>
|
||||
<p class="text-xs text-art-muted mt-1">每次保存后生成新版本,可查看、对比或恢复</p>
|
||||
</div>
|
||||
<button type="button" class="text-art-muted hover:text-white" @click="emit('close')">✕</button>
|
||||
</div>
|
||||
|
||||
<div class="flex-1 overflow-hidden flex min-h-0">
|
||||
<!-- Version list -->
|
||||
<div class="w-72 border-r border-white/10 overflow-y-auto custom-scrollbar shrink-0">
|
||||
<div v-if="loading" class="p-6 text-center text-art-muted text-sm">加载中...</div>
|
||||
<div v-else-if="historyList.length === 0" class="p-6 text-center text-art-muted text-sm">暂无历史版本</div>
|
||||
<button
|
||||
v-for="item in historyList"
|
||||
:key="item.version"
|
||||
type="button"
|
||||
class="w-full text-left px-4 py-3 border-b border-white/5 hover:bg-white/5 transition-colors"
|
||||
:class="{ 'bg-art-accent/10 border-l-2 border-l-art-accent': selectedVersions.includes(item.version) }"
|
||||
@click="toggleVersionSelect(item.version)"
|
||||
>
|
||||
<div class="flex items-center justify-between gap-2">
|
||||
<span class="text-sm text-white font-medium">v{{ item.version }}</span>
|
||||
<span class="text-xs text-art-muted">{{ item.modifiedAt }}</span>
|
||||
</div>
|
||||
<p class="text-xs text-art-muted mt-1 truncate">{{ item.title }}</p>
|
||||
</button>
|
||||
</div>
|
||||
|
||||
<!-- Detail / diff panel -->
|
||||
<div class="flex-1 overflow-y-auto custom-scrollbar p-6">
|
||||
<div v-if="viewMode === 'list'" class="text-sm text-art-muted">
|
||||
<p>点击版本可勾选(最多 2 个)进行对比,或点击下方操作。</p>
|
||||
<div class="mt-4 flex flex-wrap gap-2">
|
||||
<button
|
||||
type="button"
|
||||
class="admin-btn-secondary text-xs"
|
||||
:disabled="selectedVersions.length !== 1"
|
||||
@click="viewVersion(selectedVersions[0])"
|
||||
>
|
||||
查看选中版本
|
||||
</button>
|
||||
<button
|
||||
type="button"
|
||||
class="admin-btn-secondary text-xs"
|
||||
:disabled="selectedVersions.length !== 2"
|
||||
@click="compareVersions"
|
||||
>
|
||||
对比选中版本
|
||||
</button>
|
||||
<button
|
||||
type="button"
|
||||
class="admin-btn-primary text-xs"
|
||||
:disabled="selectedVersions.length !== 1"
|
||||
@click="restoreVersion(selectedVersions[0])"
|
||||
>
|
||||
恢复选中版本
|
||||
</button>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<div v-else-if="viewMode === 'preview' && previewData">
|
||||
<div class="flex items-center justify-between mb-4">
|
||||
<h4 class="text-white font-medium">版本 v{{ previewData.version }}</h4>
|
||||
<button type="button" class="text-xs text-art-accent" @click="viewMode = 'list'">返回列表</button>
|
||||
</div>
|
||||
<div class="space-y-3 text-sm">
|
||||
<div><span class="text-art-muted">标题:</span><span class="text-white">{{ previewData.title }}</span></div>
|
||||
<div><span class="text-art-muted">摘要:</span><span class="text-white">{{ previewData.excerpt || '—' }}</span></div>
|
||||
<pre class="bg-black/30 rounded-lg p-4 text-xs text-white/80 whitespace-pre-wrap max-h-96 overflow-y-auto">{{ previewData.content || '—' }}</pre>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<div v-else-if="viewMode === 'diff' && diffData">
|
||||
<div class="flex items-center justify-between mb-4">
|
||||
<h4 class="text-white font-medium">v{{ diffData.fromVersion }} → v{{ diffData.toVersion }}</h4>
|
||||
<button type="button" class="text-xs text-art-accent" @click="viewMode = 'list'">返回列表</button>
|
||||
</div>
|
||||
<div class="space-y-4">
|
||||
<div
|
||||
v-for="(field, key) in diffData.fields"
|
||||
:key="key"
|
||||
class="rounded-lg border p-4"
|
||||
:class="field.changed ? 'border-art-accent/30 bg-art-accent/5' : 'border-white/5 bg-white/[0.02]'"
|
||||
>
|
||||
<div class="text-xs uppercase tracking-wider text-art-muted mb-2">{{ key }}</div>
|
||||
<template v-if="field.changed">
|
||||
<div class="grid md:grid-cols-2 gap-3 text-xs">
|
||||
<div>
|
||||
<div class="text-art-muted mb-1">旧版</div>
|
||||
<pre class="whitespace-pre-wrap bg-black/30 rounded p-2 text-white/70 max-h-40 overflow-y-auto">{{ field.from || '—' }}</pre>
|
||||
</div>
|
||||
<div>
|
||||
<div class="text-art-muted mb-1">新版</div>
|
||||
<pre class="whitespace-pre-wrap bg-black/30 rounded p-2 text-white/70 max-h-40 overflow-y-auto">{{ field.to || '—' }}</pre>
|
||||
</div>
|
||||
</div>
|
||||
<pre v-if="field.diff" class="mt-2 text-xs text-art-accent/80 whitespace-pre-wrap">{{ field.diff }}</pre>
|
||||
</template>
|
||||
<div v-else class="text-xs text-art-muted">无变化</div>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
</Teleport>
|
||||
</template>
|
||||
|
||||
<script setup lang="ts">
|
||||
import { ref, watch } from 'vue'
|
||||
import {
|
||||
getPostHistory,
|
||||
getPostHistoryByVersion,
|
||||
getPostHistoryDiff,
|
||||
restorePostHistory,
|
||||
type PostHistory,
|
||||
type PostHistoryDiff
|
||||
} from '../../services/api'
|
||||
import { useToast } from '../../composables/useToast'
|
||||
|
||||
const props = defineProps<{
|
||||
isOpen: boolean
|
||||
postId: number | string
|
||||
}>()
|
||||
|
||||
const emit = defineEmits<{
|
||||
close: []
|
||||
restored: []
|
||||
}>()
|
||||
|
||||
const toast = useToast()
|
||||
const loading = ref(false)
|
||||
const historyList = ref<PostHistory[]>([])
|
||||
const selectedVersions = ref<number[]>([])
|
||||
const viewMode = ref<'list' | 'preview' | 'diff'>('list')
|
||||
const previewData = ref<PostHistory | null>(null)
|
||||
const diffData = ref<PostHistoryDiff | null>(null)
|
||||
|
||||
const loadHistory = async () => {
|
||||
if (!props.postId) return
|
||||
loading.value = true
|
||||
try {
|
||||
historyList.value = await getPostHistory(props.postId)
|
||||
historyList.value.sort((a, b) => b.version - a.version)
|
||||
} catch (error: any) {
|
||||
toast.showToast(error.message || '加载历史版本失败', 'error')
|
||||
} finally {
|
||||
loading.value = false
|
||||
}
|
||||
}
|
||||
|
||||
const toggleVersionSelect = (version: number) => {
|
||||
const idx = selectedVersions.value.indexOf(version)
|
||||
if (idx >= 0) {
|
||||
selectedVersions.value.splice(idx, 1)
|
||||
return
|
||||
}
|
||||
if (selectedVersions.value.length >= 2) {
|
||||
selectedVersions.value.shift()
|
||||
}
|
||||
selectedVersions.value.push(version)
|
||||
}
|
||||
|
||||
const viewVersion = async (version?: number) => {
|
||||
if (!version) return
|
||||
try {
|
||||
previewData.value = await getPostHistoryByVersion(props.postId, version)
|
||||
viewMode.value = 'preview'
|
||||
} catch (error: any) {
|
||||
toast.showToast(error.message || '加载版本详情失败', 'error')
|
||||
}
|
||||
}
|
||||
|
||||
const compareVersions = async () => {
|
||||
if (selectedVersions.value.length !== 2) return
|
||||
const [a, b] = [...selectedVersions.value].sort((x, y) => x - y)
|
||||
try {
|
||||
diffData.value = await getPostHistoryDiff(props.postId, a, b)
|
||||
viewMode.value = 'diff'
|
||||
} catch (error: any) {
|
||||
toast.showToast(error.message || '对比失败', 'error')
|
||||
}
|
||||
}
|
||||
|
||||
const restoreVersion = async (version?: number) => {
|
||||
if (!version) return
|
||||
if (!confirm(`确定将文章恢复为版本 v${version} 吗?当前内容会先保存为新版本。`)) return
|
||||
try {
|
||||
await restorePostHistory(props.postId, version)
|
||||
toast.showToast('版本恢复成功', 'success')
|
||||
emit('restored')
|
||||
emit('close')
|
||||
} catch (error: any) {
|
||||
toast.showToast(error.message || '恢复失败', 'error')
|
||||
}
|
||||
}
|
||||
|
||||
watch(
|
||||
() => props.isOpen,
|
||||
(open) => {
|
||||
if (open) {
|
||||
selectedVersions.value = []
|
||||
viewMode.value = 'list'
|
||||
previewData.value = null
|
||||
diffData.value = null
|
||||
loadHistory()
|
||||
}
|
||||
}
|
||||
)
|
||||
</script>
|
||||
|
||||
<style scoped>
|
||||
.custom-scrollbar::-webkit-scrollbar {
|
||||
width: 4px;
|
||||
}
|
||||
.custom-scrollbar::-webkit-scrollbar-thumb {
|
||||
background: rgba(255, 255, 255, 0.1);
|
||||
border-radius: 2px;
|
||||
}
|
||||
</style>
|
||||
26
client/src/components/admin/SessionExpiredModal.vue
Normal file
26
client/src/components/admin/SessionExpiredModal.vue
Normal file
@@ -0,0 +1,26 @@
|
||||
<template>
|
||||
<Teleport to="body">
|
||||
<div
|
||||
v-if="sessionExpired"
|
||||
class="fixed inset-0 z-[9999] flex items-center justify-center bg-black/60 backdrop-blur-sm"
|
||||
>
|
||||
<div class="w-full max-w-sm mx-4 bg-[#121214] border border-white/10 rounded-xl p-6 shadow-2xl">
|
||||
<h3 class="text-lg font-medium text-white mb-2">登录已过期</h3>
|
||||
<p class="text-sm text-art-muted mb-6">您的登录状态已失效,请重新登录。</p>
|
||||
<button
|
||||
type="button"
|
||||
class="w-full admin-btn-primary py-2.5"
|
||||
@click="confirmSessionExpired"
|
||||
>
|
||||
确认
|
||||
</button>
|
||||
</div>
|
||||
</div>
|
||||
</Teleport>
|
||||
</template>
|
||||
|
||||
<script setup lang="ts">
|
||||
import { useAuth } from '../../composables/useAuth'
|
||||
|
||||
const { sessionExpired, confirmSessionExpired } = useAuth()
|
||||
</script>
|
||||
111
client/src/composables/useAuth.ts
Normal file
111
client/src/composables/useAuth.ts
Normal file
@@ -0,0 +1,111 @@
|
||||
import { ref } from 'vue'
|
||||
import router from '../router'
|
||||
|
||||
const TOKEN_KEY = 'token'
|
||||
const USER_KEY = 'user'
|
||||
const EXPIRE_KEY = 'tokenExpireAt'
|
||||
|
||||
const sessionExpired = ref(false)
|
||||
let sessionExpiredHandled = false
|
||||
let expiryTimer: ReturnType<typeof setTimeout> | null = null
|
||||
|
||||
export function useAuth() {
|
||||
const getToken = () => localStorage.getItem(TOKEN_KEY)
|
||||
|
||||
const getTokenExpireAt = (): number => {
|
||||
const raw = localStorage.getItem(EXPIRE_KEY)
|
||||
return raw ? Number(raw) : 0
|
||||
}
|
||||
|
||||
const isAuthenticated = (): boolean => {
|
||||
const token = getToken()
|
||||
if (!token) return false
|
||||
|
||||
const expireAt = getTokenExpireAt()
|
||||
if (expireAt > 0 && Date.now() >= expireAt) {
|
||||
return false
|
||||
}
|
||||
|
||||
return true
|
||||
}
|
||||
|
||||
const login = (token: string, user: unknown, expireUnixSeconds: number) => {
|
||||
localStorage.setItem(TOKEN_KEY, token)
|
||||
localStorage.setItem(USER_KEY, JSON.stringify(user))
|
||||
localStorage.setItem(EXPIRE_KEY, String(expireUnixSeconds * 1000))
|
||||
sessionExpiredHandled = false
|
||||
sessionExpired.value = false
|
||||
scheduleExpiryCheck()
|
||||
}
|
||||
|
||||
const logout = (showToast?: (msg: string, type: 'success' | 'error') => void) => {
|
||||
clearExpiryTimer()
|
||||
localStorage.removeItem(TOKEN_KEY)
|
||||
localStorage.removeItem(USER_KEY)
|
||||
localStorage.removeItem(EXPIRE_KEY)
|
||||
sessionExpiredHandled = false
|
||||
sessionExpired.value = false
|
||||
|
||||
if (router.currentRoute.value.path !== '/login') {
|
||||
router.push('/login')
|
||||
}
|
||||
|
||||
if (showToast) {
|
||||
// noop by default for expiry flow
|
||||
}
|
||||
}
|
||||
|
||||
const clearExpiryTimer = () => {
|
||||
if (expiryTimer) {
|
||||
clearTimeout(expiryTimer)
|
||||
expiryTimer = null
|
||||
}
|
||||
}
|
||||
|
||||
const scheduleExpiryCheck = () => {
|
||||
clearExpiryTimer()
|
||||
const expireAt = getTokenExpireAt()
|
||||
if (!expireAt) return
|
||||
|
||||
const delay = expireAt - Date.now()
|
||||
if (delay <= 0) {
|
||||
handleSessionExpired()
|
||||
return
|
||||
}
|
||||
|
||||
expiryTimer = setTimeout(() => {
|
||||
handleSessionExpired()
|
||||
}, delay)
|
||||
}
|
||||
|
||||
const handleSessionExpired = () => {
|
||||
if (sessionExpiredHandled) return
|
||||
sessionExpiredHandled = true
|
||||
sessionExpired.value = true
|
||||
}
|
||||
|
||||
const confirmSessionExpired = () => {
|
||||
logout()
|
||||
}
|
||||
|
||||
const getUser = () => {
|
||||
try {
|
||||
return JSON.parse(localStorage.getItem(USER_KEY) || '{}')
|
||||
} catch {
|
||||
return {}
|
||||
}
|
||||
}
|
||||
|
||||
return {
|
||||
sessionExpired,
|
||||
getToken,
|
||||
getTokenExpireAt,
|
||||
isAuthenticated,
|
||||
login,
|
||||
logout,
|
||||
handleSessionExpired,
|
||||
confirmSessionExpired,
|
||||
scheduleExpiryCheck,
|
||||
getUser,
|
||||
}
|
||||
}
|
||||
43
client/src/composables/useSearchHistory.ts
Normal file
43
client/src/composables/useSearchHistory.ts
Normal file
@@ -0,0 +1,43 @@
|
||||
export const SEARCH_HISTORY_KEY = 'blog_search_history'
|
||||
const MAX_HISTORY = 10
|
||||
|
||||
export function useSearchHistory() {
|
||||
const readHistory = (): string[] => {
|
||||
try {
|
||||
const raw = localStorage.getItem(SEARCH_HISTORY_KEY)
|
||||
if (!raw) return []
|
||||
const parsed = JSON.parse(raw)
|
||||
return Array.isArray(parsed) ? parsed.filter((item) => typeof item === 'string') : []
|
||||
} catch {
|
||||
return []
|
||||
}
|
||||
}
|
||||
|
||||
const writeHistory = (items: string[]) => {
|
||||
localStorage.setItem(SEARCH_HISTORY_KEY, JSON.stringify(items.slice(0, MAX_HISTORY)))
|
||||
}
|
||||
|
||||
const getHistory = () => readHistory()
|
||||
|
||||
const addHistory = (keyword: string) => {
|
||||
const trimmed = keyword.trim()
|
||||
if (!trimmed) return
|
||||
const next = [trimmed, ...readHistory().filter((item) => item !== trimmed)].slice(0, MAX_HISTORY)
|
||||
writeHistory(next)
|
||||
}
|
||||
|
||||
const removeHistory = (keyword: string) => {
|
||||
writeHistory(readHistory().filter((item) => item !== keyword))
|
||||
}
|
||||
|
||||
const clearHistory = () => {
|
||||
localStorage.removeItem(SEARCH_HISTORY_KEY)
|
||||
}
|
||||
|
||||
return {
|
||||
getHistory,
|
||||
addHistory,
|
||||
removeHistory,
|
||||
clearHistory,
|
||||
}
|
||||
}
|
||||
@@ -10,10 +10,21 @@
|
||||
<input
|
||||
type="text"
|
||||
v-model="searchQuery"
|
||||
@focus="handleSearchFocus"
|
||||
@blur="handleSearchBlur"
|
||||
@keyup.enter="handleSearch"
|
||||
placeholder="搜索文章标题或内容..."
|
||||
class="w-full bg-white/5 border border-white/10 rounded-full px-6 py-3 text-white placeholder-white/30 focus:outline-none focus:border-art-accent transition-colors"
|
||||
/>
|
||||
<SearchSuggestDropdown
|
||||
:visible="showSearchSuggest"
|
||||
:history="searchHistory"
|
||||
:hot-keywords="hotKeywords"
|
||||
:loading-hot="loadingHot"
|
||||
@select="selectSuggestKeyword"
|
||||
@remove-history="removeSearchHistoryItem"
|
||||
@clear-history="clearSearchHistory"
|
||||
/>
|
||||
<button
|
||||
v-if="searchQuery"
|
||||
@click="clearSearch"
|
||||
@@ -129,9 +140,13 @@
|
||||
|
||||
<script setup lang="ts">
|
||||
import { ref, onMounted, nextTick, computed, onBeforeUnmount } from 'vue'
|
||||
import { fetchPosts, fetchCategories, fetchTags, getPublicSettings, Post, Category, Tag, PaginationResponse } from '../services/api'
|
||||
import { fetchPosts, fetchCategories, fetchTags, getPublicSettings, getHotSearches, Post, Category, Tag, PaginationResponse, HotSearchKeyword } from '../services/api'
|
||||
import { useScrollAnimation } from '../composables/useScrollAnimation'
|
||||
import { useSearchHistory } from '../composables/useSearchHistory'
|
||||
import CustomSelect from '../components/CustomSelect.vue'
|
||||
import SearchSuggestDropdown from '../components/SearchSuggestDropdown.vue'
|
||||
|
||||
const { getHistory, addHistory, removeHistory, clearHistory } = useSearchHistory()
|
||||
|
||||
const blogPosts = ref<Post[]>([])
|
||||
const loading = ref(false)
|
||||
@@ -142,6 +157,11 @@ const selectedCategoryId = ref(0)
|
||||
const selectedTagId = ref(0)
|
||||
const categories = ref<Category[]>([])
|
||||
const tags = ref<Tag[]>([])
|
||||
const showSearchSuggest = ref(false)
|
||||
const searchHistory = ref<string[]>([])
|
||||
const hotKeywords = ref<HotSearchKeyword[]>([])
|
||||
const loadingHot = ref(false)
|
||||
let blurTimer: ReturnType<typeof setTimeout> | null = null
|
||||
|
||||
// 分页相关状态
|
||||
const currentPage = ref(1)
|
||||
@@ -262,9 +282,54 @@ const removeScrollListener = () => {
|
||||
const handleSearch = () => {
|
||||
if (!searchQuery.value.trim() && !isSearching.value) return
|
||||
isSearching.value = !!searchQuery.value.trim()
|
||||
if (searchQuery.value.trim()) {
|
||||
addHistory(searchQuery.value.trim())
|
||||
searchHistory.value = getHistory()
|
||||
}
|
||||
showSearchSuggest.value = false
|
||||
fetchBlogPosts(true)
|
||||
}
|
||||
|
||||
const handleSearchFocus = async () => {
|
||||
if (blurTimer) {
|
||||
clearTimeout(blurTimer)
|
||||
blurTimer = null
|
||||
}
|
||||
searchHistory.value = getHistory()
|
||||
showSearchSuggest.value = true
|
||||
if (hotKeywords.value.length === 0 && !loadingHot.value) {
|
||||
loadingHot.value = true
|
||||
try {
|
||||
hotKeywords.value = await getHotSearches()
|
||||
} catch (err) {
|
||||
console.error('Failed to load hot searches:', err)
|
||||
} finally {
|
||||
loadingHot.value = false
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
const handleSearchBlur = () => {
|
||||
blurTimer = setTimeout(() => {
|
||||
showSearchSuggest.value = false
|
||||
}, 150)
|
||||
}
|
||||
|
||||
const selectSuggestKeyword = (keyword: string) => {
|
||||
searchQuery.value = keyword
|
||||
handleSearch()
|
||||
}
|
||||
|
||||
const removeSearchHistoryItem = (keyword: string) => {
|
||||
removeHistory(keyword)
|
||||
searchHistory.value = getHistory()
|
||||
}
|
||||
|
||||
const clearSearchHistory = () => {
|
||||
clearHistory()
|
||||
searchHistory.value = []
|
||||
}
|
||||
|
||||
const clearSearch = () => {
|
||||
searchQuery.value = ''
|
||||
isSearching.value = false
|
||||
|
||||
@@ -106,10 +106,12 @@
|
||||
import { ref } from 'vue'
|
||||
import { useRouter } from 'vue-router'
|
||||
import { useToast } from '../composables/useToast'
|
||||
import { useAuth } from '../composables/useAuth'
|
||||
import { login } from '../services/api'
|
||||
|
||||
const router = useRouter()
|
||||
const toast = useToast()
|
||||
const { login: saveAuth } = useAuth()
|
||||
|
||||
const form = ref({
|
||||
username: '',
|
||||
@@ -125,9 +127,7 @@ const handleLogin = async () => {
|
||||
|
||||
try {
|
||||
const response = await login(form.value)
|
||||
// 保存token到本地存储
|
||||
localStorage.setItem('token', response.token)
|
||||
localStorage.setItem('user', JSON.stringify(response.user))
|
||||
saveAuth(response.token, response.user, response.expire)
|
||||
toast.showToast('欢迎回来,管理员', 'success')
|
||||
// 登录成功后重定向到管理后台
|
||||
router.push('/admin')
|
||||
|
||||
@@ -53,6 +53,21 @@
|
||||
<div v-if="attachment.fileType === 'image'" class="aspect-square mb-2 rounded overflow-hidden bg-white/5">
|
||||
<img :src="attachment.fileUrl" :alt="attachment.originalName" class="w-full h-full object-cover" />
|
||||
</div>
|
||||
<div v-else-if="attachment.fileType === 'video'" class="aspect-square mb-2 rounded overflow-hidden bg-black/40 relative">
|
||||
<video
|
||||
:src="attachment.fileUrl"
|
||||
muted
|
||||
preload="metadata"
|
||||
class="w-full h-full object-cover"
|
||||
/>
|
||||
<div class="absolute inset-0 flex items-center justify-center bg-black/30 pointer-events-none">
|
||||
<div class="w-10 h-10 rounded-full bg-white/20 backdrop-blur-sm flex items-center justify-center border border-white/30">
|
||||
<svg xmlns="http://www.w3.org/2000/svg" width="18" height="18" viewBox="0 0 24 24" fill="white">
|
||||
<polygon points="8 5 19 12 8 19 8 5"></polygon>
|
||||
</svg>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
<div v-else class="aspect-square mb-2 rounded bg-white/5 flex items-center justify-center">
|
||||
<i data-lucide="file" class="w-12 h-12 text-art-muted"></i>
|
||||
</div>
|
||||
@@ -135,7 +150,7 @@ import { ref, onMounted, computed } from 'vue'
|
||||
import { useToast } from '../../composables/useToast'
|
||||
import CustomSelect from '../../components/CustomSelect.vue'
|
||||
import AttachmentDetailModal from '../../components/admin/AttachmentDetailModal.vue'
|
||||
import { updateAttachment, type Attachment } from '../../services/api'
|
||||
import { updateAttachment, type Attachment, API_BASE, authFetch, parseApiResponse } from '../../services/api'
|
||||
|
||||
const toast = useToast()
|
||||
|
||||
@@ -191,14 +206,6 @@ const uploadCategoryOptions = computed(() => {
|
||||
})
|
||||
|
||||
|
||||
const API_BASE = '/api'
|
||||
const getAuthHeaders = () => {
|
||||
const token = localStorage.getItem('token')
|
||||
return {
|
||||
...(token ? { Authorization: `Bearer ${token}` } : {})
|
||||
}
|
||||
}
|
||||
|
||||
const loadAttachments = async () => {
|
||||
loading.value = true
|
||||
try {
|
||||
@@ -210,14 +217,8 @@ const loadAttachments = async () => {
|
||||
url += `&fileType=${filterFileType.value}`
|
||||
}
|
||||
|
||||
const response = await fetch(url, {
|
||||
headers: getAuthHeaders()
|
||||
})
|
||||
|
||||
if (!response.ok) throw new Error('获取附件列表失败')
|
||||
|
||||
const data = await response.json()
|
||||
attachments.value = data.result.list || []
|
||||
const data = await parseApiResponse<{ list: Attachment[] }>(await authFetch(url))
|
||||
attachments.value = data?.list || []
|
||||
} catch (err: any) {
|
||||
toast.showToast(err.message || '加载失败', 'error')
|
||||
} finally {
|
||||
@@ -227,14 +228,8 @@ const loadAttachments = async () => {
|
||||
|
||||
const loadCategories = async () => {
|
||||
try {
|
||||
const response = await fetch(`${API_BASE}/admin/attachment-categories`, {
|
||||
headers: getAuthHeaders()
|
||||
})
|
||||
|
||||
if (!response.ok) throw new Error('获取分类失败')
|
||||
|
||||
const data = await response.json()
|
||||
categories.value = data.result || []
|
||||
const data = await parseApiResponse<Category[]>(await authFetch(`${API_BASE}/admin/attachment-categories`))
|
||||
categories.value = data || []
|
||||
} catch (err) {
|
||||
console.error('Failed to load categories:', err)
|
||||
}
|
||||
@@ -259,16 +254,11 @@ const uploadFile = async () => {
|
||||
}
|
||||
formData.append('storageType', 'local')
|
||||
|
||||
const response = await fetch(`${API_BASE}/admin/attachments/upload`, {
|
||||
await parseApiResponse(await authFetch(`${API_BASE}/admin/attachments/upload`, {
|
||||
method: 'POST',
|
||||
headers: getAuthHeaders(),
|
||||
headers: {},
|
||||
body: formData
|
||||
})
|
||||
|
||||
if (!response.ok) {
|
||||
const errorData = await response.json()
|
||||
throw new Error(errorData.message || '上传失败')
|
||||
}
|
||||
}))
|
||||
|
||||
toast.showToast('上传成功', 'success')
|
||||
showUploadModal.value = false
|
||||
@@ -286,12 +276,9 @@ const deleteAttachment = async (id: number) => {
|
||||
if (!confirm('确定要删除这个附件吗?')) return
|
||||
|
||||
try {
|
||||
const response = await fetch(`${API_BASE}/admin/attachments/${id}`, {
|
||||
method: 'DELETE',
|
||||
headers: getAuthHeaders()
|
||||
})
|
||||
|
||||
if (!response.ok) throw new Error('删除失败')
|
||||
await parseApiResponse(await authFetch(`${API_BASE}/admin/attachments/${id}`, {
|
||||
method: 'DELETE'
|
||||
}))
|
||||
|
||||
toast.showToast('删除成功', 'success')
|
||||
loadAttachments()
|
||||
|
||||
@@ -64,7 +64,7 @@
|
||||
|
||||
<script setup lang="ts">
|
||||
import { ref, onMounted } from 'vue'
|
||||
import { API_BASE, getAuthHeaders, type EmailSuffix } from '../../services/api'
|
||||
import { API_BASE, authFetchJson, getAuthHeaders, type EmailSuffix } from '../../services/api'
|
||||
import { useToast } from '../../composables/useToast'
|
||||
|
||||
const toast = useToast()
|
||||
@@ -74,13 +74,9 @@ const newSortOrder = ref(0)
|
||||
|
||||
const fetchSuffixes = async () => {
|
||||
try {
|
||||
const response = await fetch(`${API_BASE}/admin/email-suffixes`, {
|
||||
suffixes.value = await authFetchJson<EmailSuffix[]>(`${API_BASE}/admin/email-suffixes`, {
|
||||
headers: getAuthHeaders()
|
||||
})
|
||||
if (response.ok) {
|
||||
const data = await response.json()
|
||||
suffixes.value = data.result || []
|
||||
}
|
||||
}) || []
|
||||
} catch (error) {
|
||||
console.error('Failed to fetch suffixes:', error)
|
||||
}
|
||||
@@ -93,7 +89,7 @@ const handleAdd = async () => {
|
||||
}
|
||||
|
||||
try {
|
||||
const response = await fetch(`${API_BASE}/admin/email-suffixes`, {
|
||||
await authFetchJson(`${API_BASE}/admin/email-suffixes`, {
|
||||
method: 'POST',
|
||||
headers: getAuthHeaders(),
|
||||
body: JSON.stringify({
|
||||
@@ -102,19 +98,13 @@ const handleAdd = async () => {
|
||||
sortOrder: newSortOrder.value
|
||||
})
|
||||
})
|
||||
|
||||
if (response.ok) {
|
||||
toast.success('添加成功')
|
||||
newSuffix.value = ''
|
||||
newSortOrder.value = 0
|
||||
fetchSuffixes()
|
||||
} else {
|
||||
const errorData = await response.json()
|
||||
toast.error(errorData.message || '添加失败')
|
||||
}
|
||||
} catch (error) {
|
||||
toast.success('添加成功')
|
||||
newSuffix.value = ''
|
||||
newSortOrder.value = 0
|
||||
fetchSuffixes()
|
||||
} catch (error: any) {
|
||||
console.error(error)
|
||||
toast.error('添加失败')
|
||||
toast.error(error.message || '添加失败')
|
||||
}
|
||||
}
|
||||
|
||||
@@ -122,21 +112,15 @@ const handleDelete = async (id: number) => {
|
||||
if (!confirm('确定删除该后缀吗?')) return
|
||||
|
||||
try {
|
||||
const response = await fetch(`${API_BASE}/admin/email-suffixes/${id}`, {
|
||||
await authFetchJson(`${API_BASE}/admin/email-suffixes/${id}`, {
|
||||
method: 'DELETE',
|
||||
headers: getAuthHeaders()
|
||||
})
|
||||
|
||||
if (response.ok) {
|
||||
toast.success('删除成功')
|
||||
fetchSuffixes()
|
||||
} else {
|
||||
const errorData = await response.json()
|
||||
toast.error(errorData.message || '删除失败')
|
||||
}
|
||||
} catch (error) {
|
||||
toast.success('删除成功')
|
||||
fetchSuffixes()
|
||||
} catch (error: any) {
|
||||
console.error(error)
|
||||
toast.error('删除失败')
|
||||
toast.error(error.message || '删除失败')
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
@@ -74,21 +74,15 @@
|
||||
|
||||
<script setup lang="ts">
|
||||
import { ref, onMounted } from 'vue'
|
||||
import { API_BASE, getAuthHeaders, type Inquiry } from '../../services/api'
|
||||
import { API_BASE, authFetchJson, fetchInquiries, getAuthHeaders, type Inquiry } from '../../services/api'
|
||||
import { useToast } from '../../composables/useToast'
|
||||
|
||||
const toast = useToast()
|
||||
const inquiries = ref<Inquiry[]>([])
|
||||
|
||||
const fetchInquiries = async () => {
|
||||
const fetchInquiriesList = async () => {
|
||||
try {
|
||||
const response = await fetch(`${API_BASE}/admin/inquiries`, {
|
||||
headers: getAuthHeaders()
|
||||
})
|
||||
if (response.ok) {
|
||||
const data = await response.json()
|
||||
inquiries.value = data.result || []
|
||||
}
|
||||
inquiries.value = await fetchInquiries()
|
||||
} catch (error) {
|
||||
console.error('Failed to fetch inquiries:', error)
|
||||
toast.error('获取咨询列表失败')
|
||||
@@ -97,22 +91,16 @@ const fetchInquiries = async () => {
|
||||
|
||||
const updateStatus = async (id: number, status: number) => {
|
||||
try {
|
||||
const response = await fetch(`${API_BASE}/admin/inquiries/${id}/status`, {
|
||||
await authFetchJson(`${API_BASE}/admin/inquiries/${id}/status`, {
|
||||
method: 'PUT',
|
||||
headers: getAuthHeaders(),
|
||||
body: JSON.stringify({ status })
|
||||
})
|
||||
|
||||
if (response.ok) {
|
||||
toast.success('状态更新成功')
|
||||
fetchInquiries()
|
||||
} else {
|
||||
const errorData = await response.json()
|
||||
toast.error(errorData.message || '更新失败')
|
||||
}
|
||||
} catch (error) {
|
||||
toast.success('状态更新成功')
|
||||
fetchInquiriesList()
|
||||
} catch (error: any) {
|
||||
console.error(error)
|
||||
toast.error('更新失败')
|
||||
toast.error(error.message || '更新失败')
|
||||
}
|
||||
}
|
||||
|
||||
@@ -144,7 +132,7 @@ const getStatusClass = (status?: number) => {
|
||||
}
|
||||
|
||||
onMounted(() => {
|
||||
fetchInquiries()
|
||||
fetchInquiriesList()
|
||||
})
|
||||
</script>
|
||||
|
||||
|
||||
@@ -17,6 +17,15 @@
|
||||
</button>
|
||||
</div>
|
||||
<div class="flex gap-3">
|
||||
<button
|
||||
v-if="isEditing"
|
||||
type="button"
|
||||
class="admin-btn-secondary"
|
||||
@click="openHistoryModal"
|
||||
title="查看历史版本"
|
||||
>
|
||||
📜 历史版本
|
||||
</button>
|
||||
<button
|
||||
v-if="isEditing"
|
||||
type="button"
|
||||
@@ -40,14 +49,17 @@
|
||||
<div class="flex-1 flex flex-col min-w-0 transition-all duration-300 ease-in-out h-full">
|
||||
<div
|
||||
class="admin-card flex-1 flex flex-col overflow-hidden border border-white/10 focus-within:border-art-accent/50 transition-colors"
|
||||
@paste="handlePaste"
|
||||
@paste="handleVideoPaste"
|
||||
>
|
||||
<MdEditor
|
||||
ref="editorRef"
|
||||
v-model="form.content"
|
||||
theme="dark"
|
||||
:preview="false"
|
||||
placeholder="开始创作..."
|
||||
class="custom-md-editor flex-1"
|
||||
@onUploadImg="handleUploadImg"
|
||||
@onDrop="handleEditorDrop"
|
||||
/>
|
||||
</div>
|
||||
</div>
|
||||
@@ -251,6 +263,13 @@
|
||||
</form>
|
||||
|
||||
<!-- Access Log Modal -->
|
||||
<PostHistoryModal
|
||||
v-if="isEditing"
|
||||
:is-open="isHistoryModalOpen"
|
||||
:post-id="route.params.id as string"
|
||||
@close="isHistoryModalOpen = false"
|
||||
@restored="loadData"
|
||||
/>
|
||||
<AccessLogModal
|
||||
v-if="isEditing"
|
||||
v-model:isOpen="isAccessLogModalOpen"
|
||||
@@ -265,6 +284,7 @@ import { ref, reactive, onMounted, computed } from 'vue'
|
||||
import { useRouter, useRoute } from 'vue-router'
|
||||
// 引入 md-editor-v3
|
||||
import { MdEditor } from 'md-editor-v3'
|
||||
import type { ExposeParam, UploadImgCallBack } from 'md-editor-v3'
|
||||
import 'md-editor-v3/lib/style.css'
|
||||
|
||||
import { useToast } from '../../composables/useToast'
|
||||
@@ -280,8 +300,10 @@ import {
|
||||
createTag as createTagApi,
|
||||
Tag
|
||||
} from '../../services/api'
|
||||
import { authFetch, parseApiResponse } from '../../services/api'
|
||||
import CustomSelect from '../../components/CustomSelect.vue'
|
||||
import AccessLogModal from '../../components/admin/AccessLogModal.vue'
|
||||
import PostHistoryModal from '../../components/admin/PostHistoryModal.vue'
|
||||
import ImageUpload from '../../components/admin/ImageUpload.vue'
|
||||
|
||||
const router = useRouter()
|
||||
@@ -301,9 +323,13 @@ const errors = reactive<Record<string, string>>({})
|
||||
|
||||
// Access log modal state
|
||||
const isAccessLogModalOpen = ref(false)
|
||||
const isHistoryModalOpen = ref(false)
|
||||
const openAccessLogModal = () => {
|
||||
isAccessLogModalOpen.value = true
|
||||
}
|
||||
const openHistoryModal = () => {
|
||||
isHistoryModalOpen.value = true
|
||||
}
|
||||
|
||||
// Data sources
|
||||
const categories = ref<{value: number, label: string}[]>([])
|
||||
@@ -517,67 +543,96 @@ const handleCancel = () => {
|
||||
router.push('/admin/posts')
|
||||
}
|
||||
|
||||
// Handle paste event for image upload
|
||||
const handlePaste = async (e: ClipboardEvent) => {
|
||||
const editorRef = ref<ExposeParam>()
|
||||
|
||||
const uploadMediaFile = async (file: File): Promise<string | null> => {
|
||||
const formData = new FormData()
|
||||
formData.append('file', file)
|
||||
formData.append('categoryId', '1')
|
||||
formData.append('storageType', 'local')
|
||||
|
||||
const response = await authFetch('/api/admin/attachments/upload', {
|
||||
method: 'POST',
|
||||
headers: {},
|
||||
body: formData
|
||||
})
|
||||
|
||||
const result = await parseApiResponse<{ fileUrl: string }>(response)
|
||||
return result?.fileUrl ?? null
|
||||
}
|
||||
|
||||
const insertAtCursor = (text: string) => {
|
||||
editorRef.value?.insert?.(() => ({ targetValue: text }))
|
||||
}
|
||||
|
||||
const uploadAndInsertVideo = async (file: File) => {
|
||||
try {
|
||||
const url = await uploadMediaFile(file)
|
||||
if (!url) return
|
||||
insertAtCursor(`\n<video controls src="${url}" style="max-width:100%"></video>\n`)
|
||||
toast.showToast('视频上传成功', 'success')
|
||||
} catch (error: any) {
|
||||
console.error('上传视频失败:', error)
|
||||
toast.showToast(error.message || '上传视频失败', 'error')
|
||||
}
|
||||
}
|
||||
|
||||
const handleUploadImg = async (files: File[], callback: UploadImgCallBack) => {
|
||||
try {
|
||||
const uploadResults = await Promise.all(
|
||||
files.map(async (file) => {
|
||||
const url = await uploadMediaFile(file)
|
||||
return url ? { url, alt: file.name, title: file.name } : null
|
||||
})
|
||||
)
|
||||
const urls = uploadResults.filter((item): item is { url: string; alt: string; title: string } => item !== null)
|
||||
if (urls.length > 0) {
|
||||
callback(urls)
|
||||
toast.showToast('图片上传成功', 'success')
|
||||
}
|
||||
} catch (error: any) {
|
||||
console.error('上传图片失败:', error)
|
||||
toast.showToast(error.message || '上传图片失败', 'error')
|
||||
}
|
||||
}
|
||||
|
||||
const handleEditorDrop = async (e: DragEvent) => {
|
||||
const files = Array.from(e.dataTransfer?.files || [])
|
||||
const imageFiles = files.filter((f) => f.type.startsWith('image/'))
|
||||
const videoFiles = files.filter((f) => f.type.startsWith('video/'))
|
||||
if (imageFiles.length === 0 && videoFiles.length === 0) return
|
||||
|
||||
e.preventDefault()
|
||||
|
||||
if (imageFiles.length > 0) {
|
||||
await handleUploadImg(imageFiles, (urls) => {
|
||||
if (!Array.isArray(urls) || urls.length === 0) return
|
||||
urls.forEach((item) => {
|
||||
if (typeof item === 'string') {
|
||||
insertAtCursor(``)
|
||||
} else {
|
||||
insertAtCursor(``)
|
||||
}
|
||||
})
|
||||
})
|
||||
}
|
||||
|
||||
for (const file of videoFiles) {
|
||||
await uploadAndInsertVideo(file)
|
||||
}
|
||||
}
|
||||
|
||||
const handleVideoPaste = async (e: ClipboardEvent) => {
|
||||
const items = e.clipboardData?.items
|
||||
if (!items) return
|
||||
|
||||
// Check if any item is an image
|
||||
let hasImage = false
|
||||
for (let i = 0; i < items.length; i++) {
|
||||
if (items[i].type.startsWith('image/')) {
|
||||
hasImage = true
|
||||
break
|
||||
}
|
||||
}
|
||||
|
||||
if (!hasImage) return
|
||||
|
||||
// Prevent default paste behavior for images
|
||||
e.preventDefault()
|
||||
|
||||
for (let i = 0; i < items.length; i++) {
|
||||
const item = items[i]
|
||||
if (item.type.startsWith('image/')) {
|
||||
if (item.type.startsWith('video/')) {
|
||||
e.preventDefault()
|
||||
const file = item.getAsFile()
|
||||
if (!file) continue
|
||||
|
||||
try {
|
||||
// Upload image
|
||||
const formData = new FormData()
|
||||
formData.append('file', file)
|
||||
formData.append('categoryId', '1') // 默认上传到分类1
|
||||
formData.append('storageType', 'local')
|
||||
|
||||
const token = localStorage.getItem('token')
|
||||
const response = await fetch('/api/admin/attachments/upload', {
|
||||
method: 'POST',
|
||||
headers: {
|
||||
...(token ? { Authorization: `Bearer ${token}` } : {})
|
||||
},
|
||||
body: formData
|
||||
})
|
||||
|
||||
if (!response.ok) {
|
||||
const errorData = await response.json()
|
||||
throw new Error(errorData.message || '上传失败')
|
||||
}
|
||||
|
||||
const data = await response.json()
|
||||
const imageUrl = data.result.fileUrl
|
||||
|
||||
// Insert markdown image syntax
|
||||
const imageMarkdown = ``
|
||||
const currentContent = form.content
|
||||
// Insert at the end of content (md-editor-v3 will handle cursor position)
|
||||
form.content = currentContent + (currentContent ? '\n\n' : '') + imageMarkdown + '\n'
|
||||
|
||||
toast.showToast('图片上传成功', 'success')
|
||||
} catch (error: any) {
|
||||
console.error('上传图片失败:', error)
|
||||
toast.showToast(error.message || '上传图片失败', 'error')
|
||||
}
|
||||
break // Only handle first image
|
||||
if (file) await uploadAndInsertVideo(file)
|
||||
break
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@@ -78,7 +78,7 @@
|
||||
import { ref, reactive, onMounted, computed } from 'vue'
|
||||
import { useRouter, useRoute } from 'vue-router'
|
||||
import { useToast } from '../../composables/useToast'
|
||||
import { createUser, updateUser, API_BASE, getAuthHeaders } from '../../services/api'
|
||||
import { createUser, updateUser, fetchUser } from '../../services/api'
|
||||
import CustomSelect from '../../components/CustomSelect.vue'
|
||||
|
||||
const router = useRouter()
|
||||
@@ -180,49 +180,13 @@ onMounted(async () => {
|
||||
if (isEditing.value) {
|
||||
try {
|
||||
const userId = parseInt(route.params.id as string)
|
||||
console.log(`Fetching user data for ID: ${userId}`)
|
||||
|
||||
// Direct fetch to debug
|
||||
const response = await fetch(`${API_BASE}/admin/users/${userId}`, {
|
||||
headers: getAuthHeaders()
|
||||
})
|
||||
|
||||
console.log(`Response status: ${response.status}`)
|
||||
|
||||
// Check response headers
|
||||
const contentType = response.headers.get('content-type')
|
||||
console.log(`Response content-type: ${contentType}`)
|
||||
|
||||
// Read response as text first to debug
|
||||
const responseText = await response.text()
|
||||
console.log(`Response text: ${responseText}`)
|
||||
|
||||
// Then try to parse as JSON
|
||||
if (!response.ok) {
|
||||
// If response is not ok, still try to parse as JSON
|
||||
let errorData
|
||||
try {
|
||||
errorData = JSON.parse(responseText)
|
||||
throw new Error(errorData.message || '获取用户详情失败')
|
||||
} catch (parseError) {
|
||||
const errorMessage = parseError instanceof Error ? parseError.message : String(parseError)
|
||||
throw new Error(`获取用户详情失败,响应格式错误: ${errorMessage}`)
|
||||
}
|
||||
}
|
||||
|
||||
// Parse successful response
|
||||
const data = JSON.parse(responseText)
|
||||
const user = data.result // 从统一响应格式中提取 result
|
||||
console.log('Parsed user data:', user)
|
||||
|
||||
// Populate form with user data
|
||||
const user = await fetchUser(userId)
|
||||
form.username = user.username
|
||||
form.email = user.email
|
||||
form.role = user.role
|
||||
form.isActive = user.isActive
|
||||
} catch (error: any) {
|
||||
console.error('Failed to fetch user data:', error)
|
||||
console.error('Error stack:', error.stack)
|
||||
toast.error('加载用户数据失败: ' + (error.message || '未知错误'))
|
||||
}
|
||||
}
|
||||
|
||||
@@ -1,4 +1,5 @@
|
||||
import { createRouter, createWebHistory } from 'vue-router'
|
||||
import { useAuth } from './composables/useAuth'
|
||||
import { getPublicSettings } from './services/api'
|
||||
|
||||
// 缓存网站配置,避免重复获取
|
||||
@@ -166,10 +167,8 @@ const router = createRouter({
|
||||
router.beforeEach(async (to, _from, next) => {
|
||||
// 检查路由是否需要认证
|
||||
if (to.matched.some(record => record.meta.requiresAuth)) {
|
||||
// 检查本地存储中是否有token
|
||||
const token = localStorage.getItem('token')
|
||||
if (!token) {
|
||||
// 没有token,重定向到登录页
|
||||
const { isAuthenticated } = useAuth()
|
||||
if (!isAuthenticated()) {
|
||||
next({ name: 'login' })
|
||||
return
|
||||
}
|
||||
|
||||
File diff suppressed because it is too large
Load Diff
Reference in New Issue
Block a user