feat: 全面升级——后台优化 / 动态配置 / 个人中心 / OSS 存储

- OSS 文件存储(RustFS / S3 v4 兼容,零依赖手写 SigV4):
  上传/列表/删除走桶 arcticnewone,/uploads 代理服务 + 本地回退;
  server/utils/sigv4.ts 纯函数 + AWS 测试向量验证
- 业务动态配置:settings 表 + /api/settings(公开) + /api/admin/settings(PATCH),
  useSiteSettings 组合式,footer/contact/tools/app.vue/侧边栏/工具页全部接入,
  后台 /admin/settings 修改前台即时生效(站点/联系/社交/工具箱/页脚/SEO)
- 后台全面优化:Admin* 设计系统(按钮/输入/表单/卡片/徽标/弹窗/确认/空态/骨架/
  分页/页头/Toast)14 组件;Dashboard 增强;各列表页搜索/筛选/批量删除/分页;
  布局与侧边栏分组;统一 toast/确认反馈
- 个人中心全新重设计:顶部资料卡 + 统计、精致化改密/删号(二次确认)、
  收藏封面网格、评论卡片、移动端适配
- deploy.sh 支持 OSS 凭据注入(NUXT_OSS_*);.env.example 更新
- 测试 17 例全过(含 SigV4 AWS 向量、settings 默认结构)
This commit is contained in:
2026-08-06 18:40:17 +08:00
parent 685c7b51d1
commit 5a7ad8de11
55 changed files with 3857 additions and 1993 deletions
+9
View File
@@ -30,3 +30,12 @@ NUXT_ADMIN_EMAILS=chenchun@virtheart.com
# 预置管理员初始密码(仅首次初始化数据库时创建 admin 账号用;生产由 deploy.sh 注入)
# NUXT_ADMIN_INITIAL_PASSWORD=change-me
# ---- OSS 文件存储(RustFS / S3 v4 兼容;凭据不写入仓库,生产由 deploy.sh 注入 Secret)----
NUXT_OSS_ENDPOINT=oss.virtheart.com
NUXT_OSS_ACCESS_KEY=
NUXT_OSS_SECRET_KEY=
NUXT_OSS_BUCKET=arcticnewone
NUXT_OSS_REGION=us-east-1
# 若桶公开可读,可填 https://oss.virtheart.com/arcticnewone 用于直链;留空则走 /uploads 代理
NUXT_OSS_PUBLIC_BASE=
+10 -9
View File
@@ -52,16 +52,16 @@ pnpm dev
| 模块 | 说明 |
| --- | --- |
| 页面 | 首页、工作室、作品(列表/详情)、动态(列表/详情)、工具箱、联系、个人中心 |
| **后台管理** | `/admin`:Dashboard 统计、动态/作品增删改(中英双语 CMS)、用户管理、评论审核、联系/订阅管理、图片上传 |
| 用户系统 | 真实注册/登录/登出(scrypt 密码哈希 + httpOnly Cookie 会话);预置 admin 账号 |
| 个人中心 | `/account`:资料编辑、作品收藏、我的评论;管理员可进入 `/admin` |
| **后台管理** | `/admin`:Dashboard、动态/作品增删改(双语 CMS)、用户/评论/联系/订阅管理、图片管理(OSS)、操作审计日志、**站点动态配置** |
| **动态配置** | 站点信息/联系方式/社交链接/工具箱/页脚文案/SEO 均可在 `/admin/settings` 后台修改,前台即时生效 |
| **文件存储** | 图片上传/管理使用 OSS(RustFS,S3 v4 兼容,桶 `arcticnewone`),经 `/uploads` 代理服务 |
| 用户系统 | 注册/登录/登出、修改密码、自助删除账号、预置 admin;个人中心(资料/收藏/评论) |
| 交互 | 作品收藏、新闻评论、分享(X/LinkedIn/复制链接)、搜索、加载更多 |
| 国际化 | 中/英双语,Header 一键切换(`no_prefix`,默认中文);内容双语存于数据库 |
| SEO | 动态 `sitemap.xml`(数据来自 DB)/ `robots.txt`、JSON-LD、自动生成的 `og-image.png` |
| 邮件 | SMTP 发送联系/订阅邮件;未配置 SMTP 时数据仍真实写入 SQLite |
| 国际化 | 中/英双语,Header 一键切换;内容双语存于数据库 |
| SEO | 动态 `sitemap.xml`/`robots.txt`/`feed.xml`(RSS)、JSON-LD、canonical、`og-image.png` |
| 工程 | `pnpm test`(vitest:密码/SigV4/校验器/种子/配置 17 例) |
> **预置管理员**:首次部署时若设置 `ADMIN_INITIAL_PASSWORD`(或由 `deploy.sh` 自动生成并打印),
> 数据库初始化会自动创建 `admin` 账号(邮箱取 `ADMIN_EMAILS` 第一个)。登录后访问 `/admin` 即可管理内容。
> **预置管理员**:首次部署设置 `ADMIN_INITIAL_PASSWORD`(或由 `deploy.sh` 自动生成并打印)会自动创建 `admin` 账号,登录后访问 `/admin` 管理内容与配置。
### 环境变量(详见 `.env.example`,Nuxt runtimeConfig 使用 `NUXT_` 前缀)
@@ -74,8 +74,9 @@ pnpm dev
| `NUXT_CONTACT_TO` | 联系表单留言收件邮箱 |
| `NUXT_ADMIN_EMAILS` | 管理员邮箱(逗号分隔),命中者个人中心可见管理面板 |
| `NUXT_ADMIN_INITIAL_PASSWORD` | 预置管理员初始密码(仅首次初始化创建 admin 账号用) |
| `NUXT_OSS_ENDPOINT/ACCESS_KEY/SECRET_KEY/BUCKET/REGION/PUBLIC_BASE` | OSS 文件存储(RustFS / S3 v4,凭据仅走 Secret,不写入仓库) |
> `deploy.sh` 中的对外变量名(`SESSION_SECRET`/`SMTP_*`/`CONTACT_TO`/`ADMIN_EMAILS`/`ADMIN_INITIAL_PASSWORD`)会在写入 K8s Secret 时自动加 `NUXT_` 前缀。
> `deploy.sh` 中的对外变量名(`SESSION_SECRET`/`SMTP_*`/`CONTACT_TO`/`ADMIN_EMAILS`/`ADMIN_INITIAL_PASSWORD`/`OSS_*`)会在写入 K8s Secret 时自动加 `NUXT_` 前缀。
## 项目结构
+15 -13
View File
@@ -2,9 +2,10 @@
import { computed } from 'vue'
import { useHead, useSeoMeta, useRuntimeConfig, useRoute } from '#imports'
import { useI18n } from 'vue-i18n'
import { siteConfig } from '~/config/site'
import { useSiteSettings } from '~/composables/useSiteSettings'
const { t } = useI18n()
const { settings, loc } = useSiteSettings()
const { public: publicCfg } = useRuntimeConfig()
const route = useRoute()
const baseUrl = String(publicCfg.siteUrl || '').replace(/\/$/, '')
@@ -15,40 +16,41 @@ const siteImage = baseUrl ? `${baseUrl}/og-image.png` : '/og-image.png'
// 配置全局 Title 模板 + canonical(SEO)
useHead({
titleTemplate: (titleChunk?: string) => {
const siteName = t('app.name')
const siteName = settings.value?.site.name || t('app.name')
return titleChunk ? `${titleChunk} - ${siteName}` : siteName
},
link: [
{ rel: 'canonical', href: computed(() => (baseUrl ? `${baseUrl}${route.path}` : undefined)) },
],
// JSON-LD 结构化数据(Organization)
// JSON-LD 结构化数据(Organization,取自后台动态配置)
script: [
{
type: 'application/ld+json',
innerHTML: JSON.stringify({
'@context': 'https://schema.org',
'@type': 'Organization',
name: t('app.name'),
alternateName: siteConfig.brandZh,
description: t('app.description'),
name: settings.value?.site.name || t('app.name'),
alternateName: settings.value?.site.brand || '',
description: loc(settings.value?.site.description) || t('app.description'),
url: baseUrl || undefined,
logo: siteImage,
sameAs: siteConfig.socials.map((s) => s.url),
sameAs: (settings.value?.socials ?? []).map((s) => s.url),
}),
},
],
})
// 配置全局基础 SEO 和 Meta (响应式支持国际化)
// 配置全局基础 SEO 和 Meta (取自后台动态配置,响应式国际化)
useSeoMeta({
description: () => t('app.description'),
ogTitle: () => t('app.name'),
ogDescription: () => t('app.description'),
description: () => loc(settings.value?.site.description) || t('app.description'),
keywords: () => loc(settings.value?.seo.keywords) || undefined,
ogTitle: () => settings.value?.site.name || t('app.name'),
ogDescription: () => loc(settings.value?.site.description) || t('app.description'),
ogImage: siteImage,
ogType: 'website',
twitterCard: 'summary_large_image',
twitterTitle: () => t('app.name'),
twitterDescription: () => t('app.description'),
twitterTitle: () => settings.value?.site.name || t('app.name'),
twitterDescription: () => loc(settings.value?.site.description) || t('app.description'),
twitterImage: siteImage,
})
</script>
+22
View File
@@ -0,0 +1,22 @@
<template>
<span
class="inline-flex items-center gap-1 rounded-full px-2.5 py-0.5 text-xs font-semibold"
:class="toneClass"
>
<slot />
</span>
</template>
<script setup lang="ts">
const props = withDefaults(defineProps<{ tone?: 'gray' | 'green' | 'red' | 'amber' | 'black' | 'blue' }>(), {
tone: 'gray',
})
const toneClass = {
gray: 'bg-gray-100 text-gray-600',
green: 'bg-green-50 text-green-700',
red: 'bg-red-50 text-red-700',
amber: 'bg-amber-50 text-amber-700',
black: 'bg-black text-white',
blue: 'bg-blue-50 text-blue-700',
}[props.tone]
</script>
+40
View File
@@ -0,0 +1,40 @@
<template>
<button
:type="type"
:disabled="disabled || loading"
class="inline-flex items-center justify-center gap-2 rounded-xl font-semibold transition-all duration-200 focus:outline-none focus:ring-2 focus:ring-black/10 disabled:opacity-50 disabled:cursor-not-allowed"
:class="[sizeClass, variantClass, block ? 'w-full' : '']"
@click="emit('click', $event)"
>
<Icon v-if="loading" name="ph:circle-notch" class="w-4 h-4 animate-spin" />
<slot />
</button>
</template>
<script setup lang="ts">
const props = withDefaults(
defineProps<{
type?: 'button' | 'submit'
variant?: 'primary' | 'secondary' | 'danger' | 'ghost'
size?: 'sm' | 'md' | 'lg'
loading?: boolean
disabled?: boolean
block?: boolean
}>(),
{ type: 'button', variant: 'primary', size: 'md', loading: false, disabled: false, block: false },
)
const emit = defineEmits<{ click: [e: MouseEvent] }>()
const sizeClass = {
sm: 'px-3 py-1.5 text-xs',
md: 'px-4 py-2 text-sm',
lg: 'px-6 py-3 text-base',
}[props.size]
const variantClass = {
primary: 'bg-black text-white hover:bg-gray-800 shadow-sm',
secondary: 'bg-gray-100 text-gray-800 hover:bg-gray-200',
danger: 'bg-red-600 text-white hover:bg-red-700 shadow-sm',
ghost: 'text-gray-600 hover:bg-gray-100',
}[props.variant]
</script>
+16
View File
@@ -0,0 +1,16 @@
<template>
<div class="rounded-2xl border border-gray-100 bg-white shadow-sm">
<div v-if="title || $slots.actions" class="flex items-center justify-between gap-3 border-b border-gray-100 px-5 py-4">
<div>
<h3 v-if="title" class="text-base font-bold text-black">{{ title }}</h3>
<p v-if="subtitle" class="mt-0.5 text-sm text-gray-500">{{ subtitle }}</p>
</div>
<div v-if="$slots.actions" class="flex items-center gap-2"><slot name="actions" /></div>
</div>
<div class="p-5"><slot /></div>
</div>
</template>
<script setup lang="ts">
withDefaults(defineProps<{ title?: string; subtitle?: string }>(), { title: '', subtitle: '' })
</script>
+27
View File
@@ -0,0 +1,27 @@
<template>
<AdminModal :open="open" title="确认操作" @update:open="emit('update:open', $event)">
<div class="flex items-start gap-3">
<div
class="flex h-10 w-10 shrink-0 items-center justify-center rounded-full"
:class="danger ? 'bg-red-50 text-red-600' : 'bg-gray-100 text-gray-600'"
>
<Icon :name="danger ? 'ph:warning-fill' : 'ph:question-fill'" class="w-5 h-5" />
</div>
<p class="text-sm text-gray-700 leading-relaxed">{{ message }}</p>
</div>
<template #footer>
<AdminButton variant="secondary" size="sm" :disabled="loading" @click="emit('update:open', false)">取消</AdminButton>
<AdminButton :variant="danger ? 'danger' : 'primary'" size="sm" :loading="loading" @click="emit('confirm')">
确认
</AdminButton>
</template>
</AdminModal>
</template>
<script setup lang="ts">
withDefaults(defineProps<{ open: boolean; message: string; danger?: boolean; loading?: boolean }>(), {
danger: false,
loading: false,
})
const emit = defineEmits<{ 'update:open': [v: boolean]; confirm: [] }>()
</script>
+17
View File
@@ -0,0 +1,17 @@
<template>
<div class="flex flex-col items-center justify-center gap-3 py-14 text-center">
<div class="flex h-14 w-14 items-center justify-center rounded-full bg-gray-100 text-gray-400">
<Icon :name="icon" class="w-7 h-7" />
</div>
<p class="text-sm font-semibold text-gray-700">{{ title }}</p>
<p v-if="description" class="text-sm text-gray-500 max-w-sm">{{ description }}</p>
<div v-if="$slots.action" class="mt-1"><slot name="action" /></div>
</div>
</template>
<script setup lang="ts">
withDefaults(defineProps<{ icon?: string; title: string; description?: string }>(), {
icon: 'ph:tray',
description: '',
})
</script>
+32
View File
@@ -0,0 +1,32 @@
<template>
<div>
<label v-if="label" class="block text-sm font-semibold text-gray-800 mb-1.5">{{ label }}<span v-if="required" class="text-red-500 ml-0.5">*</span></label>
<input
:type="type"
:value="modelValue"
:placeholder="placeholder"
:disabled="disabled"
:required="required"
class="w-full rounded-xl border bg-white px-3.5 py-2.5 text-sm outline-none transition-all focus:ring-2"
:class="error ? 'border-red-300 focus:border-red-500 focus:ring-red-500/10' : 'border-gray-200 focus:border-black focus:ring-black/10'"
@input="emit('update:modelValue', ($event.target as HTMLInputElement).value)"
/>
<p v-if="error" class="mt-1 text-xs text-red-600">{{ error }}</p>
</div>
</template>
<script setup lang="ts">
withDefaults(
defineProps<{
modelValue: string
label?: string
type?: string
placeholder?: string
error?: string
disabled?: boolean
required?: boolean
}>(),
{ label: '', type: 'text', placeholder: '', error: '', disabled: false, required: false },
)
const emit = defineEmits<{ 'update:modelValue': [v: string] }>()
</script>
+48
View File
@@ -0,0 +1,48 @@
<template>
<Teleport to="body">
<Transition name="modal">
<div
v-if="open"
class="fixed inset-0 z-[150] flex items-center justify-center bg-black/40 p-4"
@click.self="emit('update:open', false)"
>
<div class="w-full max-w-lg rounded-2xl bg-white shadow-2xl">
<div class="flex items-center justify-between border-b border-gray-100 px-6 py-4">
<h3 class="text-lg font-bold text-black">{{ title }}</h3>
<button @click="emit('update:open', false)" class="text-gray-400 hover:text-gray-600" aria-label="close">
<Icon name="ph:x" class="w-5 h-5" />
</button>
</div>
<div class="px-6 py-5 max-h-[70vh] overflow-y-auto"><slot /></div>
<div v-if="$slots.footer" class="flex justify-end gap-2 border-t border-gray-100 px-6 py-4">
<slot name="footer" />
</div>
</div>
</div>
</Transition>
</Teleport>
</template>
<script setup lang="ts">
withDefaults(defineProps<{ open: boolean; title?: string }>(), { title: '' })
const emit = defineEmits<{ 'update:open': [v: boolean] }>()
</script>
<style scoped>
.modal-enter-active,
.modal-leave-active {
transition: opacity 0.2s ease;
}
.modal-enter-from,
.modal-leave-to {
opacity: 0;
}
.modal-enter-active > div,
.modal-leave-active > div {
transition: transform 0.2s ease;
}
.modal-enter-from > div,
.modal-leave-to > div {
transform: scale(0.97) translateY(8px);
}
</style>
+13
View File
@@ -0,0 +1,13 @@
<template>
<div class="flex flex-wrap items-center justify-between gap-3 mb-6">
<div>
<h1 class="text-2xl font-bold text-black">{{ title }}</h1>
<p v-if="subtitle" class="mt-1 text-sm text-gray-500">{{ subtitle }}</p>
</div>
<div v-if="$slots.actions" class="flex items-center gap-2"><slot name="actions" /></div>
</div>
</template>
<script setup lang="ts">
withDefaults(defineProps<{ title: string; subtitle?: string }>(), { subtitle: '' })
</script>
+20
View File
@@ -0,0 +1,20 @@
<template>
<div v-if="total > 0" class="flex items-center justify-between gap-4 text-sm">
<p class="text-gray-500">共 {{ total }} 条</p>
<div class="flex items-center gap-2">
<AdminButton variant="secondary" size="sm" :disabled="page <= 1" @click="emit('page', page - 1)">上一页</AdminButton>
<span class="text-gray-600 px-1">{{ page }} / {{ totalPages }}</span>
<AdminButton variant="secondary" size="sm" :disabled="page >= totalPages" @click="emit('page', page + 1)">下一页</AdminButton>
</div>
</div>
</template>
<script setup lang="ts">
import { computed } from 'vue'
const props = withDefaults(
defineProps<{ total: number; page: number; pageSize?: number }>(),
{ pageSize: 20 },
)
const emit = defineEmits<{ page: [p: number] }>()
const totalPages = computed(() => Math.max(1, Math.ceil(props.total / props.pageSize)))
</script>
+25
View File
@@ -0,0 +1,25 @@
<template>
<div>
<label v-if="label" class="block text-sm font-semibold text-gray-800 mb-1.5">{{ label }}</label>
<select
:value="modelValue"
:disabled="disabled"
class="w-full rounded-xl border border-gray-200 bg-white px-3.5 py-2.5 text-sm outline-none transition-all focus:border-black focus:ring-2 focus:ring-black/10 disabled:opacity-50"
@change="emit('update:modelValue', ($event.target as HTMLSelectElement).value)"
>
<option v-for="o in options" :key="o.value" :value="o.value">{{ o.label }}</option>
</select>
</div>
</template>
<script setup lang="ts">
interface Option {
label: string
value: string
}
withDefaults(defineProps<{ modelValue: string; options: Option[]; label?: string; disabled?: boolean }>(), {
label: '',
disabled: false,
})
const emit = defineEmits<{ 'update:modelValue': [v: string] }>()
</script>
+43 -6
View File
@@ -1,24 +1,52 @@
<script setup lang="ts">
/**
* 后台左侧导航栏(Dashboard / 动态 / 作品 / 用户 / 评论 / 联系 / 订阅 / 图片 / 日志 / 返回前台)。
* 后台左侧导航栏:按「内容 / 数据 / 系统」分组,底部返回前台。
* 高亮当前路由;点击任意导航项时向父级发出 navigate 事件(移动端关闭侧栏)。
*/
import { useRoute } from '#app'
import { siteConfig } from '~/config/site'
import { useSiteSettings } from '~/composables/useSiteSettings'
const route = useRoute()
const emit = defineEmits<{ navigate: [] }>()
const { settings } = useSiteSettings()
const items = [
interface SidebarItem {
to: string
label: string
icon: string
}
interface SidebarGroup {
label: string
items: SidebarItem[]
}
const groups: SidebarGroup[] = [
{
label: '内容',
items: [
{ to: '/admin', label: 'Dashboard', icon: 'ph:gauge' },
{ to: '/admin/news', label: '动态管理', icon: 'ph:newspaper' },
{ to: '/admin/work', label: '作品管理', icon: 'ph:image-square' },
],
},
{
label: '数据',
items: [
{ to: '/admin/users', label: '用户管理', icon: 'ph:users-three' },
{ to: '/admin/comments', label: '评论管理', icon: 'ph:chat-circle-text' },
{ to: '/admin/contacts', label: '联系留言', icon: 'ph:envelope-simple' },
{ to: '/admin/subscribers', label: '订阅管理', icon: 'ph:paper-plane-tilt' },
],
},
{
label: '系统',
items: [
{ to: '/admin/uploads', label: '图片管理', icon: 'ph:image' },
{ to: '/admin/audit', label: '操作日志', icon: 'ph:list-checks' },
{ to: '/admin/settings', label: '站点设置', icon: 'ph:gear-six' },
],
},
]
const isActive = (to: string) => route.path === to
@@ -37,14 +65,21 @@ const isActive = (to: string) => route.path === to
A
</div>
<div class="leading-tight">
<p class="text-sm font-bold">{{ siteConfig.brandZh }}</p>
<p class="text-sm font-bold">{{ settings?.site.brand }}</p>
<p class="text-[11px] text-white/50">后台管理</p>
</div>
</NuxtLink>
<nav class="flex-1 py-4 px-3 space-y-1 overflow-y-auto">
<nav class="flex-1 py-5 px-3 overflow-y-auto space-y-6">
<div v-for="group in groups" :key="group.label">
<p
class="px-3 mb-1.5 text-[11px] font-semibold uppercase tracking-wider text-white/40"
>
{{ group.label }}
</p>
<div class="space-y-1">
<NuxtLink
v-for="item in items"
v-for="item in group.items"
:key="item.to"
:to="item.to"
class="flex items-center gap-3 px-3 py-2.5 rounded-lg text-sm font-medium transition-colors"
@@ -54,6 +89,8 @@ const isActive = (to: string) => route.path === to
<Icon :name="item.icon" class="w-[18px] h-[18px]" />
{{ item.label }}
</NuxtLink>
</div>
</div>
</nav>
<div class="p-3 border-t border-white/10 shrink-0">
+11
View File
@@ -0,0 +1,11 @@
<template>
<div class="space-y-3 p-2">
<div v-for="i in rows" :key="i" class="animate-pulse">
<div class="h-3.5 rounded bg-gray-100" :style="{ width: `${40 + ((i * 13) % 50)}%` }" />
</div>
</div>
</template>
<script setup lang="ts">
withDefaults(defineProps<{ rows?: number }>(), { rows: 5 })
</script>
+31
View File
@@ -0,0 +1,31 @@
<template>
<div>
<label v-if="label" class="block text-sm font-semibold text-gray-800 mb-1.5">{{ label }}<span v-if="required" class="text-red-500 ml-0.5">*</span></label>
<textarea
:value="modelValue"
:placeholder="placeholder"
:disabled="disabled"
:rows="rows"
class="w-full rounded-xl border bg-white px-3.5 py-2.5 text-sm outline-none transition-all focus:ring-2 resize-y"
:class="error ? 'border-red-300 focus:border-red-500 focus:ring-red-500/10' : 'border-gray-200 focus:border-black focus:ring-black/10'"
@input="emit('update:modelValue', ($event.target as HTMLTextAreaElement).value)"
/>
<p v-if="error" class="mt-1 text-xs text-red-600">{{ error }}</p>
</div>
</template>
<script setup lang="ts">
withDefaults(
defineProps<{
modelValue: string
label?: string
placeholder?: string
error?: string
disabled?: boolean
required?: boolean
rows?: number
}>(),
{ label: '', placeholder: '', error: '', disabled: false, required: false, rows: 3 },
)
const emit = defineEmits<{ 'update:modelValue': [v: string] }>()
</script>
+54
View File
@@ -0,0 +1,54 @@
<template>
<Teleport to="body">
<div class="fixed top-4 right-4 z-[200] flex flex-col gap-2 w-80 max-w-[calc(100vw-2rem)]">
<TransitionGroup name="toast">
<div
v-for="t in toast.toasts"
:key="t.id"
class="flex items-start gap-3 rounded-xl border bg-white px-4 py-3 shadow-lg"
:class="borderClass(t.type)"
>
<Icon :name="iconFor(t.type)" class="w-5 h-5 mt-0.5" :class="iconClass(t.type)" />
<p class="flex-1 text-sm text-gray-800 break-words">{{ t.message }}</p>
<button @click="toast.remove(t.id)" class="text-gray-400 hover:text-gray-600" aria-label="close">
<Icon name="ph:x" class="w-4 h-4" />
</button>
</div>
</TransitionGroup>
</div>
</Teleport>
</template>
<script setup lang="ts">
import { useToastStore } from '~/stores/toast'
const toast = useToastStore()
const borderClass = (type: string) => {
if (type === 'success') return 'border-green-200'
if (type === 'error') return 'border-red-200'
return 'border-gray-200'
}
const iconFor = (type: string) => {
if (type === 'success') return 'ph:check-circle-fill'
if (type === 'error') return 'ph:warning-circle-fill'
return 'ph:info-fill'
}
const iconClass = (type: string) => {
if (type === 'success') return 'text-green-600'
if (type === 'error') return 'text-red-600'
return 'text-gray-400'
}
</script>
<style scoped>
.toast-enter-active,
.toast-leave-active {
transition: all 0.25s ease;
}
.toast-enter-from,
.toast-leave-to {
opacity: 0;
transform: translateX(16px);
}
</style>
+18
View File
@@ -0,0 +1,18 @@
<template>
<button
type="button"
class="relative inline-flex h-6 w-11 items-center rounded-full transition-colors duration-200 focus:outline-none focus:ring-2 focus:ring-black/10"
:class="modelValue ? 'bg-black' : 'bg-gray-300'"
@click="emit('update:modelValue', !modelValue)"
>
<span
class="inline-block h-4 w-4 transform rounded-full bg-white shadow transition-transform duration-200"
:class="modelValue ? 'translate-x-6' : 'translate-x-1'"
/>
</button>
</template>
<script setup lang="ts">
defineProps<{ modelValue: boolean }>()
const emit = defineEmits<{ 'update:modelValue': [v: boolean] }>()
</script>
+14 -12
View File
@@ -5,11 +5,13 @@ import { gsap } from 'gsap'
import { ScrollTrigger } from 'gsap/ScrollTrigger'
import FooterLogo from '~/components/common/FooterLogo.vue'
import AnimatedButton from '~/components/common/AnimatedButton.vue'
import { siteConfig } from '~/config/site'
import { useSiteSettings } from '~/composables/useSiteSettings'
const { t } = useI18n()
const { settings, loc } = useSiteSettings()
gsap.registerPlugin(ScrollTrigger)
const { t } = useI18n()
const footerRef = ref<HTMLElement | null>(null)
const newsletterEmail = ref('')
const isSubscribing = ref(false)
@@ -121,7 +123,7 @@ onUnmounted(() => {
<!-- Top Section -->
<div class="flex flex-col md:flex-row justify-between items-start md:items-end gap-8 mb-16">
<h2 class="animated-item text-3xl md:text-4xl lg:text-[44px] font-normal tracking-normal !leading-[1.4] max-w-none whitespace-pre-line">
{{ t('footer.title') }}
{{ loc(settings?.footer.title) }}
</h2>
<div class="animated-item inline-flex items-center shrink-0">
<AnimatedButton
@@ -143,7 +145,7 @@ onUnmounted(() => {
<div>
<FooterLogo class="mb-16 animated-item justify-start" />
<h3 class="text-2xl font-medium mb-6 animated-item">{{ t('footer.newsletterTitle') }}</h3>
<h3 class="text-2xl font-medium mb-6 animated-item">{{ loc(settings?.footer.newsletterTitle) }}</h3>
<form @submit.prevent="handleNewsletterSubmit" class="relative w-full max-w-sm mb-4 animated-item">
<input
@@ -180,13 +182,13 @@ onUnmounted(() => {
<div class="text-xs text-white/40 flex items-center gap-2 animated-item">
<span class="w-1.5 h-1.5 bg-white rounded-full inline-block shrink-0"></span>
{{ t('footer.newsletterNote') }}
{{ loc(settings?.footer.newsletterNote) }}
</div>
</div>
<div class="mt-24 lg:mt-0 flex items-center gap-2 animated-item">
<div class="text-[16px] font-bold text-white/30 font-sans">
{{ t('footer.copyright') }}
{{ loc(settings?.footer.copyright) }}
</div>
</div>
</div>
@@ -226,10 +228,10 @@ onUnmounted(() => {
<div class="grid grid-cols-1 sm:grid-cols-2 gap-8">
<ul class="space-y-3">
<li class="animated-item">
<a :href="`mailto:${siteConfig.email}`" class="group flex items-center overflow-hidden text-[16px] font-bold text-white/80 hover:text-white transition-colors" style="justify-content: flex-start;">
<a :href="`mailto:${settings?.contact.email}`" class="group flex items-center overflow-hidden text-[16px] font-bold text-white/80 hover:text-white transition-colors" style="justify-content: flex-start;">
<div class="flex items-center transition-transform duration-300 group-hover:translate-x-0 -translate-x-[21px] pr-[21px]">
<span class="mr-[10px] h-[11px] w-[11px] rounded-full bg-white shrink-0"></span>
<span>{{ siteConfig.email }}</span>
<span>{{ settings?.contact.email }}</span>
</div>
</a>
</li>
@@ -237,7 +239,7 @@ onUnmounted(() => {
<span class="group flex items-center overflow-hidden text-[16px] font-bold text-white/80 transition-colors cursor-default" style="justify-content: flex-start;">
<div class="flex items-center transition-transform duration-300 group-hover:translate-x-0 -translate-x-[21px] pr-[21px]">
<span class="mr-[10px] h-[11px] w-[11px] rounded-full bg-white shrink-0"></span>
<span>{{ t('footer.wechat') }}: {{ siteConfig.wechat }}</span>
<span>{{ t('footer.wechat') }}: {{ settings?.contact.wechat }}</span>
</div>
</span>
</li>
@@ -245,10 +247,10 @@ onUnmounted(() => {
<ul class="space-y-3">
<li class="animated-item">
<a :href="`mailto:${siteConfig.infoEmail}`" class="group flex items-center overflow-hidden text-[16px] font-bold text-white/80 hover:text-white transition-colors" style="justify-content: flex-start;">
<a :href="`mailto:${settings?.contact.infoEmail}`" class="group flex items-center overflow-hidden text-[16px] font-bold text-white/80 hover:text-white transition-colors" style="justify-content: flex-start;">
<div class="flex items-center transition-transform duration-300 group-hover:translate-x-0 -translate-x-[21px] pr-[21px]">
<span class="mr-[10px] h-[11px] w-[11px] rounded-full bg-white shrink-0"></span>
<span>{{ siteConfig.infoEmail }}</span>
<span>{{ settings?.contact.infoEmail }}</span>
</div>
</a>
</li>
@@ -266,7 +268,7 @@ onUnmounted(() => {
<div class="flex gap-3 animated-item">
<a
v-for="social in siteConfig.socials"
v-for="social in settings?.socials ?? []"
:key="social.name"
:href="social.url"
target="_blank"
+20
View File
@@ -0,0 +1,20 @@
import { computed } from 'vue'
import { useFetch } from '#imports'
import { useI18n } from 'vue-i18n'
import type { SiteSettings, LocalizedText } from '~/config/site'
/**
* 站点动态配置(SSR 友好)。
* - settings:后端合并默认值后的站点配置(可在后台 /admin/settings 修改)
* - loc(t):按当前语言取双语文本(locale 切换即时生效,无需重新请求)
*/
export function useSiteSettings() {
const { locale } = useI18n()
const { data, refresh, status } = useFetch<SiteSettings>('/api/settings')
const settings = computed(() => data.value)
const loc = (t?: LocalizedText) => (t ? (locale.value === 'zh' ? t.zh : t.en) : '')
return { settings, loc, refresh, status }
}
+116 -8
View File
@@ -1,27 +1,135 @@
/**
* 站点全局元数据(品牌、联系、社交)。
* 站点配置:类型 + 默认值(单一事实源)。
*
* 单一事实源:Footer、联系页、账号页等不再各自硬编码邮箱/社交链接。
*
* 注意:社交地址为品牌官方占位链接,正式上线前请替换为北极新一真实账号。
* 业务配置可在后台 `/admin/settings` 动态修改(存于 DB settings 表),
* 未修改时使用这里的默认值。`siteConfig` 为兼容旧引用的子集。
*/
export interface LocalizedText {
zh: string
en: string
}
export interface SocialLink {
name: string
icon: string
url: string
}
export const siteConfig = {
brand: 'ArcticNewOne',
brandZh: '北极新一',
export interface ToolItem {
id: string
name: string
url: string
icon: string
color: string
descZh: string
descEn: string
}
export interface SiteSettings {
site: {
name: string
brand: string
description: LocalizedText
}
contact: {
email: string
infoEmail: string
wechat: string
address: LocalizedText
}
socials: SocialLink[]
tools: ToolItem[]
footer: {
title: LocalizedText
newsletterTitle: LocalizedText
newsletterNote: LocalizedText
copyright: LocalizedText
}
seo: {
description: LocalizedText
keywords: LocalizedText
}
}
export const defaultSettings: SiteSettings = {
site: {
name: 'ArcticNewOne',
brand: '北极新一',
description: {
zh: '探索无限可能的现代化体验,欢迎来到 ArcticNewOne。',
en: 'Explore infinite possibilities and modern experiences. Welcome to ArcticNewOne.',
},
},
contact: {
email: 'chenchun@virtheart.com',
infoEmail: 'info@virtheart.com',
wechat: 'LucskyNew',
copyright: '© 2026 北极新一工作室',
address: {
zh: '贵州省毕节市七星关区\n滨河西路',
en: 'Binhe West Road, Qixingguan District\nBijie City, Guizhou Province',
},
},
socials: [
{ name: 'X', icon: 'ph:x-logo', url: 'https://x.com/arcticnewone' },
{ name: 'Instagram', icon: 'ph:instagram-logo', url: 'https://instagram.com/arcticnewone' },
{ name: 'LinkedIn', icon: 'ph:linkedin-logo', url: 'https://www.linkedin.com/company/arcticnewone' },
{ name: 'GitHub', icon: 'ph:github-logo', url: 'https://github.com/arcticnewone' },
],
tools: [
{
id: 'drawio',
name: 'Drawio',
url: 'https://drawio.virtheart.com',
icon: 'ph:flow-arrow-duotone',
color: 'from-orange-50/50 to-amber-100/50',
descZh: '强大的在线图表绘制工具,支持流程图、UML、网络拓扑等。',
descEn: 'Powerful online diagramming tool for flowcharts, UML, and network topologies.',
},
{
id: 'excalidraw',
name: 'Excalidraw',
url: 'https://excalidraw.virtheart.com',
icon: 'ph:pencil-circle-duotone',
color: 'from-purple-50/50 to-indigo-100/50',
descZh: '手绘风格的白板工具,轻松绘制草图和协作思考。',
descEn: 'Hand-drawn style whiteboard tool for easy sketching and collaborative thinking.',
},
{
id: 'itTools',
name: 'IT-Tools',
url: 'https://ittools.virtheart.com',
icon: 'ph:wrench-duotone',
color: 'from-blue-50/50 to-cyan-100/50',
descZh: '为开发人员和IT从业者提供的一站式实用工具集合。',
descEn: 'An all-in-one practical tool collection for developers and IT professionals.',
},
],
footer: {
title: {
zh: '雕琢视觉,塑造故事。\n让我们共创卓越作品!',
en: 'Crafting visuals. Shaping stories.\nLet\'s create great work together!',
},
newsletterTitle: { zh: '抢先获取最新资讯', en: 'Get the latest updates first' },
newsletterNote: { zh: '无广告干扰。仅提供精选更新。', en: 'No spam. Only curated updates.' },
copyright: { zh: '© 2026 北极新一工作室', en: '© 2026 ArcticNewOne Studio' },
},
seo: {
description: {
zh: '探索无限可能的现代化体验,欢迎来到 ArcticNewOne。',
en: 'Explore infinite possibilities and modern experiences. Welcome to ArcticNewOne.',
},
keywords: { zh: '北极新一,ArcticNewOne,设计,开发,品牌', en: 'ArcticNewOne,design,development,branding' },
},
}
/** 兼容旧引用的站点元信息子集(新代码请用 useSiteSettings) */
export const siteConfig = {
brand: defaultSettings.site.name,
brandZh: defaultSettings.site.brand,
email: defaultSettings.contact.email,
infoEmail: defaultSettings.contact.infoEmail,
wechat: defaultSettings.contact.wechat,
copyright: defaultSettings.footer.copyright.zh,
socials: defaultSettings.socials,
}
+8 -3
View File
@@ -1,8 +1,10 @@
<script setup lang="ts">
/**
* 后台管理布局:左侧固定深色侧边栏 + 右侧内容区。
* 不包含站点公共 Header/Footer;移动端侧栏收起为顶栏按钮。
* 由各后台页面通过 definePageMeta({ layout: 'admin' }) 启用。
* - 挂载全局 <AdminToast />,供后台各页统一反馈
* - 内容区统一内边距与最大宽度(居中)
* - 不包含站点公共 Header/Footer;移动端侧栏收起为顶栏按钮
* - 由各后台页面通过 definePageMeta({ layout: 'admin' }) 启用
*/
import { ref } from 'vue'
@@ -11,6 +13,9 @@ const sidebarOpen = ref(false)
<template>
<div class="min-h-screen bg-gray-50">
<!-- 全局 toast(Teleport 到 body) -->
<AdminToast />
<!-- 移动端顶栏 -->
<header
class="lg:hidden fixed top-0 inset-x-0 z-40 h-14 bg-black text-white flex items-center justify-between px-4 shadow-lg"
@@ -52,7 +57,7 @@ const sidebarOpen = ref(false)
<!-- 内容区 -->
<main class="lg:pl-64 pt-14 lg:pt-0 min-h-screen">
<div class="p-4 sm:p-6 lg:p-10 max-w-[1200px]">
<div class="mx-auto max-w-[1200px] px-4 sm:px-6 lg:px-10 py-6 lg:py-10">
<slot />
</div>
</main>
+516 -280
View File
@@ -1,259 +1,68 @@
<template>
<main class="page-container min-h-screen pt-32 pb-20 px-4 md:px-8 mx-auto max-w-[1200px]">
<!-- 未登录 -->
<div
v-if="!userStore.isAuthenticated"
class="max-w-md mx-auto mt-16 p-10 rounded-3xl bg-white border border-gray-100 shadow-xl text-center"
>
<div class="w-16 h-16 mx-auto rounded-full bg-gray-100 flex items-center justify-center mb-6">
<Icon name="ph:user-duotone" class="w-8 h-8 text-gray-400" />
</div>
<h1 class="text-2xl font-bold text-black mb-3">{{ t('account.title') }}</h1>
<p class="text-gray-500 mb-8">{{ t('auth.loginRequired') }}</p>
<button
@click="authModal.openLogin()"
class="px-8 py-3 rounded-full bg-black text-white font-semibold hover:bg-gray-800 transition-colors"
>
{{ t('auth.login') }}
</button>
</div>
<!-- 已登录 -->
<div v-else>
<div class="mb-10 text-center">
<img :src="userStore.avatar" :alt="userStore.user?.username" class="w-20 h-20 rounded-full object-cover mx-auto mb-4" />
<h1 class="text-3xl md:text-4xl font-bold text-black mb-2">{{ userStore.user?.username }}</h1>
<p class="text-gray-500">{{ userStore.user?.email }}</p>
</div>
<!-- 管理员入口 -->
<div v-if="userStore.user?.role === 'admin'" class="flex justify-center mb-6">
<NuxtLink
to="/admin"
class="inline-flex items-center gap-2 px-6 py-2.5 rounded-full bg-black text-white text-sm font-semibold hover:bg-gray-800 transition-colors"
>
<Icon name="ph:gear-six" class="w-4 h-4" />
{{ t('account.adminEntry') }}
</NuxtLink>
</div>
<!-- 页签 -->
<div class="flex justify-center gap-2 md:gap-3 mb-10 flex-wrap">
<button
v-for="tab in tabs"
:key="tab.key"
@click="switchTab(tab.key)"
class="px-5 py-2 rounded-full text-sm md:text-base font-semibold transition-all duration-300"
:class="activeTab === tab.key ? 'bg-black text-white shadow-lg' : 'bg-gray-100 text-gray-700 hover:bg-gray-200'"
>
{{ tab.label }}
</button>
</div>
<!-- 个人资料 -->
<section v-if="activeTab === 'profile'" class="max-w-lg mx-auto space-y-5">
<div class="p-6 rounded-2xl bg-white border border-gray-100 shadow-sm space-y-5">
<div>
<label class="block text-sm font-semibold text-gray-800 mb-2">{{ t('account.username') }}</label>
<input v-model="profileForm.username" type="text" class="w-full px-4 py-3 rounded-xl border border-gray-200 focus:border-black focus:ring-2 focus:ring-black/5 outline-none transition-all" />
</div>
<div>
<label class="block text-sm font-semibold text-gray-800 mb-2">{{ t('account.phone') }}</label>
<input v-model="profileForm.phone" type="tel" class="w-full px-4 py-3 rounded-xl border border-gray-200 focus:border-black focus:ring-2 focus:ring-black/5 outline-none transition-all" />
</div>
<div>
<label class="block text-sm font-semibold text-gray-800 mb-2">{{ t('account.email') }}</label>
<input :value="userStore.user?.email" type="email" disabled class="w-full px-4 py-3 rounded-xl border border-gray-200 bg-gray-50 text-gray-500 cursor-not-allowed" />
</div>
<div class="grid grid-cols-2 gap-4 text-sm text-gray-600">
<div>
<p class="text-gray-400 mb-1">{{ t('account.joinedAt') }}</p>
<p class="font-medium text-black">{{ formatDate(userStore.user?.createdAt) }}</p>
</div>
<div>
<p class="text-gray-400 mb-1">{{ t('account.role') }}</p>
<p class="font-medium text-black">
{{ userStore.user?.role === 'admin' ? t('account.roleAdmin') : t('account.roleUser') }}
</p>
</div>
</div>
<p v-if="saveMessage" class="text-sm" :class="saveFailed ? 'text-red-600' : 'text-green-600'">{{ saveMessage }}</p>
<button
@click="saveProfile"
:disabled="saving"
class="w-full py-3 rounded-xl bg-black text-white font-semibold flex items-center justify-center gap-2 transition-colors disabled:opacity-50"
>
<Icon v-if="saving" name="ph:circle-notch" class="w-5 h-5 animate-spin" />
{{ saving ? t('account.saving') : t('account.save') }}
</button>
</div>
<!-- 修改密码 -->
<form class="p-6 rounded-2xl bg-white border border-gray-100 shadow-sm space-y-5" @submit.prevent="changePassword">
<h3 class="text-lg font-bold text-black">{{ t('account.changePassword.title') }}</h3>
<div>
<label class="block text-sm font-semibold text-gray-800 mb-2">{{ t('account.changePassword.currentPassword') }}</label>
<input
v-model="pwForm.currentPassword"
type="password"
autocomplete="current-password"
class="w-full px-4 py-3 rounded-xl border border-gray-200 focus:border-black focus:ring-2 focus:ring-black/5 outline-none transition-all"
/>
</div>
<div>
<label class="block text-sm font-semibold text-gray-800 mb-2">{{ t('account.changePassword.newPassword') }}</label>
<input
v-model="pwForm.newPassword"
type="password"
autocomplete="new-password"
class="w-full px-4 py-3 rounded-xl border border-gray-200 focus:border-black focus:ring-2 focus:ring-black/5 outline-none transition-all"
/>
</div>
<div>
<label class="block text-sm font-semibold text-gray-800 mb-2">{{ t('account.changePassword.confirmPassword') }}</label>
<input
v-model="pwForm.confirmPassword"
type="password"
autocomplete="new-password"
class="w-full px-4 py-3 rounded-xl border border-gray-200 focus:border-black focus:ring-2 focus:ring-black/5 outline-none transition-all"
/>
</div>
<p v-if="pwMessage" class="text-sm" :class="pwFailed ? 'text-red-600' : 'text-green-600'">{{ pwMessage }}</p>
<button
type="submit"
:disabled="pwSaving"
class="w-full py-3 rounded-xl bg-black text-white font-semibold flex items-center justify-center gap-2 transition-colors disabled:opacity-50"
>
<Icon v-if="pwSaving" name="ph:circle-notch" class="w-5 h-5 animate-spin" />
{{ pwSaving ? t('account.changePassword.saving') : t('account.changePassword.submit') }}
</button>
</form>
<!-- 删除账号(危险区) -->
<div class="p-6 rounded-2xl bg-white border border-red-200 shadow-sm space-y-5">
<h3 class="text-lg font-bold text-red-600">{{ t('account.deleteAccount.title') }}</h3>
<p class="text-sm text-gray-500">{{ t('account.deleteAccount.hint') }}</p>
<div>
<input
v-model="deletePassword"
type="password"
autocomplete="current-password"
:placeholder="t('account.deleteAccount.passwordPlaceholder')"
@keydown.enter.prevent
class="w-full px-4 py-3 rounded-xl border border-gray-200 focus:border-red-500 focus:ring-2 focus:ring-red-500/5 outline-none transition-all"
/>
</div>
<p v-if="deleteMessage" class="text-sm" :class="deleteFailed ? 'text-red-600' : 'text-green-600'">{{ deleteMessage }}</p>
<button
@click="confirmDeleteAccount"
:disabled="deleting"
class="w-full py-3 rounded-xl bg-red-600 text-white font-semibold flex items-center justify-center gap-2 transition-colors hover:bg-red-700 disabled:opacity-50"
>
<Icon v-if="deleting" name="ph:circle-notch" class="w-5 h-5 animate-spin" />
{{ t('account.deleteAccount.confirmButton') }}
</button>
</div>
</section>
<!-- 我的收藏 -->
<section v-if="activeTab === 'favorites'" class="max-w-3xl mx-auto">
<p v-if="!favorites.length" class="text-center text-gray-500 py-12">{{ t('account.emptyFavorites') }}</p>
<div v-else class="grid grid-cols-1 sm:grid-cols-2 gap-5">
<div
v-for="fav in favorites"
:key="fav.slug"
class="group rounded-2xl overflow-hidden bg-white border border-gray-100 shadow-sm hover:shadow-xl transition-all duration-300"
>
<NuxtLink :to="`/work/${fav.slug}`" class="block relative aspect-[4/3] overflow-hidden">
<img :src="fav.image" :alt="favTitle(fav)" class="w-full h-full object-cover transition-transform duration-500 group-hover:scale-105" />
</NuxtLink>
<div class="p-5 flex items-center justify-between">
<NuxtLink :to="`/work/${fav.slug}`" class="font-bold text-black group-hover:text-gray-600 transition-colors">
{{ favTitle(fav) }}
</NuxtLink>
<button
@click="removeFavorite(fav.slug)"
class="w-9 h-9 rounded-full bg-gray-50 text-gray-500 hover:bg-red-50 hover:text-red-600 flex items-center justify-center transition-colors"
aria-label="unfavorite"
>
<Icon name="ph:bookmark-simple-fill" class="w-4 h-4" />
</button>
</div>
</div>
</div>
</section>
<!-- 我的评论 -->
<section v-if="activeTab === 'comments'" class="max-w-2xl mx-auto space-y-4">
<p v-if="!myComments.length" class="text-center text-gray-500 py-12">{{ t('account.emptyComments') }}</p>
<div
v-for="comment in myComments"
:key="comment.id"
class="p-5 rounded-2xl bg-white border border-gray-100 shadow-sm"
>
<div class="flex items-center justify-between mb-2">
<NuxtLink :to="`/news/${comment.newsSlug}`" class="text-sm font-semibold text-black hover:text-gray-600">
#{{ comment.newsSlug }}
</NuxtLink>
<span class="text-xs text-gray-400">{{ formatDate(comment.createdAt) }}</span>
</div>
<p class="text-gray-700 text-sm break-words">{{ comment.content }}</p>
</div>
</section>
</div>
</main>
</template>
<script setup lang="ts">
import { nextTick, onBeforeUnmount, onMounted, reactive, ref, computed } from 'vue'
/**
* 个人中心(全新设计)。
* - 顶部深色渐变资料卡:头像 / 用户名 / 邮箱 / 角色徽标 / 注册时间 / 三项统计
* - pill 页签:profile / favorites / comments
* - profile:资料编辑、修改密码、删除账号(危险区 + 确认弹窗)
* - favorites:作品封面网格卡(封面 / 标题 / 年份 / 分类 / 取消收藏)
* - comments:评论卡片列表
* - 数据:favorites = /api/favorites + /api/work;comments = /api/account/comments
*/
import { computed, nextTick, onBeforeUnmount, onMounted, reactive, ref } from 'vue'
import { useI18n } from 'vue-i18n'
import { useSeoMeta } from '#imports'
import gsap from 'gsap'
import { useUserStore } from '~/stores/user'
import { useAuthModalStore } from '~/stores/authModal'
import { useToastStore } from '~/stores/toast'
import { useApiError } from '~/composables/useApiError'
const { t, locale } = useI18n()
const userStore = useUserStore()
const authModal = useAuthModalStore()
const toast = useToastStore()
const apiError = useApiError()
useSeoMeta({
title: () => t('account.title'),
})
useSeoMeta({ title: () => t('account.title') })
const tabs = computed(() => {
const list: Array<{ key: string; label: string }> = [
{ key: 'profile', label: t('account.profile') },
{ key: 'favorites', label: t('account.favorites') },
{ key: 'comments', label: t('account.comments') },
]
return list
})
const activeTab = ref('profile')
const switchTab = (key: string) => {
activeTab.value = key
if (key === 'favorites') loadFavorites()
if (key === 'comments') loadComments()
}
const isAdmin = computed(() => userStore.user?.role === 'admin')
const formatDate = (raw?: string) => {
if (!raw) return ''
const d = new Date(String(raw).replace(' ', 'T') + 'Z')
if (Number.isNaN(d.getTime())) return raw
return new Intl.DateTimeFormat(locale.value === 'zh' ? 'zh-CN' : 'en-US', {
year: 'numeric',
month: 'short',
day: 'numeric',
}).format(d)
const loc = locale.value === 'zh' ? 'zh-CN' : 'en-US'
return new Intl.DateTimeFormat(loc, { year: 'numeric', month: 'short', day: 'numeric' }).format(d)
}
// ---- 个人资料 ----
// 统计卡「加入于」用紧凑格式(仅年月)
const formatMonth = (raw?: string) => {
if (!raw) return ''
const d = new Date(String(raw).replace(' ', 'T') + 'Z')
if (Number.isNaN(d.getTime())) return formatDate(raw)
const loc = locale.value === 'zh' ? 'zh-CN' : 'en-US'
return new Intl.DateTimeFormat(loc, { year: 'numeric', month: 'short' }).format(d)
}
/* ---------- 页签 ---------- */
const activeTab = ref('profile')
const tabs = computed(() => [
{ key: 'profile', label: t('account.profile'), count: null as number | null },
{ key: 'favorites', label: t('account.favorites'), count: favorites.value.length },
{ key: 'comments', label: t('account.comments'), count: myComments.value.length },
])
const switchTab = (key: string) => {
if (key === activeTab.value) return
activeTab.value = key
if (key === 'favorites') loadFavorites()
if (key === 'comments') loadComments()
}
/* ---------- 个人资料 ---------- */
const profileForm = reactive({ username: '', phone: '' })
const saving = ref(false)
const saveMessage = ref('')
const saveFailed = ref(false)
const profileSaving = ref(false)
const initProfileForm = () => {
profileForm.username = userStore.user?.username ?? ''
@@ -261,94 +70,114 @@ const initProfileForm = () => {
}
const saveProfile = async () => {
saving.value = true
saveMessage.value = ''
saveFailed.value = false
profileSaving.value = true
const result = await userStore.updateProfile({
username: profileForm.username,
phone: profileForm.phone,
})
profileSaving.value = false
if (result.success) {
saveMessage.value = t('account.saved')
toast.success(t('account.saved'))
} else {
saveFailed.value = true
saveMessage.value = apiError({ data: { code: result.code } })
toast.error(apiError({ data: { code: result.code } }))
}
saving.value = false
}
// ---- 修改密码 ----
/* ---------- 修改密码 ---------- */
const pwForm = reactive({ currentPassword: '', newPassword: '', confirmPassword: '' })
const pwSaving = ref(false)
const pwMessage = ref('')
const pwFailed = ref(false)
const pwError = ref('')
const changePassword = async () => {
pwMessage.value = ''
pwFailed.value = false
pwError.value = ''
if (pwForm.newPassword.length < 8) {
pwFailed.value = true
pwMessage.value = t('account.changePassword.tooShort')
pwError.value = t('account.changePassword.tooShort')
return
}
if (pwForm.newPassword !== pwForm.confirmPassword) {
pwFailed.value = true
pwMessage.value = t('account.changePassword.mismatch')
pwError.value = t('account.changePassword.mismatch')
return
}
pwSaving.value = true
try {
await $fetch('/api/auth/password', {
method: 'PATCH',
body: { currentPassword: pwForm.currentPassword, newPassword: pwForm.newPassword },
})
pwMessage.value = t('account.changePassword.success')
pwForm.currentPassword = ''
pwForm.newPassword = ''
pwForm.confirmPassword = ''
toast.success(t('account.changePassword.success'))
} catch (err) {
pwFailed.value = true
pwMessage.value =
pwError.value =
(err as any)?.data?.code === 'WRONG_PASSWORD'
? t('account.changePassword.wrongPassword')
: apiError(err)
}
: apiError(err, 'account.changePassword.failed')
} finally {
pwSaving.value = false
}
}
// ---- 删除账号 ----
/* ---------- 删除账号 ---------- */
const deletePassword = ref('')
const deleting = ref(false)
const deleteMessage = ref('')
const deleteFailed = ref(false)
const deleteError = ref('')
const deleteConfirmOpen = ref(false)
const confirmDeleteAccount = async () => {
if (!window.confirm(t('account.deleteAccount.confirmText'))) return
deleteMessage.value = ''
deleteFailed.value = false
const askDeleteAccount = () => {
deleteError.value = ''
if (!deletePassword.value.trim()) {
deleteError.value = t('account.deleteAccount.passwordPlaceholder')
return
}
deleteConfirmOpen.value = true
}
const doDeleteAccount = async () => {
deleting.value = true
try {
await $fetch('/api/auth/me', { method: 'DELETE', body: { password: deletePassword.value } })
deleteConfirmOpen.value = false
toast.success(t('account.deleteAccount.success'))
await userStore.logout()
await navigateTo('/')
} catch (err) {
deleteFailed.value = true
deleteMessage.value =
deleteConfirmOpen.value = false
deleteError.value =
(err as any)?.data?.code === 'WRONG_PASSWORD'
? t('account.deleteAccount.wrongPassword')
: apiError(err)
}
} finally {
deleting.value = false
}
}
// ---- 收藏 ----
interface FavedWork { slug: string; titleZh: string; titleEn: string; image: string | null }
/* ---------- 我的收藏 ---------- */
interface FavedWork {
slug: string
titleZh: string
titleEn: string
image: string | null
year: string
category: string
}
const favorites = ref<FavedWork[]>([])
const favLoading = ref(false)
const favLoaded = ref(false)
const favTitle = (w: FavedWork) => (locale.value === 'zh' ? w.titleZh : w.titleEn)
const CATEGORY_KEYS: Record<string, string> = {
webDesign: 'webDesign',
branding: 'branding',
development: 'development',
}
const categoryLabel = (cat: string) =>
CATEGORY_KEYS[cat] ? t(`work.categories.${CATEGORY_KEYS[cat]}`) : cat
const loadFavorites = async () => {
if (favLoaded.value) return
favLoading.value = true
try {
const [favRes, workRes] = await Promise.all([
$fetch<{ slugs: string[] }>('/api/favorites'),
@@ -356,47 +185,454 @@ const loadFavorites = async () => {
])
const bySlug = new Map(workRes.works.map((w) => [w.slug, w]))
favorites.value = favRes.slugs.map((s) => bySlug.get(s)).filter(Boolean) as FavedWork[]
favLoaded.value = true
} catch (err) {
console.error('load favorites error:', err)
} finally {
favLoading.value = false
}
}
const removeFavorite = async (slug: string) => {
try {
await $fetch('/api/favorites', { method: 'DELETE', body: { workSlug: slug } })
favorites.value = favorites.value.filter((f) => f.slug !== slug)
toast.success(t('favorites.remove'))
} catch (err) {
console.error('remove favorite error:', err)
toast.error(apiError(err))
}
}
// ---- 我的评论 ----
const myComments = ref<Array<{ id: number; newsSlug: string; content: string; createdAt: string }>>([])
/* ---------- 我的评论 ---------- */
interface MyComment {
id: number
newsSlug: string
content: string
createdAt: string
}
const myComments = ref<MyComment[]>([])
const commentLoading = ref(false)
const commentsLoaded = ref(false)
const loadComments = async () => {
if (commentsLoaded.value) return
commentLoading.value = true
try {
const data = await $fetch<{ comments: Array<{ id: number; newsSlug: string; content: string; createdAt: string }> }>('/api/account/comments')
const data = await $fetch<{ comments: MyComment[] }>('/api/account/comments')
myComments.value = data.comments
commentsLoaded.value = true
} catch (err) {
console.error('load comments error:', err)
} finally {
commentLoading.value = false
}
}
// ---- 页面进场动画 ----
/* ---------- 页面入场动画 ---------- */
const mainRef = ref<HTMLElement | null>(null)
let ctx: gsap.Context | null = null
const runIntro = () => {
ctx?.revert()
if (!mainRef.value) return
ctx = gsap.context(() => {
const targets = gsap.utils.toArray<HTMLElement>('[data-animate]', mainRef.value)
if (!targets.length) return
gsap.set(targets, { autoAlpha: 0, y: 24 })
gsap.to(targets, { autoAlpha: 1, y: 0, duration: 0.7, ease: 'power3.out', stagger: 0.1 })
}, mainRef.value)
}
onMounted(async () => {
await nextTick()
initProfileForm()
ctx = gsap.context(() => {
const targets = gsap.utils.toArray<HTMLElement>('[data-animate]', mainRef.value!)
if (targets.length) {
gsap.set(targets, { autoAlpha: 0, y: 24 })
gsap.to(targets, { autoAlpha: 1, y: 0, duration: 0.6, ease: 'power3.out', stagger: 0.08 })
runIntro()
// 统计数字依赖收藏/评论数据,异步补齐(入场动画不等待网络)
if (userStore.isAuthenticated) {
await Promise.all([loadFavorites(), loadComments()])
}
}, mainRef.value)
})
onBeforeUnmount(() => {
ctx?.revert()
})
</script>
<template>
<main
ref="mainRef"
class="page-container min-h-screen pt-24 md:pt-32 pb-24 px-4 md:px-8 mx-auto max-w-[1100px]"
>
<AdminToast />
<!-- 未登录 -->
<section
v-if="!userStore.isAuthenticated"
data-animate
class="max-w-md mx-auto mt-10 md:mt-16 p-10 rounded-3xl bg-white border border-gray-100 shadow-xl text-center"
>
<div class="w-16 h-16 mx-auto rounded-full bg-gray-100 flex items-center justify-center mb-6">
<Icon name="ph:user-duotone" class="w-8 h-8 text-gray-400" />
</div>
<h1 class="text-2xl font-bold text-black mb-3">{{ t('account.title') }}</h1>
<p class="text-gray-500 mb-8">{{ t('auth.loginRequired') }}</p>
<AdminButton size="lg" @click="authModal.openLogin()">
<Icon name="ph:sign-in" class="w-4 h-4" />
{{ t('auth.login') }}
</AdminButton>
</section>
<template v-else>
<!-- 顶部资料卡 -->
<section data-animate class="relative overflow-hidden rounded-3xl bg-black text-white shadow-xl">
<!-- 装饰渐变 -->
<div class="pointer-events-none absolute -top-24 -right-20 w-72 h-72 rounded-full bg-gradient-to-br from-indigo-500/40 via-fuchsia-500/20 to-transparent blur-3xl"></div>
<div class="pointer-events-none absolute -bottom-28 -left-16 w-80 h-80 rounded-full bg-gradient-to-tr from-cyan-400/30 to-blue-600/10 blur-3xl"></div>
<div class="relative p-6 md:p-10">
<!-- 身份信息 -->
<div class="flex flex-col md:flex-row md:items-center gap-5 md:gap-7">
<div class="flex-shrink-0">
<div class="w-20 h-20 md:w-24 md:h-24 rounded-2xl bg-white/10 border border-white/20 p-1.5">
<img
:src="userStore.avatar"
:alt="userStore.user?.username"
class="w-full h-full rounded-xl object-cover"
/>
</div>
</div>
<div class="flex-1 min-w-0">
<div class="flex items-center gap-3 flex-wrap">
<h1 class="text-2xl md:text-3xl font-bold tracking-tight">{{ userStore.user?.username }}</h1>
<AdminBadge v-if="isAdmin" tone="amber">
<Icon name="ph:shield-check" class="w-3 h-3" /> {{ t('account.roleAdmin') }}
</AdminBadge>
<AdminBadge v-else tone="blue">{{ t('account.roleUser') }}</AdminBadge>
</div>
<p class="mt-2 flex items-center gap-2 text-sm md:text-base text-white/70">
<Icon name="ph:envelope-simple" class="w-4 h-4 flex-shrink-0" />
<span class="truncate">{{ userStore.user?.email }}</span>
</p>
<p class="mt-1 flex items-center gap-2 text-xs md:text-sm text-white/50">
<Icon name="ph:calendar-dots" class="w-4 h-4 flex-shrink-0" />
{{ t('account.joinedAt') }} · {{ formatDate(userStore.user?.createdAt) }}
</p>
</div>
<!-- 管理员入口 -->
<div v-if="isAdmin" class="flex-shrink-0">
<NuxtLink
to="/admin"
class="inline-flex items-center gap-2 px-5 py-2.5 rounded-full bg-white text-black text-sm font-semibold hover:bg-white/90 transition-colors shadow-lg"
>
<Icon name="ph:gear-six" class="w-4 h-4" />
{{ t('account.adminEntry') }}
</NuxtLink>
</div>
</div>
<!-- 统计 -->
<div class="mt-8 grid grid-cols-3 gap-3 md:gap-5">
<div class="rounded-2xl bg-white/10 border border-white/10 px-3 py-4 md:py-5 text-center">
<p class="text-xl md:text-3xl font-bold leading-none">{{ favorites.length }}</p>
<p class="mt-2 text-[11px] md:text-xs text-white/60">{{ t('account.statFavorites') }}</p>
</div>
<div class="rounded-2xl bg-white/10 border border-white/10 px-3 py-4 md:py-5 text-center">
<p class="text-xl md:text-3xl font-bold leading-none">{{ myComments.length }}</p>
<p class="mt-2 text-[11px] md:text-xs text-white/60">{{ t('account.statComments') }}</p>
</div>
<div class="rounded-2xl bg-white/10 border border-white/10 px-3 py-4 md:py-5 text-center">
<p class="text-sm md:text-base font-bold leading-tight break-words">{{ formatMonth(userStore.user?.createdAt) }}</p>
<p class="mt-2 text-[11px] md:text-xs text-white/60">{{ t('account.statJoined') }}</p>
</div>
</div>
</div>
</section>
<!-- 页签 -->
<nav data-animate class="mt-8 md:mt-10 flex justify-center">
<div class="inline-flex p-1.5 rounded-full bg-white border border-gray-100 shadow-sm">
<button
v-for="tab in tabs"
:key="tab.key"
type="button"
@click="switchTab(tab.key)"
class="flex items-center gap-2 px-5 md:px-6 py-2.5 rounded-full text-sm font-semibold transition-all duration-300"
:class="activeTab === tab.key ? 'bg-black text-white shadow' : 'text-gray-500 hover:text-black'"
>
{{ tab.label }}
<span
v-if="tab.count != null"
class="text-[11px] leading-none px-1.5 py-1 rounded-full"
:class="activeTab === tab.key ? 'bg-white/20 text-white' : 'bg-gray-100 text-gray-500'"
>
{{ tab.count }}
</span>
</button>
</div>
</nav>
<!-- 内容区 -->
<div class="mt-8 md:mt-10">
<Transition name="panel" mode="out-in">
<!-- 个人资料 -->
<section v-if="activeTab === 'profile'" key="profile" class="space-y-6 max-w-2xl mx-auto">
<!-- 资料编辑 -->
<div class="rounded-3xl bg-white border border-gray-100 shadow-sm overflow-hidden">
<div class="px-6 py-4 border-b border-gray-100 flex items-center gap-3">
<div class="w-9 h-9 rounded-xl bg-gray-100 text-gray-600 flex items-center justify-center">
<Icon name="ph:user-focus" class="w-5 h-5" />
</div>
<div>
<h3 class="text-base font-bold text-black">{{ t('account.profile') }}</h3>
<p class="text-xs text-gray-400">个人基本信息</p>
</div>
</div>
<div class="p-6 space-y-5">
<AdminInput v-model="profileForm.username" :label="t('account.username')" required />
<AdminInput v-model="profileForm.phone" :label="t('account.phone')" type="tel" />
<AdminInput
:model-value="userStore.user?.email ?? ''"
:label="t('account.email')"
type="email"
disabled
/>
<div class="flex justify-end pt-1">
<AdminButton :loading="profileSaving" @click="saveProfile">
<Icon v-if="!profileSaving" name="ph:floppy-disk" class="w-4 h-4" />
{{ profileSaving ? t('account.saving') : t('account.save') }}
</AdminButton>
</div>
</div>
</div>
<!-- 修改密码 -->
<div class="rounded-3xl bg-white border border-gray-100 shadow-sm overflow-hidden">
<div class="px-6 py-4 border-b border-gray-100 flex items-center gap-3">
<div class="w-9 h-9 rounded-xl bg-gray-100 text-gray-600 flex items-center justify-center">
<Icon name="ph:key" class="w-5 h-5" />
</div>
<div>
<h3 class="text-base font-bold text-black">{{ t('account.changePassword.title') }}</h3>
<p class="text-xs text-gray-400">定期更换密码更安全</p>
</div>
</div>
<form class="p-6 space-y-5" @submit.prevent="changePassword">
<AdminInput
v-model="pwForm.currentPassword"
:label="t('account.changePassword.currentPassword')"
type="password"
required
/>
<AdminInput
v-model="pwForm.newPassword"
:label="t('account.changePassword.newPassword')"
type="password"
required
/>
<AdminInput
v-model="pwForm.confirmPassword"
:label="t('account.changePassword.confirmPassword')"
type="password"
required
/>
<p v-if="pwError" class="text-sm text-red-600">{{ pwError }}</p>
<div class="flex justify-end pt-1">
<AdminButton type="submit" variant="secondary" :loading="pwSaving">
<Icon v-if="!pwSaving" name="ph:lock-simple" class="w-4 h-4" />
{{ pwSaving ? t('account.changePassword.saving') : t('account.changePassword.submit') }}
</AdminButton>
</div>
</form>
</div>
<!-- 删除账号(危险区) -->
<div class="rounded-3xl border-2 border-red-100 bg-red-50/50 shadow-sm overflow-hidden">
<div class="px-6 py-4 border-b border-red-100 flex items-center gap-3">
<div class="w-9 h-9 rounded-xl bg-red-100 text-red-600 flex items-center justify-center">
<Icon name="ph:warning" class="w-5 h-5" />
</div>
<div>
<h3 class="text-base font-bold text-red-600">{{ t('account.deleteAccount.title') }}</h3>
<p class="text-xs text-red-400">危险操作</p>
</div>
</div>
<div class="p-6 space-y-5">
<p class="text-sm text-gray-600 leading-relaxed">{{ t('account.deleteAccount.hint') }}</p>
<AdminInput
v-model="deletePassword"
:label="t('auth.password')"
:placeholder="t('account.deleteAccount.passwordPlaceholder')"
type="password"
/>
<p v-if="deleteError" class="text-sm text-red-600">{{ deleteError }}</p>
<div class="flex justify-end pt-1">
<AdminButton variant="danger" :loading="deleting" @click="askDeleteAccount">
<Icon v-if="!deleting" name="ph:trash" class="w-4 h-4" />
{{ t('account.deleteAccount.confirmButton') }}
</AdminButton>
</div>
</div>
</div>
</section>
<!-- 我的收藏 -->
<section v-else-if="activeTab === 'favorites'" key="favorites">
<div v-if="favLoading" class="grid grid-cols-1 sm:grid-cols-2 lg:grid-cols-3 gap-5">
<div
v-for="i in 3"
:key="i"
class="rounded-2xl bg-white border border-gray-100 shadow-sm overflow-hidden animate-pulse"
>
<div class="aspect-[4/3] bg-gray-100"></div>
<div class="p-4 space-y-2">
<div class="h-3.5 rounded bg-gray-100 w-2/3"></div>
<div class="h-3 rounded bg-gray-100 w-1/3"></div>
</div>
</div>
</div>
<AdminEmptyState
v-else-if="!favorites.length"
icon="ph:bookmark-simple"
:title="t('account.emptyFavorites')"
/>
<div v-else class="grid grid-cols-1 sm:grid-cols-2 lg:grid-cols-3 gap-5">
<div
v-for="fav in favorites"
:key="fav.slug"
class="group rounded-2xl overflow-hidden bg-white border border-gray-100 shadow-sm hover:shadow-xl transition-all duration-300 hover:-translate-y-1"
>
<div class="relative aspect-[4/3] overflow-hidden bg-gray-50">
<NuxtLink :to="`/work/${fav.slug}`" class="block w-full h-full" :aria-label="favTitle(fav)">
<img
v-if="fav.image"
:src="fav.image"
:alt="favTitle(fav)"
class="w-full h-full object-cover transition-transform duration-500 group-hover:scale-105"
/>
<div v-else class="w-full h-full flex items-center justify-center">
<Icon name="ph:image" class="w-8 h-8 text-gray-300" />
</div>
</NuxtLink>
<span
v-if="fav.year"
class="absolute top-3 left-3 px-2.5 py-1 rounded-full bg-black/60 backdrop-blur-sm text-white text-xs font-semibold pointer-events-none"
>
{{ fav.year }}
</span>
<button
type="button"
@click="removeFavorite(fav.slug)"
class="absolute top-3 right-3 w-9 h-9 rounded-full bg-white/90 backdrop-blur-sm text-gray-600 hover:bg-red-500 hover:text-white flex items-center justify-center shadow transition-all duration-200"
:aria-label="t('favorites.remove')"
>
<Icon name="ph:bookmark-simple-fill" class="w-4 h-4" />
</button>
</div>
<div class="p-4">
<NuxtLink
:to="`/work/${fav.slug}`"
class="block font-bold text-black group-hover:text-gray-600 transition-colors truncate"
>
{{ favTitle(fav) }}
</NuxtLink>
<p class="mt-1.5 inline-flex items-center gap-1.5">
<span class="px-2 py-0.5 rounded-full bg-gray-100 text-gray-500 text-xs font-medium">
{{ categoryLabel(fav.category) }}
</span>
</p>
</div>
</div>
</div>
</section>
<!-- 我的评论 -->
<section v-else key="comments" class="max-w-2xl mx-auto">
<div v-if="commentLoading" class="space-y-4">
<div
v-for="i in 3"
:key="i"
class="rounded-2xl bg-white border border-gray-100 shadow-sm p-5 animate-pulse space-y-3"
>
<div class="h-3.5 rounded bg-gray-100 w-1/4"></div>
<div class="h-3 rounded bg-gray-100 w-full"></div>
<div class="h-3 rounded bg-gray-100 w-2/3"></div>
</div>
</div>
<AdminEmptyState
v-else-if="!myComments.length"
icon="ph:chat-circle-text"
:title="t('account.emptyComments')"
/>
<div v-else class="space-y-4">
<div
v-for="comment in myComments"
:key="comment.id"
class="rounded-2xl bg-white border border-gray-100 shadow-sm p-5 flex gap-4"
>
<div class="w-10 h-10 rounded-full bg-gray-100 text-gray-400 flex items-center justify-center flex-shrink-0">
<Icon name="ph:chat-circle-dots" class="w-5 h-5" />
</div>
<div class="min-w-0 flex-1">
<div class="flex items-center justify-between gap-3 flex-wrap">
<NuxtLink
:to="`/news/${comment.newsSlug}`"
class="inline-flex items-center gap-1.5 text-sm font-semibold text-black hover:text-gray-600 transition-colors"
>
<Icon name="ph:article" class="w-4 h-4 text-gray-400" />
#{{ comment.newsSlug }}
</NuxtLink>
<span class="text-xs text-gray-400">{{ formatDate(comment.createdAt) }}</span>
</div>
<p class="mt-2 text-gray-700 text-sm leading-relaxed break-words">{{ comment.content }}</p>
</div>
</div>
</div>
</section>
</Transition>
</div>
</template>
<!-- 删除账号确认 -->
<AdminModal
:open="deleteConfirmOpen"
:title="t('account.deleteAccount.title')"
@update:open="deleteConfirmOpen = $event"
>
<div class="flex items-start gap-3">
<div class="flex h-10 w-10 shrink-0 items-center justify-center rounded-full bg-red-50 text-red-600">
<Icon name="ph:warning-fill" class="w-5 h-5" />
</div>
<p class="text-sm text-gray-700 leading-relaxed">{{ t('account.deleteAccount.confirmText') }}</p>
</div>
<template #footer>
<AdminButton variant="secondary" size="sm" :disabled="deleting" @click="deleteConfirmOpen = false">
{{ t('account.deleteAccount.cancelButton') }}
</AdminButton>
<AdminButton variant="danger" size="sm" :loading="deleting" @click="doDeleteAccount">
{{ t('account.deleteAccount.confirmButton') }}
</AdminButton>
</template>
</AdminModal>
</main>
</template>
<style scoped>
.panel-enter-active,
.panel-leave-active {
transition: opacity 0.28s ease, transform 0.28s ease;
}
.panel-enter-from {
opacity: 0;
transform: translateY(14px);
}
.panel-leave-to {
opacity: 0;
transform: translateY(-8px);
}
</style>
+180 -166
View File
@@ -1,124 +1,13 @@
<template>
<section class="p-4 md:p-8 lg:p-10">
<header class="mb-8 flex flex-col sm:flex-row sm:items-center sm:justify-between gap-4">
<div class="flex items-center gap-3">
<div class="w-11 h-11 rounded-2xl bg-black text-white flex items-center justify-center flex-shrink-0">
<Icon name="ph:list-checks" class="w-6 h-6" />
</div>
<div>
<h1 class="text-2xl font-bold text-black leading-tight">操作日志</h1>
<p class="text-sm text-gray-500 mt-1">后台管理员的关键操作审计记录。</p>
</div>
</div>
<button
@click="clearLogs"
:disabled="!logs.length || clearing"
class="inline-flex items-center gap-2 px-5 py-2.5 rounded-full bg-black text-white text-sm font-semibold hover:bg-gray-800 disabled:opacity-40 disabled:cursor-not-allowed transition-colors flex-shrink-0"
title="清空全部操作日志"
>
<Icon v-if="clearing" name="ph:circle-notch" class="w-4 h-4 animate-spin" />
<Icon v-else name="ph:trash" class="w-4 h-4" />
清空日志
</button>
</header>
<!-- 操作反馈 -->
<div
v-if="flash"
class="mb-6 px-4 py-3 rounded-xl text-sm font-medium flex items-center gap-2"
:class="flashKind === 'ok' ? 'bg-green-50 text-green-700 border border-green-200' : 'bg-red-50 text-red-700 border border-red-200'"
>
<Icon :name="flashKind === 'ok' ? 'ph:check-circle' : 'ph:warning-circle'" class="w-4 h-4" />
{{ flash }}
</div>
<div class="flex items-center gap-2 mb-4">
<span class="text-sm text-gray-500">共 {{ total }} 条日志</span>
</div>
<!-- 加载中 -->
<div v-if="loading" class="py-24 flex flex-col items-center gap-3 text-gray-400">
<Icon name="ph:circle-notch" class="w-8 h-8 animate-spin" />
<p class="text-sm">加载中…</p>
</div>
<!-- 加载失败 -->
<div v-else-if="loadError" class="py-24 text-center">
<div class="inline-flex flex-col items-center gap-3 text-gray-500">
<Icon name="ph:warning-circle" class="w-8 h-8 text-red-500" />
<p class="text-sm">{{ loadError }}</p>
<button @click="loadLogs" class="px-5 py-2 rounded-full bg-black text-white text-sm font-semibold hover:bg-gray-800 transition-colors">
重试
</button>
</div>
</div>
<!-- 空态 -->
<div v-else-if="!logs.length" class="py-24 flex flex-col items-center gap-3 text-gray-400">
<Icon name="ph:list-checks" class="w-10 h-10" />
<p class="text-sm">暂无操作日志</p>
</div>
<!-- 日志表格 -->
<div v-else class="bg-white rounded-2xl border border-gray-100 shadow-sm overflow-hidden">
<div class="overflow-x-auto">
<table class="w-full text-sm">
<thead>
<tr class="text-left text-gray-500 border-b border-gray-100 bg-gray-50">
<th class="px-6 py-4 font-semibold text-xs uppercase tracking-wider whitespace-nowrap">时间</th>
<th class="px-6 py-4 font-semibold text-xs uppercase tracking-wider whitespace-nowrap">操作人</th>
<th class="px-6 py-4 font-semibold text-xs uppercase tracking-wider whitespace-nowrap">操作</th>
<th class="px-6 py-4 font-semibold text-xs uppercase tracking-wider">对象</th>
<th class="px-6 py-4 font-semibold text-xs uppercase tracking-wider">详情</th>
</tr>
</thead>
<tbody>
<tr
v-for="log in logs"
:key="log.id"
class="border-b border-gray-100 last:border-b-0 hover:bg-gray-50/70 transition-colors"
>
<td class="px-6 py-4 text-gray-500 text-xs whitespace-nowrap">{{ formatDate(log.createdAt) }}</td>
<td class="px-6 py-4 text-gray-700 whitespace-nowrap">{{ log.actor_name || 'system' }}</td>
<td class="px-6 py-4 whitespace-nowrap">
<span
class="inline-flex items-center px-2.5 py-1 rounded-full text-xs font-semibold"
:class="actionMeta(log.action).cls"
>
{{ actionMeta(log.action).label }}
</span>
</td>
<td class="px-6 py-4">
<code class="text-xs text-gray-600 bg-gray-50 border border-gray-100 rounded px-2 py-1">{{ log.target }}</code>
</td>
<td class="px-6 py-4 text-gray-600 max-w-[320px] md:max-w-md truncate" :title="log.detail || undefined">
{{ log.detail || '—' }}
</td>
</tr>
</tbody>
</table>
</div>
<!-- 加载更多 -->
<div v-if="logs.length < total" class="p-4 border-t border-gray-100 flex justify-center">
<button
@click="loadMore"
:disabled="loadingMore"
class="inline-flex items-center gap-2 px-6 py-2.5 rounded-full border border-gray-200 bg-white text-sm font-semibold text-gray-700 hover:bg-gray-100 disabled:opacity-60 transition-colors"
>
<Icon v-if="loadingMore" name="ph:circle-notch" class="w-4 h-4 animate-spin" />
{{ loadingMore ? '加载中…' : '加载更多' }}
</button>
</div>
</div>
</section>
</template>
<script setup lang="ts">
import { onMounted, ref } from 'vue'
/**
* 后台操作日志:后端分页 + 操作类型筛选 + 关键词检索(当前页过滤)+ 清空确认。
* - GET /api/admin/audit?page=&pageSize= → { logs, total, page, pageSize };DELETE /api/admin/audit
*/
import { computed, onMounted, ref, watch } from 'vue'
import { useToastStore } from '~/stores/toast'
definePageMeta({ middleware: 'admin', layout: 'admin' })
useSeoMeta({ title: '操作日志' })
useHead({ title: '操作日志' })
interface AuditLog {
id: number
@@ -129,41 +18,41 @@ interface AuditLog {
createdAt: string
}
const pageSize = 20
const page = ref(0)
const toast = useToastStore()
const ACTION_META: Record<string, { label: string; tone: 'green' | 'amber' | 'red' | 'blue' | 'gray' }> = {
create: { label: '新增', tone: 'green' },
update: { label: '更新', tone: 'amber' },
delete: { label: '删除', tone: 'red' },
upload: { label: '上传', tone: 'blue' },
clear: { label: '清空', tone: 'gray' },
}
const actionMeta = (action: string) =>
ACTION_META[action] ?? { label: action, tone: 'gray' as const }
const ACTION_OPTIONS = [
{ value: 'all', label: '全部操作' },
{ value: 'create', label: '新增' },
{ value: 'update', label: '更新' },
{ value: 'delete', label: '删除' },
{ value: 'upload', label: '上传' },
{ value: 'clear', label: '清空' },
]
/* ---------- 列表(后端分页) ---------- */
const pageSize = 15
const page = ref(1)
const total = ref(0)
const logs = ref<AuditLog[]>([])
const loading = ref(true)
const loadingMore = ref(false)
const loadError = ref('')
const ACTION_META: Record<string, { label: string; cls: string }> = {
create: { label: '新增', cls: 'bg-green-100 text-green-700' },
update: { label: '更新', cls: 'bg-amber-100 text-amber-700' },
delete: { label: '删除', cls: 'bg-red-100 text-red-700' },
upload: { label: '上传', cls: 'bg-blue-100 text-blue-700' },
clear: { label: '清空', cls: 'bg-gray-200 text-gray-600' },
}
const actionMeta = (action: string) => ACTION_META[action] ?? { label: action, cls: 'bg-gray-100 text-gray-700' }
const flash = ref('')
const flashKind = ref<'ok' | 'err'>('ok')
let flashTimer: ReturnType<typeof setTimeout> | null = null
const showFlash = (msg: string, kind: 'ok' | 'err' = 'ok') => {
flash.value = msg
flashKind.value = kind
if (flashTimer) clearTimeout(flashTimer)
flashTimer = setTimeout(() => {
flash.value = ''
}, 3000)
}
const loadLogs = async () => {
loading.value = true
loadError.value = ''
try {
const data = await $fetch<{ logs: AuditLog[]; total: number; page: number }>('/api/admin/audit', {
query: { page: 1, pageSize },
query: { page: page.value, pageSize },
})
logs.value = data.logs
total.value = data.total
@@ -176,35 +65,51 @@ const loadLogs = async () => {
}
}
const loadMore = async () => {
if (loadingMore.value || logs.value.length >= total.value) return
loadingMore.value = true
try {
const next = page.value + 1
const data = await $fetch<{ logs: AuditLog[]; total: number; page: number }>('/api/admin/audit', {
query: { page: next, pageSize },
})
logs.value.push(...data.logs)
page.value = data.page
} catch (err) {
console.error('load more audit error:', err)
showFlash('加载更多失败,请重试', 'err')
} finally {
loadingMore.value = false
}
onMounted(loadLogs)
const changePage = (p: number) => {
if (p === page.value) return
page.value = p
loadLogs()
}
/* ---------- 筛选 / 关键词(当前页过滤) ---------- */
const actionFilter = ref('all')
const keyword = ref('')
const filteredLogs = computed(() => {
const kw = keyword.value.trim().toLowerCase()
return logs.value.filter((log) => {
if (actionFilter.value !== 'all' && log.action !== actionFilter.value) return false
if (!kw) return true
return (
(log.actor_name || '').toLowerCase().includes(kw) ||
log.target.toLowerCase().includes(kw) ||
(log.detail || '').toLowerCase().includes(kw)
)
})
})
watch([actionFilter, keyword], () => {
if (page.value !== 1) {
page.value = 1
loadLogs()
}
})
/* ---------- 清空 ---------- */
const confirmClear = ref(false)
const clearing = ref(false)
const clearLogs = async () => {
if (!window.confirm('确定清空全部操作日志吗?此操作不可恢复。')) return
clearing.value = true
try {
await $fetch('/api/admin/audit', { method: 'DELETE' })
showFlash('日志已清空')
toast.success('日志已清空')
confirmClear.value = false
await loadLogs()
} catch (err) {
console.error('clear audit error:', err)
showFlash((err as any)?.data?.message || '清空失败,请重试', 'err')
} catch (err: any) {
toast.error(err?.data?.message || '清空失败,请重试')
} finally {
clearing.value = false
}
@@ -222,6 +127,115 @@ const formatDate = (raw?: string) => {
minute: '2-digit',
}).format(d)
}
onMounted(loadLogs)
</script>
<template>
<div>
<AdminPageHeader title="操作日志" subtitle="后台管理员的关键操作审计记录。">
<template #actions>
<AdminButton variant="danger" size="sm" :disabled="!total || clearing" :loading="clearing" @click="confirmClear = true">
<Icon name="ph:trash" class="w-4 h-4" /> 清空日志
</AdminButton>
</template>
</AdminPageHeader>
<!-- 统计 + 工具栏 -->
<div class="mb-4 flex flex-wrap items-center gap-x-4 gap-y-2">
<span class="text-sm text-gray-500">共 {{ total }} 条日志</span>
<span v-if="keyword" class="text-sm text-gray-400">· 当前页匹配 {{ filteredLogs.length }} 条</span>
</div>
<div class="mb-5 flex flex-col sm:flex-row gap-3">
<div class="relative flex-1 sm:max-w-xs">
<Icon name="ph:magnifying-glass" class="w-4 h-4 text-gray-400 absolute left-3.5 top-1/2 -translate-y-1/2 pointer-events-none" />
<input
v-model="keyword"
type="text"
placeholder="搜索操作人 / 对象 / 详情…"
class="w-full rounded-xl border border-gray-200 bg-white py-2.5 pl-10 pr-9 text-sm outline-none transition-all focus:border-black focus:ring-2 focus:ring-black/10"
/>
<button
v-if="keyword"
@click="keyword = ''"
class="absolute right-2.5 top-1/2 -translate-y-1/2 w-5 h-5 rounded-full text-gray-400 hover:text-gray-600 hover:bg-gray-100 flex items-center justify-center"
aria-label="清空筛选"
>
<Icon name="ph:x" class="w-3.5 h-3.5" />
</button>
</div>
<AdminSelect v-model="actionFilter" :options="ACTION_OPTIONS" class="w-full sm:w-40" />
</div>
<!-- 加载态 -->
<AdminCard v-if="loading">
<AdminSkeleton :rows="6" />
</AdminCard>
<!-- 错误态 -->
<AdminCard v-else-if="loadError">
<div class="py-10 text-center">
<Icon name="ph:warning-circle" class="w-10 h-10 text-gray-300 mx-auto mb-4" />
<p class="text-gray-500 mb-4">{{ loadError }}</p>
<AdminButton size="sm" @click="loadLogs">重新加载</AdminButton>
</div>
</AdminCard>
<!-- 空态 -->
<AdminEmptyState v-else-if="!logs.length" icon="ph:list-checks" title="暂无操作日志" description="后台管理操作会自动记录在这里。" />
<AdminEmptyState
v-else-if="!filteredLogs.length"
icon="ph:magnifying-glass"
title="当前页没有匹配的日志"
description="换个关键词或筛选条件,或在其他页试试。"
/>
<!-- 日志表格 -->
<template v-else>
<div class="rounded-2xl border border-gray-100 bg-white shadow-sm overflow-hidden">
<div class="overflow-x-auto">
<table class="w-full text-sm">
<thead>
<tr class="text-left text-gray-400 border-b border-gray-100 bg-gray-50">
<th class="px-5 py-4 font-semibold text-xs uppercase tracking-wider whitespace-nowrap">时间</th>
<th class="px-5 py-4 font-semibold text-xs uppercase tracking-wider whitespace-nowrap">操作人</th>
<th class="px-5 py-4 font-semibold text-xs uppercase tracking-wider whitespace-nowrap">操作</th>
<th class="px-5 py-4 font-semibold text-xs uppercase tracking-wider">对象</th>
<th class="px-5 py-4 font-semibold text-xs uppercase tracking-wider">详情</th>
</tr>
</thead>
<tbody class="divide-y divide-gray-50">
<tr v-for="log in filteredLogs" :key="log.id" class="hover:bg-gray-50/60 transition-colors">
<td class="px-5 py-4 text-gray-500 text-xs whitespace-nowrap">{{ formatDate(log.createdAt) }}</td>
<td class="px-5 py-4 text-gray-700 whitespace-nowrap">{{ log.actor_name || 'system' }}</td>
<td class="px-5 py-4 whitespace-nowrap">
<AdminBadge :tone="actionMeta(log.action).tone">{{ actionMeta(log.action).label }}</AdminBadge>
</td>
<td class="px-5 py-4">
<code class="text-xs text-gray-600 bg-gray-50 border border-gray-100 rounded px-2 py-1">{{ log.target }}</code>
</td>
<td class="px-5 py-4 text-gray-600 max-w-[320px] md:max-w-md truncate" :title="log.detail || undefined">
{{ log.detail || '—' }}
</td>
</tr>
</tbody>
</table>
</div>
</div>
<div class="mt-4">
<AdminPagination :total="total" :page="page" :page-size="pageSize" @page="changePage" />
</div>
</template>
<!-- 清空确认 -->
<AdminConfirm
:open="confirmClear"
:loading="clearing"
danger
message="确定清空全部操作日志吗?此操作不可恢复。"
@update:open="confirmClear = false"
@confirm="clearLogs"
/>
</div>
</template>
+262 -192
View File
@@ -1,148 +1,13 @@
<template>
<section class="p-4 md:p-8 lg:p-10">
<header class="mb-8">
<div class="flex items-center gap-3">
<div class="w-11 h-11 rounded-2xl bg-black text-white flex items-center justify-center flex-shrink-0">
<Icon name="ph:chat-text" class="w-6 h-6" />
</div>
<div>
<h1 class="text-2xl font-bold text-black leading-tight">评论管理</h1>
<p class="text-sm text-gray-500 mt-1">查看全站文章评论,按文章或内容关键词检索。</p>
</div>
</div>
</header>
<!-- 操作反馈 -->
<div
v-if="flash"
class="mb-6 px-4 py-3 rounded-xl text-sm font-medium flex items-center gap-2"
:class="flashKind === 'ok' ? 'bg-green-50 text-green-700 border border-green-200' : 'bg-red-50 text-red-700 border border-red-200'"
>
<Icon :name="flashKind === 'ok' ? 'ph:check-circle' : 'ph:warning-circle'" class="w-4 h-4" />
{{ flash }}
</div>
<!-- 搜索框 -->
<div class="relative max-w-md mb-4">
<Icon name="ph:magnifying-glass" class="w-5 h-5 text-gray-400 absolute left-4 top-1/2 -translate-y-1/2" />
<input
v-model="keyword"
type="text"
placeholder="按文章或内容关键词筛选…"
class="w-full pl-12 pr-10 py-3 rounded-full border border-gray-200 focus:border-black focus:ring-2 focus:ring-black/5 outline-none transition-all duration-300 text-sm"
/>
<button
v-if="keyword"
@click="keyword = ''"
class="w-6 h-6 rounded-full flex items-center justify-center text-gray-400 hover:text-gray-600 absolute right-3 top-1/2 -translate-y-1/2"
title="清空筛选"
>
<Icon name="ph:x" class="w-4 h-4" />
</button>
</div>
<div class="flex items-center gap-2 mb-4">
<span class="text-sm text-gray-500">共 {{ total }} 条评论</span>
<template v-if="keyword">
<span class="text-sm text-gray-400">· 匹配 {{ filteredComments.length }} 条</span>
</template>
</div>
<!-- 加载中 -->
<div v-if="loading" class="py-24 flex flex-col items-center gap-3 text-gray-400">
<Icon name="ph:circle-notch" class="w-8 h-8 animate-spin" />
<p class="text-sm">加载中…</p>
</div>
<!-- 加载失败 -->
<div v-else-if="loadError" class="py-24 text-center">
<div class="inline-flex flex-col items-center gap-3 text-gray-500">
<Icon name="ph:warning-circle" class="w-8 h-8 text-red-500" />
<p class="text-sm">{{ loadError }}</p>
<button @click="loadComments" class="px-5 py-2 rounded-full bg-black text-white text-sm font-semibold hover:bg-gray-800 transition-colors">
重试
</button>
</div>
</div>
<!-- 空态 -->
<div v-else-if="!comments.length" class="py-24 flex flex-col items-center gap-3 text-gray-400">
<Icon name="ph:chat-text" class="w-10 h-10" />
<p class="text-sm">暂无评论</p>
</div>
<div v-else-if="!filteredComments.length" class="py-24 flex flex-col items-center gap-3 text-gray-400">
<Icon name="ph:magnifying-glass" class="w-10 h-10" />
<p class="text-sm">没有匹配的评论</p>
</div>
<!-- 评论表格 -->
<div v-else class="bg-white rounded-2xl border border-gray-100 shadow-sm overflow-hidden">
<div class="overflow-x-auto">
<table class="w-full text-sm">
<thead>
<tr class="text-left text-gray-500 border-b border-gray-100 bg-gray-50">
<th class="px-6 py-4 font-semibold text-xs uppercase tracking-wider">文章</th>
<th class="px-6 py-4 font-semibold text-xs uppercase tracking-wider">作者</th>
<th class="px-6 py-4 font-semibold text-xs uppercase tracking-wider">内容</th>
<th class="px-6 py-4 font-semibold text-xs uppercase tracking-wider whitespace-nowrap">评论时间</th>
<th class="px-6 py-4 font-semibold text-xs uppercase tracking-wider text-right">操作</th>
</tr>
</thead>
<tbody>
<tr
v-for="c in filteredComments"
:key="c.id"
class="border-b border-gray-100 last:border-b-0 hover:bg-gray-50/70 transition-colors"
>
<td class="px-6 py-4 whitespace-nowrap">
<NuxtLink
:to="`/news/${c.newsSlug}`"
class="inline-flex items-center gap-1.5 font-semibold text-black hover:text-gray-600 transition-colors"
>
<Icon name="ph:article" class="w-4 h-4 text-gray-400" />
#{{ c.newsSlug }}
</NuxtLink>
</td>
<td class="px-6 py-4 text-gray-600 whitespace-nowrap">{{ c.username }}</td>
<td class="px-6 py-4">
<p class="text-gray-700 max-w-[300px] md:max-w-md truncate" :title="c.content">{{ c.content }}</p>
</td>
<td class="px-6 py-4 text-gray-500 text-xs whitespace-nowrap">{{ formatDate(c.createdAt) }}</td>
<td class="px-6 py-4">
<div class="flex items-center justify-end">
<button
@click="removeComment(c)"
class="w-8 h-8 rounded-full flex items-center justify-center text-gray-400 hover:bg-red-50 hover:text-red-600 transition-colors"
title="删除评论"
>
<Icon name="ph:trash" class="w-4 h-4" />
</button>
</div>
</td>
</tr>
</tbody>
</table>
</div>
<!-- 加载更多 -->
<div v-if="comments.length < total" class="p-4 border-t border-gray-100 flex justify-center">
<button
@click="loadMore"
:disabled="loadingMore"
class="inline-flex items-center gap-2 px-6 py-2.5 rounded-full border border-gray-200 bg-white text-sm font-semibold text-gray-700 hover:bg-gray-100 disabled:opacity-60 transition-colors"
>
<Icon v-if="loadingMore" name="ph:circle-notch" class="w-4 h-4 animate-spin" />
{{ loadingMore ? '加载中…' : '加载更多' }}
</button>
</div>
</div>
</section>
</template>
<script setup lang="ts">
import { computed, onMounted, ref } from 'vue'
/**
* 后台评论管理:后端分页 + 关键词检索(当前页过滤)+ 多选批量删除。
* - GET /api/admin/comments?page=&pageSize= → { comments, total, page, pageSize };DELETE /api/admin/comments/[id]
*/
import { computed, onMounted, ref, watch } from 'vue'
import { useToastStore } from '~/stores/toast'
definePageMeta({ middleware: 'admin', layout: 'admin' })
useSeoMeta({ title: '评论管理' })
useHead({ title: '评论管理' })
interface AdminComment {
id: number
@@ -152,41 +17,22 @@ interface AdminComment {
username: string
}
const pageSize = 20
const page = ref(0)
const toast = useToastStore()
/* ---------- 列表(后端分页) ---------- */
const pageSize = 15
const page = ref(1)
const total = ref(0)
const comments = ref<AdminComment[]>([])
const keyword = ref('')
const loading = ref(true)
const loadingMore = ref(false)
const loadError = ref('')
const filteredComments = computed(() => {
const kw = keyword.value.trim().toLowerCase()
if (!kw) return comments.value
return comments.value.filter(
(c) => c.newsSlug.toLowerCase().includes(kw) || c.content.toLowerCase().includes(kw),
)
})
const flash = ref('')
const flashKind = ref<'ok' | 'err'>('ok')
let flashTimer: ReturnType<typeof setTimeout> | null = null
const showFlash = (msg: string, kind: 'ok' | 'err' = 'ok') => {
flash.value = msg
flashKind.value = kind
if (flashTimer) clearTimeout(flashTimer)
flashTimer = setTimeout(() => {
flash.value = ''
}, 3000)
}
const loadComments = async () => {
loading.value = true
loadError.value = ''
try {
const data = await $fetch<{ comments: AdminComment[]; total: number; page: number }>('/api/admin/comments', {
query: { page: 1, pageSize },
query: { page: page.value, pageSize },
})
comments.value = data.comments
total.value = data.total
@@ -199,34 +45,105 @@ const loadComments = async () => {
}
}
const loadMore = async () => {
if (loadingMore.value || comments.value.length >= total.value) return
loadingMore.value = true
try {
const next = page.value + 1
const data = await $fetch<{ comments: AdminComment[]; total: number; page: number }>('/api/admin/comments', {
query: { page: next, pageSize },
})
comments.value.push(...data.comments)
page.value = data.page
} catch (err) {
console.error('load more comments error:', err)
showFlash('加载更多失败,请重试', 'err')
} finally {
loadingMore.value = false
onMounted(loadComments)
const changePage = (p: number) => {
if (p === page.value) return
page.value = p
loadComments()
}
/* ---------- 关键词(当前页过滤) ---------- */
const keyword = ref('')
const filteredComments = computed(() => {
const kw = keyword.value.trim().toLowerCase()
if (!kw) return comments.value
return comments.value.filter(
(c) => c.newsSlug.toLowerCase().includes(kw) || c.content.toLowerCase().includes(kw) || c.username.toLowerCase().includes(kw),
)
})
watch(keyword, () => {
if (page.value !== 1) {
page.value = 1
loadComments()
}
})
/* ---------- 多选 / 批量删除 ---------- */
const selected = ref<Set<number>>(new Set())
const allChecked = computed(
() => filteredComments.value.length > 0 && filteredComments.value.every((c) => selected.value.has(c.id)),
)
const toggleAll = () => {
if (allChecked.value) {
for (const c of filteredComments.value) selected.value.delete(c.id)
selected.value = new Set(selected.value)
} else {
const next = new Set(selected.value)
for (const c of filteredComments.value) next.add(c.id)
selected.value = next
}
}
const removeComment = async (c: AdminComment) => {
if (!window.confirm('确定删除这条评论吗?此操作不可恢复。')) return
const toggleOne = (id: number) => {
const next = new Set(selected.value)
if (next.has(id)) next.delete(id)
else next.add(id)
selected.value = next
}
const batchConfirmOpen = ref(false)
const batchDeleting = ref(false)
const doBatchDelete = async () => {
const ids = [...selected.value]
if (!ids.length) return
batchDeleting.value = true
let failed = 0
for (const id of ids) {
try {
await $fetch(`/api/admin/comments/${id}`, { method: 'DELETE' })
} catch (err: any) {
console.error('batch delete comment error:', err)
failed++
}
}
batchDeleting.value = false
batchConfirmOpen.value = false
selected.value = new Set()
if (failed === 0) {
toast.success(`已删除 ${ids.length} 条评论`)
} else {
toast.error(`删除 ${ids.length - failed} 条成功,${failed} 条失败`)
}
await loadComments()
}
/* ---------- 单条删除 ---------- */
const confirmDelete = ref<AdminComment | null>(null)
const deleting = ref(false)
const askDelete = (c: AdminComment) => {
confirmDelete.value = c
}
const doDelete = async () => {
const c = confirmDelete.value
if (!c) return
deleting.value = true
try {
await $fetch(`/api/admin/comments/${c.id}`, { method: 'DELETE' })
comments.value = comments.value.filter((x) => x.id !== c.id)
total.value = Math.max(0, total.value - 1)
showFlash('评论已删除')
} catch (err) {
console.error('delete comment error:', err)
showFlash((err as any)?.data?.message || '删除失败,请重试', 'err')
toast.success('评论已删除')
confirmDelete.value = null
selected.value.delete(c.id)
await loadComments()
} catch (err: any) {
toast.error((err as any)?.data?.message || '删除失败,请重试')
} finally {
deleting.value = false
}
}
@@ -242,6 +159,159 @@ const formatDate = (raw?: string) => {
minute: '2-digit',
}).format(d)
}
onMounted(loadComments)
</script>
<template>
<div>
<AdminPageHeader title="评论管理" subtitle="查看全站文章评论,按文章或内容关键词检索。">
<template #actions>
<AdminButton variant="secondary" size="sm" @click="loadComments">
<Icon name="ph:arrows-clockwise" class="w-4 h-4" /> 刷新
</AdminButton>
</template>
</AdminPageHeader>
<!-- 统计 + 工具栏 -->
<div class="mb-4 flex flex-wrap items-center gap-x-4 gap-y-2">
<span class="text-sm text-gray-500">共 {{ total }} 条评论</span>
<span v-if="keyword" class="text-sm text-gray-400">· 当前页匹配 {{ filteredComments.length }} 条</span>
<span v-if="selected.size" class="text-sm text-gray-400">· 已选 {{ selected.size }} 项</span>
</div>
<div class="mb-5 flex flex-wrap items-center gap-3">
<div class="relative flex-1 sm:max-w-xs">
<Icon name="ph:magnifying-glass" class="w-4 h-4 text-gray-400 absolute left-3.5 top-1/2 -translate-y-1/2 pointer-events-none" />
<input
v-model="keyword"
type="text"
placeholder="按文章或内容关键词筛选…"
class="w-full rounded-xl border border-gray-200 bg-white py-2.5 pl-10 pr-9 text-sm outline-none transition-all focus:border-black focus:ring-2 focus:ring-black/10"
/>
<button
v-if="keyword"
@click="keyword = ''"
class="absolute right-2.5 top-1/2 -translate-y-1/2 w-5 h-5 rounded-full text-gray-400 hover:text-gray-600 hover:bg-gray-100 flex items-center justify-center"
aria-label="清空筛选"
>
<Icon name="ph:x" class="w-3.5 h-3.5" />
</button>
</div>
<AdminButton variant="danger" size="sm" :disabled="!selected.size" @click="batchConfirmOpen = true">
<Icon name="ph:trash" class="w-4 h-4" /> 批量删除
</AdminButton>
</div>
<!-- 加载态 -->
<AdminCard v-if="loading">
<AdminSkeleton :rows="6" />
</AdminCard>
<!-- 错误态 -->
<AdminCard v-else-if="loadError">
<div class="py-10 text-center">
<Icon name="ph:warning-circle" class="w-10 h-10 text-gray-300 mx-auto mb-4" />
<p class="text-gray-500 mb-4">{{ loadError }}</p>
<AdminButton size="sm" @click="loadComments">重新加载</AdminButton>
</div>
</AdminCard>
<!-- 空态 -->
<AdminEmptyState v-else-if="!comments.length" icon="ph:chat-circle-text" title="暂无评论" description="还没有人发表评论。" />
<AdminEmptyState
v-else-if="!filteredComments.length"
icon="ph:magnifying-glass"
title="当前页没有匹配的评论"
description="换个关键词,或在其他页试试。"
/>
<!-- 评论表格 -->
<template v-else>
<div class="rounded-2xl border border-gray-100 bg-white shadow-sm overflow-hidden">
<div class="overflow-x-auto">
<table class="w-full text-sm">
<thead>
<tr class="text-left text-gray-400 border-b border-gray-100 bg-gray-50">
<th class="px-5 py-4 w-10">
<input
type="checkbox"
:checked="allChecked"
class="w-4 h-4 rounded border-gray-300 accent-black cursor-pointer"
@change="toggleAll"
/>
</th>
<th class="px-5 py-4 font-semibold text-xs uppercase tracking-wider">文章</th>
<th class="px-5 py-4 font-semibold text-xs uppercase tracking-wider">作者</th>
<th class="px-5 py-4 font-semibold text-xs uppercase tracking-wider">内容</th>
<th class="px-5 py-4 font-semibold text-xs uppercase tracking-wider whitespace-nowrap">评论时间</th>
<th class="px-5 py-4 font-semibold text-xs uppercase tracking-wider text-right">操作</th>
</tr>
</thead>
<tbody class="divide-y divide-gray-50">
<tr
v-for="c in filteredComments"
:key="c.id"
class="hover:bg-gray-50/60 transition-colors"
:class="selected.has(c.id) ? 'bg-gray-50/70' : ''"
>
<td class="px-5 py-4">
<input
type="checkbox"
:checked="selected.has(c.id)"
class="w-4 h-4 rounded border-gray-300 accent-black cursor-pointer"
@change="toggleOne(c.id)"
/>
</td>
<td class="px-5 py-4 whitespace-nowrap">
<NuxtLink
:to="`/news/${c.newsSlug}`"
class="inline-flex items-center gap-1.5 font-semibold text-black hover:text-gray-600 transition-colors"
>
<Icon name="ph:article" class="w-4 h-4 text-gray-400" />
#{{ c.newsSlug }}
</NuxtLink>
</td>
<td class="px-5 py-4 text-gray-600 whitespace-nowrap">{{ c.username }}</td>
<td class="px-5 py-4">
<p class="text-gray-700 max-w-[300px] md:max-w-md truncate" :title="c.content">{{ c.content }}</p>
</td>
<td class="px-5 py-4 text-gray-500 text-xs whitespace-nowrap">{{ formatDate(c.createdAt) }}</td>
<td class="px-5 py-4">
<div class="flex items-center justify-end">
<AdminButton size="sm" variant="ghost" @click="askDelete(c)">
<Icon name="ph:trash" class="w-4 h-4" />
</AdminButton>
</div>
</td>
</tr>
</tbody>
</table>
</div>
</div>
<div class="mt-4">
<AdminPagination :total="total" :page="page" :page-size="pageSize" @page="changePage" />
</div>
</template>
<!-- 批量删除确认 -->
<AdminConfirm
:open="batchConfirmOpen"
:loading="batchDeleting"
danger
:message="`确定删除已选的 ${selected.size} 条评论吗?此操作不可恢复。`"
@update:open="batchConfirmOpen = false"
@confirm="doBatchDelete"
/>
<!-- 单条删除确认 -->
<AdminConfirm
:open="!!confirmDelete"
:loading="deleting"
danger
:message="'确定删除这条评论吗?此操作不可恢复。'"
@update:open="confirmDelete = null"
@confirm="doDelete"
/>
</div>
</template>
+285 -147
View File
@@ -1,126 +1,13 @@
<template>
<section class="p-4 md:p-8 lg:p-10">
<header class="mb-8">
<div class="flex items-center gap-3">
<div class="w-11 h-11 rounded-2xl bg-black text-white flex items-center justify-center flex-shrink-0">
<Icon name="ph:envelope-simple-open" class="w-6 h-6" />
</div>
<div>
<h1 class="text-2xl font-bold text-black leading-tight">联系消息</h1>
<p class="text-sm text-gray-500 mt-1">访客通过联系表单提交的留言,关注送达状态。</p>
</div>
</div>
</header>
<!-- 操作反馈 -->
<div
v-if="flash"
class="mb-6 px-4 py-3 rounded-xl text-sm font-medium flex items-center gap-2"
:class="flashKind === 'ok' ? 'bg-green-50 text-green-700 border border-green-200' : 'bg-red-50 text-red-700 border border-red-200'"
>
<Icon :name="flashKind === 'ok' ? 'ph:check-circle' : 'ph:warning-circle'" class="w-4 h-4" />
{{ flash }}
</div>
<div class="flex items-center gap-2 mb-4">
<span class="text-sm text-gray-500">共 {{ contacts.length }} 条消息</span>
<span class="text-sm text-gray-400">· 已送达 {{ deliveredCount }} 条</span>
<span class="text-sm text-gray-400">· 未读 {{ unreadCount }} 条</span>
</div>
<!-- 加载中 -->
<div v-if="loading" class="py-24 flex flex-col items-center gap-3 text-gray-400">
<Icon name="ph:circle-notch" class="w-8 h-8 animate-spin" />
<p class="text-sm">加载中…</p>
</div>
<!-- 加载失败 -->
<div v-else-if="loadError" class="py-24 text-center">
<div class="inline-flex flex-col items-center gap-3 text-gray-500">
<Icon name="ph:warning-circle" class="w-8 h-8 text-red-500" />
<p class="text-sm">{{ loadError }}</p>
<button @click="loadContacts" class="px-5 py-2 rounded-full bg-black text-white text-sm font-semibold hover:bg-gray-800 transition-colors">
重试
</button>
</div>
</div>
<!-- 空态 -->
<div v-else-if="!contacts.length" class="py-24 flex flex-col items-center gap-3 text-gray-400">
<Icon name="ph:envelope-simple-open" class="w-10 h-10" />
<p class="text-sm">暂无联系消息</p>
</div>
<!-- 消息卡片列表 -->
<div v-else class="space-y-4">
<div
v-for="c in contacts"
:key="c.id"
class="bg-white rounded-2xl border border-gray-100 shadow-sm p-5 md:p-6 hover:shadow-md transition-shadow"
>
<div class="flex items-start justify-between gap-4">
<div class="flex items-center gap-3 min-w-0">
<div class="w-10 h-10 rounded-full bg-black text-white flex items-center justify-center font-bold flex-shrink-0">
{{ (c.name || '?').charAt(0) }}
</div>
<div class="min-w-0">
<div class="flex items-center gap-2 flex-wrap">
<h3 class="font-bold text-black">{{ c.name }}</h3>
<a :href="`mailto:${c.email}`" class="text-sm text-gray-500 hover:text-black transition-colors truncate">
{{ c.email }}
</a>
</div>
<p class="text-xs text-gray-400 mt-1">{{ formatDate(c.createdAt) }}</p>
</div>
</div>
<div class="flex items-center gap-2 flex-shrink-0">
<span
class="inline-flex items-center gap-1 px-2.5 py-1 rounded-full text-xs font-semibold"
:class="Number(c.delivered) === 1 ? 'bg-green-100 text-green-700' : 'bg-amber-100 text-amber-600'"
>
<Icon :name="Number(c.delivered) === 1 ? 'ph:check' : 'ph:clock'" class="w-3.5 h-3.5" />
{{ Number(c.delivered) === 1 ? '已送达' : '未送达' }}
</span>
<span
class="inline-flex items-center gap-1 px-2.5 py-1 rounded-full text-xs"
:class="Number(c.read) === 1 ? 'bg-gray-100 text-gray-500' : 'bg-black text-white font-bold'"
>
<Icon :name="Number(c.read) === 1 ? 'ph:envelope-open' : 'ph:envelope-simple'" class="w-3.5 h-3.5" />
{{ Number(c.read) === 1 ? '已读' : '未读' }}
</span>
<button
@click="toggleRead(c)"
:disabled="togglingId === c.id"
class="inline-flex items-center gap-1 px-2.5 py-1 rounded-full border text-xs font-semibold transition-colors disabled:opacity-50"
:class="Number(c.read) === 1 ? 'border-gray-200 text-gray-500 hover:bg-gray-100' : 'border-black text-black hover:bg-black hover:text-white'"
>
<Icon v-if="togglingId === c.id" name="ph:circle-notch" class="w-3.5 h-3.5 animate-spin" />
<Icon v-else :name="Number(c.read) === 1 ? 'ph:envelope-simple-open' : 'ph:check-circle'" class="w-3.5 h-3.5" />
{{ Number(c.read) === 1 ? '标为未读' : '标为已读' }}
</button>
<button
@click="removeContact(c)"
class="w-8 h-8 rounded-full flex items-center justify-center text-gray-400 hover:bg-red-50 hover:text-red-600 transition-colors"
title="删除消息"
>
<Icon name="ph:trash" class="w-4 h-4" />
</button>
</div>
</div>
<div class="mt-4 border-t border-gray-100 pt-4">
<p class="text-sm font-semibold text-gray-800">{{ c.subject }}</p>
<p class="mt-1.5 text-sm text-gray-600 whitespace-pre-line break-words">{{ c.message }}</p>
</div>
</div>
</div>
</section>
</template>
<script setup lang="ts">
import { computed, onMounted, ref } from 'vue'
/**
* 后台联系留言:列表 + 已读/未读筛选 + 已读切换 + 多选批量删除 + 前端分页。
* - GET /api/admin/contacts;PATCH /api/admin/contacts/[id] body { read: 0|1 };DELETE /api/admin/contacts/[id]
*/
import { computed, onMounted, ref, watch } from 'vue'
import { useToastStore } from '~/stores/toast'
definePageMeta({ middleware: 'admin', layout: 'admin' })
useSeoMeta({ title: '联系消息' })
useHead({ title: '联系留言' })
interface AdminContact {
id: number
@@ -133,25 +20,13 @@ interface AdminContact {
createdAt: string
}
const toast = useToastStore()
/* ---------- 列表 ---------- */
const contacts = ref<AdminContact[]>([])
const loading = ref(true)
const loadError = ref('')
const deliveredCount = computed(() => contacts.value.filter((c) => Number(c.delivered) === 1).length)
const unreadCount = computed(() => contacts.value.filter((c) => Number(c.read) !== 1).length)
const flash = ref('')
const flashKind = ref<'ok' | 'err'>('ok')
let flashTimer: ReturnType<typeof setTimeout> | null = null
const showFlash = (msg: string, kind: 'ok' | 'err' = 'ok') => {
flash.value = msg
flashKind.value = kind
if (flashTimer) clearTimeout(flashTimer)
flashTimer = setTimeout(() => {
flash.value = ''
}, 3000)
}
const loadContacts = async () => {
loading.value = true
loadError.value = ''
@@ -166,6 +41,49 @@ const loadContacts = async () => {
}
}
onMounted(loadContacts)
const deliveredCount = computed(() => contacts.value.filter((c) => Number(c.delivered) === 1).length)
const unreadCount = computed(() => contacts.value.filter((c) => Number(c.read) !== 1).length)
/* ---------- 筛选 / 搜索 / 分页 ---------- */
const readFilter = ref<'all' | 'read' | 'unread'>('all')
const keyword = ref('')
const filteredContacts = computed(() => {
const kw = keyword.value.trim().toLowerCase()
return contacts.value.filter((c) => {
if (readFilter.value === 'read' && Number(c.read) !== 1) return false
if (readFilter.value === 'unread' && Number(c.read) === 1) return false
if (!kw) return true
return (
c.name.toLowerCase().includes(kw) ||
c.email.toLowerCase().includes(kw) ||
c.subject.toLowerCase().includes(kw) ||
c.message.toLowerCase().includes(kw)
)
})
})
const pageSize = 10
const page = ref(1)
const totalPages = computed(() => Math.max(1, Math.ceil(filteredContacts.value.length / pageSize)))
const pagedContacts = computed(() => {
const p = Math.min(page.value, totalPages.value)
const start = (p - 1) * pageSize
return filteredContacts.value.slice(start, start + pageSize)
})
watch([readFilter, keyword], () => {
page.value = 1
})
const changePage = (p: number) => {
page.value = Math.min(Math.max(1, p), totalPages.value)
}
/* ---------- 已读切换 ---------- */
const togglingId = ref<number | null>(null)
const toggleRead = async (c: AdminContact) => {
const next = Number(c.read) === 1 ? 0 : 1
@@ -173,24 +91,88 @@ const toggleRead = async (c: AdminContact) => {
try {
await $fetch(`/api/admin/contacts/${c.id}`, { method: 'PATCH', body: { read: next } })
c.read = next
showFlash(next === 1 ? '已标记为已读' : '已标记为未读')
} catch (err) {
console.error('toggle contact read error:', err)
showFlash((err as any)?.data?.message || '操作失败,请重试', 'err')
toast.success(next === 1 ? '已标记为已读' : '已标记为未读')
} catch (err: any) {
toast.error(err?.data?.message || '操作失败,请重试')
} finally {
togglingId.value = null
}
}
const removeContact = async (c: AdminContact) => {
if (!window.confirm(`确定删除「${c.name}」的这条消息吗?此操作不可恢复。`)) return
/* ---------- 多选 / 批量删除 ---------- */
const selected = ref<Set<number>>(new Set())
const allChecked = computed(
() => pagedContacts.value.length > 0 && pagedContacts.value.every((c) => selected.value.has(c.id)),
)
const toggleAll = () => {
if (allChecked.value) {
for (const c of pagedContacts.value) selected.value.delete(c.id)
selected.value = new Set(selected.value)
} else {
const next = new Set(selected.value)
for (const c of pagedContacts.value) next.add(c.id)
selected.value = next
}
}
const toggleOne = (id: number) => {
const next = new Set(selected.value)
if (next.has(id)) next.delete(id)
else next.add(id)
selected.value = next
}
const batchConfirmOpen = ref(false)
const batchDeleting = ref(false)
const doBatchDelete = async () => {
const ids = [...selected.value]
if (!ids.length) return
batchDeleting.value = true
let failed = 0
for (const id of ids) {
try {
await $fetch(`/api/admin/contacts/${id}`, { method: 'DELETE' })
} catch (err: any) {
console.error('batch delete contact error:', err)
failed++
}
}
batchDeleting.value = false
batchConfirmOpen.value = false
selected.value = new Set()
if (failed === 0) {
toast.success(`已删除 ${ids.length} 条留言`)
} else {
toast.error(`删除 ${ids.length - failed} 条成功,${failed} 条失败`)
}
await loadContacts()
}
/* ---------- 单条删除 ---------- */
const confirmDelete = ref<AdminContact | null>(null)
const deleting = ref(false)
const askDelete = (c: AdminContact) => {
confirmDelete.value = c
}
const doDelete = async () => {
const c = confirmDelete.value
if (!c) return
deleting.value = true
try {
await $fetch(`/api/admin/contacts/${c.id}`, { method: 'DELETE' })
contacts.value = contacts.value.filter((x) => x.id !== c.id)
showFlash('消息已删除')
} catch (err) {
console.error('delete contact error:', err)
showFlash((err as any)?.data?.message || '删除失败,请重试', 'err')
selected.value.delete(c.id)
toast.success('留言已删除')
confirmDelete.value = null
} catch (err: any) {
toast.error(err?.data?.message || '删除失败,请重试')
} finally {
deleting.value = false
}
}
@@ -206,6 +188,162 @@ const formatDate = (raw?: string) => {
minute: '2-digit',
}).format(d)
}
onMounted(loadContacts)
</script>
<template>
<div>
<AdminPageHeader title="联系留言" subtitle="访客通过联系表单提交的留言,关注送达状态。">
<template #actions>
<AdminButton variant="secondary" size="sm" @click="loadContacts">
<Icon name="ph:arrows-clockwise" class="w-4 h-4" /> 刷新
</AdminButton>
</template>
</AdminPageHeader>
<!-- 统计 + 工具栏 -->
<div class="mb-4 flex flex-wrap items-center gap-x-4 gap-y-2">
<span class="text-sm text-gray-500">共 {{ contacts.length }} 条消息</span>
<span class="text-sm text-gray-400">· 已送达 {{ deliveredCount }} 条</span>
<span class="text-sm text-gray-400">· 未读 {{ unreadCount }} 条</span>
<span v-if="selected.size" class="text-sm text-gray-400">· 已选 {{ selected.size }} 项</span>
</div>
<div class="mb-5 flex flex-wrap items-center gap-3">
<div class="relative flex-1 sm:max-w-xs">
<Icon name="ph:magnifying-glass" class="w-4 h-4 text-gray-400 absolute left-3.5 top-1/2 -translate-y-1/2 pointer-events-none" />
<input
v-model="keyword"
type="text"
placeholder="搜索姓名 / 邮箱 / 主题 / 内容…"
class="w-full rounded-xl border border-gray-200 bg-white py-2.5 pl-10 pr-9 text-sm outline-none transition-all focus:border-black focus:ring-2 focus:ring-black/10"
/>
<button
v-if="keyword"
@click="keyword = ''"
class="absolute right-2.5 top-1/2 -translate-y-1/2 w-5 h-5 rounded-full text-gray-400 hover:text-gray-600 hover:bg-gray-100 flex items-center justify-center"
aria-label="清空筛选"
>
<Icon name="ph:x" class="w-3.5 h-3.5" />
</button>
</div>
<AdminSelect
v-model="readFilter"
:options="[
{ value: 'all', label: '全部状态' },
{ value: 'unread', label: '未读' },
{ value: 'read', label: '已读' },
]"
class="w-full sm:w-36"
/>
<AdminButton variant="danger" size="sm" :disabled="!selected.size" @click="batchConfirmOpen = true">
<Icon name="ph:trash" class="w-4 h-4" /> 批量删除
</AdminButton>
</div>
<!-- 加载态 -->
<AdminCard v-if="loading">
<AdminSkeleton :rows="6" />
</AdminCard>
<!-- 错误态 -->
<AdminCard v-else-if="loadError">
<div class="py-10 text-center">
<Icon name="ph:warning-circle" class="w-10 h-10 text-gray-300 mx-auto mb-4" />
<p class="text-gray-500 mb-4">{{ loadError }}</p>
<AdminButton size="sm" @click="loadContacts">重新加载</AdminButton>
</div>
</AdminCard>
<!-- 空态 -->
<AdminEmptyState
v-else-if="!contacts.length"
icon="ph:envelope-simple-open"
title="暂无联系消息"
description="访客通过联系表单提交的留言会出现在这里。"
/>
<AdminEmptyState
v-else-if="!filteredContacts.length"
icon="ph:magnifying-glass"
title="没有匹配的消息"
description="换个关键词或筛选条件试试。"
/>
<!-- 消息卡片列表 -->
<div v-else class="space-y-4">
<div
v-for="c in pagedContacts"
:key="c.id"
class="bg-white rounded-2xl border border-gray-100 shadow-sm p-5 md:p-6 transition-shadow"
:class="[selected.has(c.id) ? 'ring-2 ring-black/5 border-black/10' : 'hover:shadow-md']"
>
<div class="flex items-start justify-between gap-4">
<div class="flex items-center gap-3 min-w-0">
<input
type="checkbox"
:checked="selected.has(c.id)"
class="w-4 h-4 rounded border-gray-300 accent-black cursor-pointer flex-shrink-0 mt-1"
@change="toggleOne(c.id)"
/>
<div class="w-10 h-10 rounded-full bg-black text-white flex items-center justify-center font-bold flex-shrink-0">
{{ (c.name || '?').charAt(0) }}
</div>
<div class="min-w-0">
<div class="flex items-center gap-2 flex-wrap">
<h3 class="font-bold text-black">{{ c.name }}</h3>
<a :href="`mailto:${c.email}`" class="text-sm text-gray-500 hover:text-black transition-colors truncate">
{{ c.email }}
</a>
</div>
<p class="text-xs text-gray-400 mt-1">{{ formatDate(c.createdAt) }}</p>
</div>
</div>
<div class="flex items-center gap-2 flex-shrink-0">
<AdminBadge :tone="Number(c.delivered) === 1 ? 'green' : 'amber'">
<Icon :name="Number(c.delivered) === 1 ? 'ph:check' : 'ph:clock'" class="w-3.5 h-3.5" />
{{ Number(c.delivered) === 1 ? '已送达' : '未送达' }}
</AdminBadge>
<AdminBadge :tone="Number(c.read) === 1 ? 'gray' : 'black'">
<Icon :name="Number(c.read) === 1 ? 'ph:envelope-open' : 'ph:envelope-simple'" class="w-3.5 h-3.5" />
{{ Number(c.read) === 1 ? '已读' : '未读' }}
</AdminBadge>
<AdminButton size="sm" variant="secondary" :loading="togglingId === c.id" @click="toggleRead(c)">
{{ Number(c.read) === 1 ? '标为未读' : '标为已读' }}
</AdminButton>
<AdminButton size="sm" variant="ghost" @click="askDelete(c)">
<Icon name="ph:trash" class="w-4 h-4" />
</AdminButton>
</div>
</div>
<div class="mt-4 border-t border-gray-100 pt-4">
<p class="text-sm font-semibold text-gray-800">{{ c.subject }}</p>
<p class="mt-1.5 text-sm text-gray-600 whitespace-pre-line break-words">{{ c.message }}</p>
</div>
</div>
<div class="mt-4">
<AdminPagination :total="filteredContacts.length" :page="page" :page-size="pageSize" @page="changePage" />
</div>
</div>
<!-- 批量删除确认 -->
<AdminConfirm
:open="batchConfirmOpen"
:loading="batchDeleting"
danger
:message="`确定删除已选的 ${selected.size} 条留言吗?此操作不可恢复。`"
@update:open="batchConfirmOpen = false"
@confirm="doBatchDelete"
/>
<!-- 单条删除确认 -->
<AdminConfirm
:open="!!confirmDelete"
:loading="deleting"
danger
:message="`确定删除「${confirmDelete?.name}」的这条消息吗?此操作不可恢复。`"
@update:open="confirmDelete = null"
@confirm="doDelete"
/>
</div>
</template>
+179 -232
View File
@@ -1,14 +1,14 @@
<script setup lang="ts">
/**
* 后台动态管理:列表 + 新建/编辑表单。
* 后台动态管理:列表(搜索/分类/状态筛选 + 前端分页)+ 新建/编辑表单。
* - 列表来自 /api/admin/articles(含未发布)
* - 新建 POST /api/admin/articles;编辑 PATCH /api/admin/articles/[id];删除 DELETE /api/admin/articles/[id]
* - 正文为内容块编辑器(中英各一组)
*/
import { onMounted, reactive, ref } from 'vue'
import { computed, onMounted, reactive, ref, watch } from 'vue'
import { useToastStore } from '~/stores/toast'
definePageMeta({ middleware: 'admin', layout: 'admin' })
useHead({ title: '动态管理' })
interface Block {
@@ -35,6 +35,8 @@ interface Article {
updatedAt: string
}
const toast = useToastStore()
const CATEGORIES = [
{ value: 'insights', label: '行业洞察' },
{ value: 'projects', label: '项目动态' },
@@ -62,18 +64,50 @@ const loadArticles = async () => {
onMounted(loadArticles)
/* ---------- 提示 ---------- */
const message = ref('')
const messageType = ref<'success' | 'error'>('success')
let toastTimer: ReturnType<typeof setTimeout> | undefined
/* ---------- 搜索 / 筛选 / 分页 ---------- */
const keyword = ref('')
const categoryFilter = ref<'all' | Article['category']>('all')
const statusFilter = ref<'all' | 'published' | 'draft'>('all')
const toast = (text: string, type: 'success' | 'error' = 'success') => {
message.value = text
messageType.value = type
if (toastTimer) clearTimeout(toastTimer)
toastTimer = setTimeout(() => (message.value = ''), 3000)
const filteredArticles = computed(() => {
const kw = keyword.value.trim().toLowerCase()
return articles.value.filter((a) => {
if (categoryFilter.value !== 'all' && a.category !== categoryFilter.value) return false
if (statusFilter.value === 'published' && !a.published) return false
if (statusFilter.value === 'draft' && a.published) return false
if (!kw) return true
return (
a.titleZh.toLowerCase().includes(kw) ||
a.titleEn.toLowerCase().includes(kw) ||
a.slug.toLowerCase().includes(kw) ||
a.author.toLowerCase().includes(kw)
)
})
})
const pageSize = 10
const page = ref(1)
const totalPages = computed(() => Math.max(1, Math.ceil(filteredArticles.value.length / pageSize)))
const pagedArticles = computed(() => {
const p = Math.min(page.value, totalPages.value)
const start = (p - 1) * pageSize
return filteredArticles.value.slice(start, start + pageSize)
})
watch([keyword, categoryFilter, statusFilter], () => {
page.value = 1
})
const changePage = (p: number) => {
page.value = Math.min(Math.max(1, p), totalPages.value)
}
const headerSubtitle = computed(() => {
if (view.value === 'form') return editingId.value != null ? '编辑动态' : '新建动态'
return `共 ${articles.value.length} 篇动态`
})
/* ---------- 表单 ---------- */
const view = ref<'list' | 'form'>('list')
const editingId = ref<number | null>(null)
@@ -107,7 +141,7 @@ const openCreate = () => {
const openEdit = (a: Article) => {
if (a.id == null) {
toast('该条目缺少 id 字段,暂时无法编辑(后端待补)', 'error')
toast.error('该条目缺少 id 字段,暂时无法编辑(后端待补)')
return
}
editingId.value = a.id
@@ -165,10 +199,10 @@ const save = async () => {
}
if (editingId.value != null) {
await $fetch(`/api/admin/articles/${editingId.value}`, { method: 'PATCH', body: payload })
toast('动态已更新')
toast.success('动态已更新')
} else {
await $fetch('/api/admin/articles', { method: 'POST', body: payload })
toast('动态已创建')
toast.success('动态已创建')
}
await loadArticles()
view.value = 'list'
@@ -185,7 +219,7 @@ const deleting = ref(false)
const askDelete = (a: Article) => {
if (a.id == null) {
toast('该条目缺少 id 字段,暂时无法删除(后端待补)', 'error')
toast.error('该条目缺少 id 字段,暂时无法删除(后端待补)')
return
}
confirmDelete.value = a
@@ -197,11 +231,11 @@ const doDelete = async () => {
deleting.value = true
try {
await $fetch(`/api/admin/articles/${a.id}`, { method: 'DELETE' })
toast(`已删除「${a.titleZh}」`)
toast.success(`已删除「${a.titleZh}」`)
confirmDelete.value = null
await loadArticles()
} catch (err: any) {
toast(err?.data?.message || '删除失败', 'error')
toast.error(err?.data?.message || '删除失败')
} finally {
deleting.value = false
}
@@ -211,91 +245,104 @@ const doDelete = async () => {
<template>
<div>
<!-- 页头 -->
<div class="flex items-center justify-between gap-4 mb-8">
<div>
<h1 class="text-2xl md:text-3xl font-bold text-black tracking-tight">动态管理</h1>
<p v-if="view === 'list'" class="mt-1 text-sm text-gray-500">共 {{ articles.length }} 篇动态</p>
</div>
<button
v-if="view === 'list'"
type="button"
@click="openCreate"
class="inline-flex items-center gap-2 px-4 py-2 rounded-lg bg-black text-white text-sm font-semibold hover:bg-gray-800 transition-colors"
>
<AdminPageHeader title="动态管理" :subtitle="headerSubtitle">
<template #actions>
<AdminButton v-if="view === 'list'" size="sm" @click="openCreate">
<Icon name="ph:plus" class="w-4 h-4" /> 新建动态
</button>
<button
v-else
type="button"
@click="backToList"
class="inline-flex items-center gap-2 px-4 py-2 rounded-lg border border-gray-200 bg-white text-sm font-semibold text-gray-700 hover:bg-gray-100 transition-colors"
>
</AdminButton>
<AdminButton v-else size="sm" variant="secondary" @click="backToList">
<Icon name="ph:arrow-left" class="w-4 h-4" /> 返回列表
</button>
</div>
<!-- 提示 -->
<div
v-if="message"
class="mb-6 px-4 py-3 rounded-xl text-sm font-medium border"
:class="messageType === 'success' ? 'bg-green-50 border-green-200 text-green-700' : 'bg-red-50 border-red-200 text-red-700'"
>
{{ message }}
</div>
</AdminButton>
</template>
</AdminPageHeader>
<!-- ==================== 列表视图 ==================== -->
<template v-if="view === 'list'">
<!-- 加载态 -->
<div v-if="loading" class="space-y-3">
<div
v-for="i in 6"
:key="i"
class="rounded-2xl bg-white border border-gray-100 shadow-sm p-5 h-16 animate-pulse"
></div>
</div>
<!-- 错误态 -->
<div
v-else-if="error"
class="rounded-2xl bg-white border border-gray-100 shadow-sm p-10 text-center"
>
<Icon name="ph:warning-circle" class="w-10 h-10 text-gray-300 mx-auto mb-4" />
<p class="text-gray-500 mb-4">{{ error }}</p>
<!-- 工具栏 -->
<div class="mb-5 flex flex-col sm:flex-row gap-3">
<div class="relative flex-1 sm:max-w-xs">
<Icon name="ph:magnifying-glass" class="w-4 h-4 text-gray-400 absolute left-3.5 top-1/2 -translate-y-1/2 pointer-events-none" />
<input
v-model="keyword"
type="text"
placeholder="搜索标题 / slug / 作者…"
class="w-full rounded-xl border border-gray-200 bg-white py-2.5 pl-10 pr-9 text-sm outline-none transition-all focus:border-black focus:ring-2 focus:ring-black/10"
/>
<button
type="button"
@click="loadArticles"
class="px-5 py-2 rounded-lg bg-black text-white text-sm font-semibold hover:bg-gray-800 transition-colors"
v-if="keyword"
@click="keyword = ''"
class="absolute right-2.5 top-1/2 -translate-y-1/2 w-5 h-5 rounded-full text-gray-400 hover:text-gray-600 hover:bg-gray-100 flex items-center justify-center"
aria-label="清空筛选"
>
重新加载
<Icon name="ph:x" class="w-3.5 h-3.5" />
</button>
</div>
<!-- 空态 -->
<div
v-else-if="!articles.length"
class="rounded-2xl bg-white border border-gray-100 shadow-sm p-14 text-center"
>
<Icon name="ph:newspaper" class="w-10 h-10 text-gray-300 mx-auto mb-4" />
<p class="text-gray-500 mb-4">还没有动态,点击右上角「新建动态」创建第一篇</p>
<AdminSelect
v-model="categoryFilter"
:options="[
{ value: 'all', label: '全部分类' },
...CATEGORIES,
]"
class="w-full sm:w-40"
/>
<AdminSelect
v-model="statusFilter"
:options="[
{ value: 'all', label: '全部状态' },
{ value: 'published', label: '已发布' },
{ value: 'draft', label: '草稿' },
]"
class="w-full sm:w-36"
/>
</div>
<!-- 加载态 -->
<AdminCard v-if="loading">
<AdminSkeleton :rows="6" />
</AdminCard>
<!-- 错误态 -->
<AdminCard v-else-if="error">
<div class="py-10 text-center">
<Icon name="ph:warning-circle" class="w-10 h-10 text-gray-300 mx-auto mb-4" />
<p class="text-gray-500 mb-4">{{ error }}</p>
<AdminButton size="sm" @click="loadArticles">重新加载</AdminButton>
</div>
</AdminCard>
<!-- 空态 -->
<AdminEmptyState
v-else-if="!articles.length"
icon="ph:newspaper"
title="还没有动态"
description="点击右上角「新建动态」创建第一篇。"
/>
<AdminEmptyState
v-else-if="!filteredArticles.length"
icon="ph:magnifying-glass"
title="没有匹配的动态"
description="换个关键词或筛选条件试试。"
/>
<!-- 列表 -->
<div v-else class="rounded-2xl bg-white border border-gray-100 shadow-sm overflow-hidden">
<template v-else>
<div class="rounded-2xl border border-gray-100 bg-white shadow-sm overflow-hidden">
<div class="overflow-x-auto">
<table class="w-full text-sm">
<thead>
<tr class="text-left text-gray-400 border-b border-gray-100">
<th class="px-5 py-4 font-semibold">标题</th>
<th class="px-5 py-4 font-semibold">分类</th>
<th class="px-5 py-4 font-semibold">发布日期</th>
<th class="px-5 py-4 font-semibold">时长</th>
<th class="px-5 py-4 font-semibold">状态</th>
<th class="px-5 py-4 font-semibold text-right">操作</th>
<tr class="text-left text-gray-400 border-b border-gray-100 bg-gray-50">
<th class="px-5 py-4 font-semibold text-xs uppercase tracking-wider">标题</th>
<th class="px-5 py-4 font-semibold text-xs uppercase tracking-wider">分类</th>
<th class="px-5 py-4 font-semibold text-xs uppercase tracking-wider">发布日期</th>
<th class="px-5 py-4 font-semibold text-xs uppercase tracking-wider">时长</th>
<th class="px-5 py-4 font-semibold text-xs uppercase tracking-wider">状态</th>
<th class="px-5 py-4 font-semibold text-xs uppercase tracking-wider text-right">操作</th>
</tr>
</thead>
<tbody class="divide-y divide-gray-50">
<tr
v-for="a in articles"
v-for="a in pagedArticles"
:key="a.slug"
class="hover:bg-gray-50/60 transition-colors"
>
@@ -304,40 +351,27 @@ const doDelete = async () => {
<p class="text-xs text-gray-400 mt-0.5 font-mono">{{ a.slug }}</p>
</td>
<td class="px-5 py-4">
<span class="px-2.5 py-1 rounded-full bg-gray-100 text-gray-700 text-xs font-medium">
{{ catLabel(a.category) }}
</span>
<AdminBadge tone="gray">{{ catLabel(a.category) }}</AdminBadge>
</td>
<td class="px-5 py-4 text-gray-600 whitespace-nowrap">{{ a.date || '-' }}</td>
<td class="px-5 py-4 text-gray-600 whitespace-nowrap">{{ a.readTime }} 分钟</td>
<td class="px-5 py-4">
<AdminBadge :tone="a.published ? 'green' : 'amber'">
<span
class="px-2.5 py-1 rounded-full text-xs font-semibold inline-flex items-center gap-1"
:class="a.published ? 'bg-green-50 text-green-700' : 'bg-amber-50 text-amber-700'"
>
<span
class="w-1.5 h-1.5 rounded-full"
class="w-1.5 h-1.5 rounded-full inline-block"
:class="a.published ? 'bg-green-500' : 'bg-amber-500'"
></span>
{{ a.published ? '已发布' : '草稿' }}
</span>
</AdminBadge>
</td>
<td class="px-5 py-4">
<div class="flex items-center justify-end gap-2">
<button
type="button"
@click="openEdit(a)"
class="inline-flex items-center gap-1.5 px-3 py-1.5 rounded-lg bg-gray-100 text-gray-700 text-xs font-semibold hover:bg-gray-200 transition-colors"
>
<AdminButton size="sm" variant="secondary" @click="openEdit(a)">
<Icon name="ph:pencil-simple" class="w-3.5 h-3.5" /> 编辑
</button>
<button
type="button"
@click="askDelete(a)"
class="inline-flex items-center gap-1.5 px-3 py-1.5 rounded-lg bg-red-50 text-red-600 text-xs font-semibold hover:bg-red-100 transition-colors"
>
</AdminButton>
<AdminButton size="sm" variant="danger" @click="askDelete(a)">
<Icon name="ph:trash" class="w-3.5 h-3.5" /> 删除
</button>
</AdminButton>
</div>
</td>
</tr>
@@ -345,189 +379,102 @@ const doDelete = async () => {
</table>
</div>
</div>
<div class="mt-4">
<AdminPagination :total="filteredArticles.length" :page="page" :page-size="pageSize" @page="changePage" />
</div>
</template>
</template>
<!-- ==================== 表单视图 ==================== -->
<template v-else>
<div class="space-y-6 max-w-4xl">
<!-- 基本信息 -->
<section class="rounded-2xl bg-white border border-gray-100 shadow-sm p-5 md:p-6">
<h3 class="text-sm font-bold text-gray-900 mb-4 flex items-center gap-2">
<Icon name="ph:info" class="w-4 h-4 text-gray-400" /> 基本信息
</h3>
<AdminCard title="基本信息">
<div class="grid grid-cols-1 md:grid-cols-2 gap-5">
<div>
<label class="block text-sm font-semibold text-gray-800 mb-2">
slug<span class="text-red-500">*</span>
</label>
<input
<AdminInput
v-model="form.slug"
type="text"
label="slug"
required
placeholder="如 design-trends-2026"
class="w-full px-3 py-2.5 rounded-lg border border-gray-200 bg-white text-sm outline-none transition-all focus:border-black focus:ring-2 focus:ring-black/5 font-mono"
:error="formError && !/^[a-z0-9-]{2,64}$/.test(form.slug) ? 'slug 需为 2-64 位小写字母/数字/中划线' : ''"
/>
<p class="mt-1 text-xs text-gray-400">2-64 位小写字母 / 数字 / 中划线,用于前台链接</p>
</div>
<div>
<label class="block text-sm font-semibold text-gray-800 mb-2">分类</label>
<select
<AdminSelect
v-model="form.category"
class="w-full px-3 py-2.5 rounded-lg border border-gray-200 bg-white text-sm outline-none focus:border-black"
>
<option v-for="c in CATEGORIES" :key="c.value" :value="c.value">{{ c.label }}</option>
</select>
</div>
<div>
<label class="block text-sm font-semibold text-gray-800 mb-2">发布日期</label>
<input
v-model="form.date"
type="date"
class="w-full px-3 py-2.5 rounded-lg border border-gray-200 bg-white text-sm outline-none focus:border-black"
label="分类"
:options="CATEGORIES"
/>
</div>
<AdminInput v-model="form.date" type="date" label="发布日期" />
<div class="grid grid-cols-2 gap-5">
<div>
<label class="block text-sm font-semibold text-gray-800 mb-2">阅读时长(分钟)</label>
<input
v-model.number="form.readTime"
<AdminInput
:model-value="String(form.readTime)"
type="number"
min="1"
class="w-full px-3 py-2.5 rounded-lg border border-gray-200 bg-white text-sm outline-none focus:border-black"
label="阅读时长(分钟)"
@update:model-value="form.readTime = Number($event) || 1"
/>
</div>
<div>
<label class="block text-sm font-semibold text-gray-800 mb-2">作者</label>
<input
v-model="form.author"
type="text"
class="w-full px-3 py-2.5 rounded-lg border border-gray-200 bg-white text-sm outline-none focus:border-black"
/>
</div>
<AdminInput v-model="form.author" label="作者" />
</div>
<div class="md:col-span-2">
<label class="block text-sm font-semibold text-gray-800 mb-2">发布状态</label>
<button
type="button"
class="inline-flex items-center gap-3 group"
@click="form.published = !form.published"
>
<span
class="relative w-11 h-6 rounded-full transition-colors duration-300"
:class="form.published ? 'bg-black' : 'bg-gray-300'"
>
<span
class="absolute top-0.5 left-0.5 w-5 h-5 rounded-full bg-white shadow transition-transform duration-300"
:class="form.published ? 'translate-x-5' : ''"
></span>
</span>
<p class="block text-sm font-semibold text-gray-800 mb-1.5">发布状态</p>
<div class="flex items-center gap-3">
<AdminToggle v-model="form.published" />
<span class="text-sm" :class="form.published ? 'text-green-700 font-semibold' : 'text-gray-500'">
{{ form.published ? '已发布(前台可见)' : '草稿(前台隐藏)' }}
</span>
</button>
</div>
</div>
</section>
</div>
</AdminCard>
<!-- 标题与摘要 -->
<section class="rounded-2xl bg-white border border-gray-100 shadow-sm p-5 md:p-6">
<h3 class="text-sm font-bold text-gray-900 mb-4 flex items-center gap-2">
<Icon name="ph:text-aa" class="w-4 h-4 text-gray-400" /> 标题与摘要
</h3>
<AdminCard title="标题与摘要">
<div class="grid grid-cols-1 lg:grid-cols-2 gap-5">
<div class="space-y-4">
<div>
<label class="block text-sm font-semibold text-gray-800 mb-2">
中文标题<span class="text-red-500">*</span>
</label>
<input
v-model="form.titleZh"
type="text"
class="w-full px-3 py-2.5 rounded-lg border border-gray-200 bg-white text-sm outline-none transition-all focus:border-black focus:ring-2 focus:ring-black/5"
/>
</div>
<div>
<label class="block text-sm font-semibold text-gray-800 mb-2">中文摘要</label>
<textarea
v-model="form.excerptZh"
rows="3"
class="w-full px-3 py-2.5 rounded-lg border border-gray-200 bg-white text-sm outline-none transition-all focus:border-black focus:ring-2 focus:ring-black/5 resize-y"
></textarea>
</div>
<AdminInput v-model="form.titleZh" label="中文标题" required />
<AdminTextarea v-model="form.excerptZh" label="中文摘要" :rows="3" />
</div>
<div class="space-y-4">
<div>
<label class="block text-sm font-semibold text-gray-800 mb-2">
English Title<span class="text-red-500">*</span>
</label>
<input
v-model="form.titleEn"
type="text"
class="w-full px-3 py-2.5 rounded-lg border border-gray-200 bg-white text-sm outline-none transition-all focus:border-black focus:ring-2 focus:ring-black/5"
/>
</div>
<div>
<label class="block text-sm font-semibold text-gray-800 mb-2">English Excerpt</label>
<textarea
v-model="form.excerptEn"
rows="3"
class="w-full px-3 py-2.5 rounded-lg border border-gray-200 bg-white text-sm outline-none transition-all focus:border-black focus:ring-2 focus:ring-black/5 resize-y"
></textarea>
<AdminInput v-model="form.titleEn" label="English Title" required />
<AdminTextarea v-model="form.excerptEn" label="English Excerpt" :rows="3" />
</div>
</div>
</div>
</section>
</AdminCard>
<!-- 正文内容 -->
<section class="rounded-2xl bg-white border border-gray-100 shadow-sm p-5 md:p-6">
<h3 class="text-sm font-bold text-gray-900 mb-5 flex items-center gap-2">
<Icon name="ph:article" class="w-4 h-4 text-gray-400" /> 正文内容(中英各一组)
</h3>
<AdminCard title="正文内容(中英各一组)">
<div class="space-y-6">
<AdminBlockEditor v-model="form.contentZh" label="中文正文" />
<AdminBlockEditor v-model="form.contentEn" label="English Content" />
</div>
</section>
</AdminCard>
<!-- 封面图 -->
<section class="rounded-2xl bg-white border border-gray-100 shadow-sm p-5 md:p-6">
<h3 class="text-sm font-bold text-gray-900 mb-4 flex items-center gap-2">
<Icon name="ph:image" class="w-4 h-4 text-gray-400" /> 封面图
</h3>
<AdminCard title="封面图">
<AdminImageUpload v-model="form.image" label="封面图" />
</section>
</AdminCard>
<!-- 提交 -->
<div class="flex items-center justify-end gap-3">
<p v-if="formError" class="mr-auto text-sm text-red-600">{{ formError }}</p>
<button
type="button"
@click="backToList"
class="px-5 py-2.5 rounded-lg border border-gray-200 bg-white text-sm font-semibold text-gray-700 hover:bg-gray-100 transition-colors"
>
取消
</button>
<button
type="button"
:disabled="saving"
@click="save"
class="px-6 py-2.5 rounded-lg bg-black text-white text-sm font-semibold hover:bg-gray-800 transition-colors disabled:opacity-60 inline-flex items-center gap-2"
>
<Icon v-if="saving" name="ph:circle-notch" class="w-4 h-4 animate-spin" />
<AdminButton variant="secondary" @click="backToList">取消</AdminButton>
<AdminButton :loading="saving" @click="save">
{{ saving ? '保存中…' : editingId != null ? '保存修改' : '创建动态' }}
</button>
</AdminButton>
</div>
</div>
</template>
<!-- 删除确认 -->
<AdminConfirmDialog
<AdminConfirm
:open="!!confirmDelete"
:loading="deleting"
title="删除动态"
danger
:message="`确定要删除「${confirmDelete?.titleZh}」吗?该动态下的所有评论将一并删除,此操作不可撤销。`"
confirm-text="删除"
@update:open="confirmDelete = null"
@confirm="doDelete"
@cancel="confirmDelete = null"
/>
</div>
</template>
+260
View File
@@ -0,0 +1,260 @@
<script setup lang="ts">
/**
* 后台站点设置:分组表单,管理站点全局信息。
* - 加载 GET /api/admin/settings(返回合并默认值后的完整 SiteSettings)
* - 保存 PATCH /api/admin/settings,body { settings: <整体表单> }(按叶节点写库,未提供项不变)
* - 保存后前台 /api/settings 即时生效
*/
import { onMounted, reactive, ref } from 'vue'
import { defaultSettings, type SiteSettings } from '~/config/site'
import { useToastStore } from '~/stores/toast'
definePageMeta({ middleware: 'admin', layout: 'admin' })
useHead({ title: '站点设置' })
const toast = useToastStore()
const clone = <T>(v: T): T => JSON.parse(JSON.stringify(v))
/* ---------- 表单数据 ---------- */
// 先以默认值初始化,加载成功后整体覆盖为后端配置
const form = reactive<SiteSettings>(clone(defaultSettings))
const loading = ref(true)
const error = ref('')
const saving = ref(false)
const loadSettings = async () => {
loading.value = true
error.value = ''
try {
const data = await $fetch<SiteSettings>('/api/admin/settings')
Object.assign(form, clone(data))
} catch (err: any) {
error.value = err?.data?.message || '配置加载失败'
} finally {
loading.value = false
}
}
onMounted(loadSettings)
/* ---------- 保存 ---------- */
const saveAll = async () => {
saving.value = true
try {
await $fetch('/api/admin/settings', {
method: 'PATCH',
body: { settings: clone(form) },
})
toast.success('已保存,前台即时生效')
} catch (err: any) {
toast.error(err?.data?.message || '保存失败,请重试')
} finally {
saving.value = false
}
}
/* ---------- 社交链接 ---------- */
const SOCIAL_ICONS = [
{ label: 'X (Twitter)', value: 'ph:x-logo' },
{ label: 'Instagram', value: 'ph:instagram-logo' },
{ label: 'LinkedIn', value: 'ph:linkedin-logo' },
{ label: 'GitHub', value: 'ph:github-logo' },
{ label: 'YouTube', value: 'ph:youtube-logo' },
{ label: 'Facebook', value: 'ph:facebook-logo' },
{ label: '微信', value: 'ph:wechat-logo' },
{ label: '邮箱', value: 'ph:envelope-simple' },
{ label: '链接', value: 'ph:link-simple' },
{ label: '地球', value: 'ph:globe-simple' },
]
const addSocial = () => form.socials.push({ name: '', icon: 'ph:link-simple', url: '' })
const removeSocial = (i: number) => form.socials.splice(i, 1)
/* ---------- 工具箱 ---------- */
const TOOL_COLORS = [
{ label: '橙 · 琥珀', value: 'from-orange-50/50 to-amber-100/50' },
{ label: '紫 · 靛蓝', value: 'from-purple-50/50 to-indigo-100/50' },
{ label: '蓝 · 青', value: 'from-blue-50/50 to-cyan-100/50' },
{ label: '绿 · 翠', value: 'from-emerald-50/50 to-teal-100/50' },
{ label: '粉 · 玫', value: 'from-pink-50/50 to-rose-100/50' },
{ label: '灰 · 石板', value: 'from-gray-50/50 to-slate-100/50' },
]
const addTool = () =>
form.tools.push({
id: '',
name: '',
url: '',
icon: 'ph:wrench-duotone',
color: TOOL_COLORS[0].value,
descZh: '',
descEn: '',
})
const removeTool = (i: number) => form.tools.splice(i, 1)
</script>
<template>
<div>
<!-- 页头 -->
<AdminPageHeader title="站点设置" subtitle="管理站点全局信息,保存后前台即时生效">
<template #actions>
<AdminButton :loading="saving" :disabled="loading || !!error" @click="saveAll">
<Icon v-if="!saving" name="ph:floppy-disk" class="w-4 h-4" />
{{ saving ? '保存中…' : '保存全部' }}
</AdminButton>
</template>
</AdminPageHeader>
<!-- 加载骨架 -->
<div v-if="loading" class="space-y-6 max-w-5xl">
<AdminCard v-for="i in 4" :key="i" title="">
<AdminSkeleton :rows="5" />
</AdminCard>
</div>
<!-- 加载失败 -->
<div
v-else-if="error"
class="max-w-5xl rounded-2xl bg-white border border-gray-100 shadow-sm p-10 text-center"
>
<Icon name="ph:warning-circle" class="w-10 h-10 text-gray-300 mx-auto mb-4" />
<p class="text-gray-500 mb-4">{{ error }}</p>
<AdminButton variant="secondary" @click="loadSettings">
<Icon name="ph:arrow-clockwise" class="w-4 h-4" /> 重新加载
</AdminButton>
</div>
<!-- 表单 -->
<div v-else class="space-y-6 max-w-5xl">
<!-- 1. 站点信息 -->
<AdminCard title="站点信息" subtitle="品牌标识与浏览器标题等基础信息">
<template #actions><Icon name="ph:info" class="w-5 h-5 text-gray-300" /></template>
<div class="grid grid-cols-1 md:grid-cols-2 gap-5">
<AdminInput v-model="form.site.name" label="站点名称" placeholder="ArcticNewOne" />
<AdminInput v-model="form.site.brand" label="品牌名" placeholder="北极新一" />
<AdminTextarea v-model="form.site.description.zh" label="站点简介(中文)" :rows="3" />
<AdminTextarea v-model="form.site.description.en" label="Description (EN)" :rows="3" />
</div>
</AdminCard>
<!-- 2. 联系方式 -->
<AdminCard title="联系方式" subtitle="前台「联系我们」展示的联系信息">
<template #actions><Icon name="ph:envelope-simple" class="w-5 h-5 text-gray-300" /></template>
<div class="grid grid-cols-1 md:grid-cols-2 gap-5">
<AdminInput v-model="form.contact.email" label="联系邮箱" type="email" placeholder="hello@..." />
<AdminInput v-model="form.contact.infoEmail" label="信息邮箱" type="email" placeholder="info@..." />
<AdminInput v-model="form.contact.wechat" label="微信号" placeholder="LucskyNew" />
<AdminTextarea v-model="form.contact.address.zh" label="地址(中文)" :rows="2" />
<AdminTextarea v-model="form.contact.address.en" label="Address (EN)" :rows="2" />
</div>
</AdminCard>
<!-- 3. 社交链接 -->
<AdminCard title="社交链接" subtitle="前台页脚与联系页展示的社交入口">
<template #actions><Icon name="ph:share-network" class="w-5 h-5 text-gray-300" /></template>
<div class="space-y-4">
<div
v-for="(s, i) in form.socials"
:key="i"
class="rounded-xl border border-gray-100 bg-gray-50/50 p-4"
>
<div class="grid grid-cols-1 md:grid-cols-[120px_200px_1fr_auto] gap-3 items-end">
<AdminInput v-model="s.name" label="名称" placeholder="X" />
<AdminSelect v-model="s.icon" :options="SOCIAL_ICONS" label="图标" />
<AdminInput v-model="s.url" label="链接" type="url" placeholder="https://..." />
<button
type="button"
class="mb-1 w-9 h-9 rounded-lg text-gray-400 hover:text-red-600 hover:bg-red-50 flex items-center justify-center transition-colors"
:aria-label="`删除社交链接 ${s.name}`"
@click="removeSocial(i)"
>
<Icon name="ph:trash" class="w-4 h-4" />
</button>
</div>
</div>
<AdminButton variant="secondary" size="sm" @click="addSocial">
<Icon name="ph:plus" class="w-4 h-4" /> 添加社交链接
</AdminButton>
</div>
</AdminCard>
<!-- 4. 工具箱 -->
<AdminCard title="工具箱" subtitle="前台「工具箱」页展示的在线工具">
<template #actions><Icon name="ph:wrench" class="w-5 h-5 text-gray-300" /></template>
<div class="space-y-4">
<div
v-for="(tool, i) in form.tools"
:key="i"
class="rounded-xl border border-gray-100 bg-gray-50/50 p-4 space-y-3"
>
<div class="flex items-center justify-between">
<span class="text-xs font-semibold text-gray-400">工具 #{{ i + 1 }}</span>
<button
type="button"
class="inline-flex items-center gap-1 px-2.5 py-1.5 rounded-lg text-xs font-semibold text-gray-400 hover:text-red-600 hover:bg-red-50 transition-colors"
@click="removeTool(i)"
>
<Icon name="ph:trash" class="w-3.5 h-3.5" /> 删除
</button>
</div>
<div class="grid grid-cols-1 md:grid-cols-2 gap-3">
<AdminInput v-model="tool.id" label="ID" placeholder="drawio" />
<AdminInput v-model="tool.name" label="名称" placeholder="Drawio" />
<AdminInput v-model="tool.url" label="链接" type="url" placeholder="https://..." />
<AdminInput v-model="tool.icon" label="图标名" placeholder="ph:flow-arrow-duotone" />
<AdminSelect v-model="tool.color" :options="TOOL_COLORS" label="主题色" />
</div>
<div class="grid grid-cols-1 md:grid-cols-2 gap-3">
<AdminTextarea v-model="tool.descZh" label="中文简介" :rows="2" />
<AdminTextarea v-model="tool.descEn" label="Description (EN)" :rows="2" />
</div>
</div>
<AdminButton variant="secondary" size="sm" @click="addTool">
<Icon name="ph:plus" class="w-4 h-4" /> 添加工具
</AdminButton>
</div>
</AdminCard>
<!-- 5. 页脚文案 -->
<AdminCard title="页脚文案" subtitle="前台页脚与订阅区的文案">
<template #actions><Icon name="ph:paragraph" class="w-5 h-5 text-gray-300" /></template>
<div class="space-y-5">
<div class="grid grid-cols-1 md:grid-cols-2 gap-4">
<AdminTextarea v-model="form.footer.title.zh" label="主标题(中文)" :rows="3" />
<AdminTextarea v-model="form.footer.title.en" label="Headline (EN)" :rows="3" />
</div>
<div class="grid grid-cols-1 md:grid-cols-2 gap-4">
<AdminInput v-model="form.footer.newsletterTitle.zh" label="订阅标题(中文)" />
<AdminInput v-model="form.footer.newsletterTitle.en" label="Newsletter Title (EN)" />
</div>
<div class="grid grid-cols-1 md:grid-cols-2 gap-4">
<AdminInput v-model="form.footer.newsletterNote.zh" label="订阅说明(中文)" />
<AdminInput v-model="form.footer.newsletterNote.en" label="Newsletter Note (EN)" />
</div>
<div class="grid grid-cols-1 md:grid-cols-2 gap-4">
<AdminInput v-model="form.footer.copyright.zh" label="版权(中文)" />
<AdminInput v-model="form.footer.copyright.en" label="Copyright (EN)" />
</div>
</div>
</AdminCard>
<!-- 6. SEO -->
<AdminCard title="SEO" subtitle="搜索引擎描述与关键词">
<template #actions><Icon name="ph:magnifying-glass" class="w-5 h-5 text-gray-300" /></template>
<div class="space-y-5">
<div class="grid grid-cols-1 md:grid-cols-2 gap-4">
<AdminTextarea v-model="form.seo.description.zh" label="描述(中文)" :rows="3" />
<AdminTextarea v-model="form.seo.description.en" label="Description (EN)" :rows="3" />
</div>
<div class="grid grid-cols-1 md:grid-cols-2 gap-4">
<AdminTextarea v-model="form.seo.keywords.zh" label="关键词(中文,逗号分隔)" :rows="2" />
<AdminTextarea v-model="form.seo.keywords.en" label="Keywords (EN, comma-separated)" :rows="2" />
</div>
</div>
</AdminCard>
</div>
</div>
</template>
+261 -124
View File
@@ -1,110 +1,13 @@
<template>
<section class="p-4 md:p-8 lg:p-10">
<header class="mb-8 flex flex-col sm:flex-row sm:items-center sm:justify-between gap-4">
<div class="flex items-center gap-3">
<div class="w-11 h-11 rounded-2xl bg-black text-white flex items-center justify-center flex-shrink-0">
<Icon name="ph:envelope" class="w-6 h-6" />
</div>
<div>
<h1 class="text-2xl font-bold text-black leading-tight">邮件订阅</h1>
<p class="text-sm text-gray-500 mt-1">订阅了站内更新的邮箱列表,可导出 CSV。</p>
</div>
</div>
<a
:href="'/api/admin/subscribers/export'"
class="inline-flex items-center gap-2 px-5 py-2.5 rounded-full bg-black text-white text-sm font-semibold hover:bg-gray-800 transition-colors flex-shrink-0"
title="导出全部订阅邮箱"
>
<Icon name="ph:download-simple" class="w-4 h-4" />
导出 CSV
</a>
</header>
<!-- 操作反馈 -->
<div
v-if="flash"
class="mb-6 px-4 py-3 rounded-xl text-sm font-medium flex items-center gap-2"
:class="flashKind === 'ok' ? 'bg-green-50 text-green-700 border border-green-200' : 'bg-red-50 text-red-700 border border-red-200'"
>
<Icon :name="flashKind === 'ok' ? 'ph:check-circle' : 'ph:warning-circle'" class="w-4 h-4" />
{{ flash }}
</div>
<div class="flex items-center gap-2 mb-4">
<span class="text-sm text-gray-500">共 {{ subscribers.length }} 个订阅</span>
</div>
<!-- 加载中 -->
<div v-if="loading" class="py-24 flex flex-col items-center gap-3 text-gray-400">
<Icon name="ph:circle-notch" class="w-8 h-8 animate-spin" />
<p class="text-sm">加载中…</p>
</div>
<!-- 加载失败 -->
<div v-else-if="loadError" class="py-24 text-center">
<div class="inline-flex flex-col items-center gap-3 text-gray-500">
<Icon name="ph:warning-circle" class="w-8 h-8 text-red-500" />
<p class="text-sm">{{ loadError }}</p>
<button @click="loadSubscribers" class="px-5 py-2 rounded-full bg-black text-white text-sm font-semibold hover:bg-gray-800 transition-colors">
重试
</button>
</div>
</div>
<!-- 空态 -->
<div v-else-if="!subscribers.length" class="py-24 flex flex-col items-center gap-3 text-gray-400">
<Icon name="ph:envelope" class="w-10 h-10" />
<p class="text-sm">暂无订阅</p>
</div>
<!-- 订阅表格 -->
<div v-else class="bg-white rounded-2xl border border-gray-100 shadow-sm overflow-hidden">
<div class="overflow-x-auto">
<table class="w-full text-sm">
<thead>
<tr class="text-left text-gray-500 border-b border-gray-100 bg-gray-50">
<th class="px-6 py-4 font-semibold text-xs uppercase tracking-wider">邮箱</th>
<th class="px-6 py-4 font-semibold text-xs uppercase tracking-wider whitespace-nowrap">订阅时间</th>
<th class="px-6 py-4 font-semibold text-xs uppercase tracking-wider text-right">操作</th>
</tr>
</thead>
<tbody>
<tr
v-for="s in subscribers"
:key="s.id"
class="border-b border-gray-100 last:border-b-0 hover:bg-gray-50/70 transition-colors"
>
<td class="px-6 py-4">
<a :href="`mailto:${s.email}`" class="inline-flex items-center gap-2 font-semibold text-black hover:text-gray-600 transition-colors">
<Icon name="ph:envelope-simple" class="w-4 h-4 text-gray-400" />
{{ s.email }}
</a>
</td>
<td class="px-6 py-4 text-gray-500 text-xs whitespace-nowrap">{{ formatDate(s.createdAt) }}</td>
<td class="px-6 py-4">
<div class="flex items-center justify-end">
<button
@click="removeSubscriber(s)"
class="w-8 h-8 rounded-full flex items-center justify-center text-gray-400 hover:bg-red-50 hover:text-red-600 transition-colors"
title="删除订阅"
>
<Icon name="ph:trash" class="w-4 h-4" />
</button>
</div>
</td>
</tr>
</tbody>
</table>
</div>
</div>
</section>
</template>
<script setup lang="ts">
import { onMounted, ref } from 'vue'
/**
* 后台订阅管理:列表 + 搜索 + 多选批量删除 + 导出 CSV + 前端分页。
* - GET/DELETE /api/admin/subscribers[/id];导出 GET /api/admin/subscribers/export
*/
import { computed, onMounted, ref, watch } from 'vue'
import { useToastStore } from '~/stores/toast'
definePageMeta({ middleware: 'admin', layout: 'admin' })
useSeoMeta({ title: '邮件订阅' })
useHead({ title: '订阅管理' })
interface AdminSubscriber {
id: number
@@ -112,22 +15,13 @@ interface AdminSubscriber {
createdAt: string
}
const toast = useToastStore()
/* ---------- 列表 ---------- */
const subscribers = ref<AdminSubscriber[]>([])
const loading = ref(true)
const loadError = ref('')
const flash = ref('')
const flashKind = ref<'ok' | 'err'>('ok')
let flashTimer: ReturnType<typeof setTimeout> | null = null
const showFlash = (msg: string, kind: 'ok' | 'err' = 'ok') => {
flash.value = msg
flashKind.value = kind
if (flashTimer) clearTimeout(flashTimer)
flashTimer = setTimeout(() => {
flash.value = ''
}, 3000)
}
const loadSubscribers = async () => {
loading.value = true
loadError.value = ''
@@ -142,15 +36,108 @@ const loadSubscribers = async () => {
}
}
const removeSubscriber = async (s: AdminSubscriber) => {
if (!window.confirm(`确定取消订阅「${s.email}」吗?此操作不可恢复。`)) return
onMounted(loadSubscribers)
/* ---------- 搜索 / 分页 ---------- */
const keyword = ref('')
const filteredSubscribers = computed(() => {
const kw = keyword.value.trim().toLowerCase()
if (!kw) return subscribers.value
return subscribers.value.filter((s) => s.email.toLowerCase().includes(kw))
})
const pageSize = 15
const page = ref(1)
const totalPages = computed(() => Math.max(1, Math.ceil(filteredSubscribers.value.length / pageSize)))
const pagedSubscribers = computed(() => {
const p = Math.min(page.value, totalPages.value)
const start = (p - 1) * pageSize
return filteredSubscribers.value.slice(start, start + pageSize)
})
watch(keyword, () => {
page.value = 1
})
const changePage = (p: number) => {
page.value = Math.min(Math.max(1, p), totalPages.value)
}
/* ---------- 多选 / 批量删除 ---------- */
const selected = ref<Set<number>>(new Set())
const allChecked = computed(
() => pagedSubscribers.value.length > 0 && pagedSubscribers.value.every((s) => selected.value.has(s.id)),
)
const toggleAll = () => {
if (allChecked.value) {
for (const s of pagedSubscribers.value) selected.value.delete(s.id)
selected.value = new Set(selected.value)
} else {
const next = new Set(selected.value)
for (const s of pagedSubscribers.value) next.add(s.id)
selected.value = next
}
}
const toggleOne = (id: number) => {
const next = new Set(selected.value)
if (next.has(id)) next.delete(id)
else next.add(id)
selected.value = next
}
const batchConfirmOpen = ref(false)
const batchDeleting = ref(false)
const doBatchDelete = async () => {
const ids = [...selected.value]
if (!ids.length) return
batchDeleting.value = true
let failed = 0
for (const id of ids) {
try {
await $fetch(`/api/admin/subscribers/${id}`, { method: 'DELETE' })
} catch (err: any) {
console.error('batch delete subscriber error:', err)
failed++
}
}
batchDeleting.value = false
batchConfirmOpen.value = false
selected.value = new Set()
if (failed === 0) {
toast.success(`已取消订阅 ${ids.length} 个邮箱`)
} else {
toast.error(`删除 ${ids.length - failed} 个成功,${failed} 个失败`)
}
await loadSubscribers()
}
/* ---------- 单条删除 ---------- */
const confirmDelete = ref<AdminSubscriber | null>(null)
const deleting = ref(false)
const askDelete = (s: AdminSubscriber) => {
confirmDelete.value = s
}
const doDelete = async () => {
const s = confirmDelete.value
if (!s) return
deleting.value = true
try {
await $fetch(`/api/admin/subscribers/${s.id}`, { method: 'DELETE' })
subscribers.value = subscribers.value.filter((x) => x.id !== s.id)
showFlash(`已取消订阅「${s.email}」`)
} catch (err) {
console.error('delete subscriber error:', err)
showFlash((err as any)?.data?.message || '删除失败,请重试', 'err')
selected.value.delete(s.id)
toast.success(`已取消订阅「${s.email}」`)
confirmDelete.value = null
} catch (err: any) {
toast.error(err?.data?.message || '删除失败,请重试')
} finally {
deleting.value = false
}
}
@@ -166,6 +153,156 @@ const formatDate = (raw?: string) => {
minute: '2-digit',
}).format(d)
}
onMounted(loadSubscribers)
</script>
<template>
<div>
<AdminPageHeader title="订阅管理" subtitle="订阅了站内更新的邮箱列表,可导出 CSV。">
<template #actions>
<a
:href="'/api/admin/subscribers/export'"
class="inline-flex items-center justify-center gap-2 rounded-xl bg-black px-4 py-2 text-sm font-semibold text-white shadow-sm transition-all duration-200 hover:bg-gray-800"
title="导出全部订阅邮箱"
>
<Icon name="ph:download-simple" class="w-4 h-4" /> 导出 CSV
</a>
</template>
</AdminPageHeader>
<!-- 统计 + 工具栏 -->
<div class="mb-4 flex flex-wrap items-center gap-x-4 gap-y-2">
<span class="text-sm text-gray-500">共 {{ subscribers.length }} 个订阅</span>
<span v-if="selected.size" class="text-sm text-gray-400">· 已选 {{ selected.size }} 项</span>
</div>
<div class="mb-5 flex flex-wrap items-center gap-3">
<div class="relative flex-1 sm:max-w-xs">
<Icon name="ph:magnifying-glass" class="w-4 h-4 text-gray-400 absolute left-3.5 top-1/2 -translate-y-1/2 pointer-events-none" />
<input
v-model="keyword"
type="text"
placeholder="搜索邮箱…"
class="w-full rounded-xl border border-gray-200 bg-white py-2.5 pl-10 pr-9 text-sm outline-none transition-all focus:border-black focus:ring-2 focus:ring-black/10"
/>
<button
v-if="keyword"
@click="keyword = ''"
class="absolute right-2.5 top-1/2 -translate-y-1/2 w-5 h-5 rounded-full text-gray-400 hover:text-gray-600 hover:bg-gray-100 flex items-center justify-center"
aria-label="清空筛选"
>
<Icon name="ph:x" class="w-3.5 h-3.5" />
</button>
</div>
<AdminButton variant="danger" size="sm" :disabled="!selected.size" @click="batchConfirmOpen = true">
<Icon name="ph:trash" class="w-4 h-4" /> 批量删除
</AdminButton>
</div>
<!-- 加载态 -->
<AdminCard v-if="loading">
<AdminSkeleton :rows="6" />
</AdminCard>
<!-- 错误态 -->
<AdminCard v-else-if="loadError">
<div class="py-10 text-center">
<Icon name="ph:warning-circle" class="w-10 h-10 text-gray-300 mx-auto mb-4" />
<p class="text-gray-500 mb-4">{{ loadError }}</p>
<AdminButton size="sm" @click="loadSubscribers">重新加载</AdminButton>
</div>
</AdminCard>
<!-- 空态 -->
<AdminEmptyState v-else-if="!subscribers.length" icon="ph:envelope" title="暂无订阅" description="还没有人订阅站内更新。" />
<AdminEmptyState
v-else-if="!filteredSubscribers.length"
icon="ph:magnifying-glass"
title="没有匹配的订阅"
description="换个邮箱关键词试试。"
/>
<!-- 订阅表格 -->
<template v-else>
<div class="rounded-2xl border border-gray-100 bg-white shadow-sm overflow-hidden">
<div class="overflow-x-auto">
<table class="w-full text-sm">
<thead>
<tr class="text-left text-gray-400 border-b border-gray-100 bg-gray-50">
<th class="px-5 py-4 w-10">
<input
type="checkbox"
:checked="allChecked"
class="w-4 h-4 rounded border-gray-300 accent-black cursor-pointer"
@change="toggleAll"
/>
</th>
<th class="px-5 py-4 font-semibold text-xs uppercase tracking-wider">邮箱</th>
<th class="px-5 py-4 font-semibold text-xs uppercase tracking-wider whitespace-nowrap">订阅时间</th>
<th class="px-5 py-4 font-semibold text-xs uppercase tracking-wider text-right">操作</th>
</tr>
</thead>
<tbody class="divide-y divide-gray-50">
<tr
v-for="s in pagedSubscribers"
:key="s.id"
class="hover:bg-gray-50/60 transition-colors"
:class="selected.has(s.id) ? 'bg-gray-50/70' : ''"
>
<td class="px-5 py-4">
<input
type="checkbox"
:checked="selected.has(s.id)"
class="w-4 h-4 rounded border-gray-300 accent-black cursor-pointer"
@change="toggleOne(s.id)"
/>
</td>
<td class="px-5 py-4">
<a
:href="`mailto:${s.email}`"
class="inline-flex items-center gap-2 font-semibold text-black hover:text-gray-600 transition-colors"
>
<Icon name="ph:envelope-simple" class="w-4 h-4 text-gray-400" />
{{ s.email }}
</a>
</td>
<td class="px-5 py-4 text-gray-500 text-xs whitespace-nowrap">{{ formatDate(s.createdAt) }}</td>
<td class="px-5 py-4">
<div class="flex items-center justify-end">
<AdminButton size="sm" variant="ghost" @click="askDelete(s)">
<Icon name="ph:trash" class="w-4 h-4" />
</AdminButton>
</div>
</td>
</tr>
</tbody>
</table>
</div>
</div>
<div class="mt-4">
<AdminPagination :total="filteredSubscribers.length" :page="page" :page-size="pageSize" @page="changePage" />
</div>
</template>
<!-- 批量删除确认 -->
<AdminConfirm
:open="batchConfirmOpen"
:loading="batchDeleting"
danger
:message="`确定删除已选的 ${selected.size} 个订阅邮箱吗?此操作不可恢复。`"
@update:open="batchConfirmOpen = false"
@confirm="doBatchDelete"
/>
<!-- 单条删除确认 -->
<AdminConfirm
:open="!!confirmDelete"
:loading="deleting"
danger
:message="`确定取消订阅「${confirmDelete?.email}」吗?此操作不可恢复。`"
@update:open="confirmDelete = null"
@confirm="doDelete"
/>
</div>
</template>
+171 -111
View File
@@ -1,95 +1,13 @@
<template>
<section class="p-4 md:p-8 lg:p-10">
<header class="mb-8 flex flex-col sm:flex-row sm:items-center sm:justify-between gap-4">
<div class="flex items-center gap-3">
<div class="w-11 h-11 rounded-2xl bg-black text-white flex items-center justify-center flex-shrink-0">
<Icon name="ph:image" class="w-6 h-6" />
</div>
<div>
<h1 class="text-2xl font-bold text-black leading-tight">图片管理</h1>
<p class="text-sm text-gray-500 mt-1">站点上传的图片文件,删除前请确认未被动态/作品引用。</p>
</div>
</div>
<button
@click="loadFiles"
class="inline-flex items-center gap-2 px-4 py-2 rounded-full border border-gray-200 bg-white text-sm font-semibold text-gray-700 hover:bg-gray-100 transition-colors flex-shrink-0"
>
<Icon name="ph:arrows-clockwise" class="w-4 h-4" />
刷新
</button>
</header>
<!-- 操作反馈 -->
<div
v-if="flash"
class="mb-6 px-4 py-3 rounded-xl text-sm font-medium flex items-center gap-2"
:class="flashKind === 'ok' ? 'bg-green-50 text-green-700 border border-green-200' : 'bg-red-50 text-red-700 border border-red-200'"
>
<Icon :name="flashKind === 'ok' ? 'ph:check-circle' : 'ph:warning-circle'" class="w-4 h-4" />
{{ flash }}
</div>
<div class="flex items-center gap-2 mb-4">
<span class="text-sm text-gray-500">共 {{ files.length }} 张图片</span>
</div>
<!-- 加载中 -->
<div v-if="loading" class="py-24 flex flex-col items-center gap-3 text-gray-400">
<Icon name="ph:circle-notch" class="w-8 h-8 animate-spin" />
<p class="text-sm">加载中…</p>
</div>
<!-- 加载失败 -->
<div v-else-if="loadError" class="py-24 text-center">
<div class="inline-flex flex-col items-center gap-3 text-gray-500">
<Icon name="ph:warning-circle" class="w-8 h-8 text-red-500" />
<p class="text-sm">{{ loadError }}</p>
<button @click="loadFiles" class="px-5 py-2 rounded-full bg-black text-white text-sm font-semibold hover:bg-gray-800 transition-colors">
重试
</button>
</div>
</div>
<!-- 空态 -->
<div v-else-if="!files.length" class="py-24 flex flex-col items-center gap-3 text-gray-400">
<Icon name="ph:image" class="w-10 h-10" />
<p class="text-sm">暂无图片</p>
</div>
<!-- 图片网格 -->
<div v-else class="grid grid-cols-2 sm:grid-cols-3 lg:grid-cols-4 xl:grid-cols-5 gap-4">
<div
v-for="f in files"
:key="f.name"
class="bg-white rounded-2xl border border-gray-100 shadow-sm overflow-hidden group"
>
<div class="relative aspect-square bg-gray-50">
<img :src="f.url" :alt="f.name" loading="lazy" class="w-full h-full object-cover" />
<button
@click="removeFile(f)"
class="absolute top-2 right-2 w-8 h-8 rounded-full bg-black/60 text-white flex items-center justify-center opacity-0 group-hover:opacity-100 transition-opacity hover:bg-red-600"
title="删除图片"
>
<Icon name="ph:trash" class="w-4 h-4" />
</button>
</div>
<div class="p-3">
<p class="text-xs font-semibold text-gray-800 truncate" :title="f.name">{{ f.name }}</p>
<div class="mt-1 flex items-center justify-between gap-2 text-[11px] text-gray-400">
<span class="flex-shrink-0">{{ formatSize(f.size) }}</span>
<span class="truncate">{{ formatDate(f.modified) }}</span>
</div>
</div>
</div>
</div>
</section>
</template>
<script setup lang="ts">
import { onMounted, ref } from 'vue'
/**
* 后台图片管理:网格 + 搜索 + 存储模式标识 + 删除确认 + 前端分页。
* - GET /api/admin/uploads → { files, storage };DELETE /api/admin/uploads?name=<key>
*/
import { computed, onMounted, ref, watch } from 'vue'
import { useToastStore } from '~/stores/toast'
definePageMeta({ middleware: 'admin', layout: 'admin' })
useSeoMeta({ title: '图片管理' })
useHead({ title: '图片管理' })
interface UploadFile {
name: string
@@ -98,28 +16,21 @@ interface UploadFile {
url: string
}
const toast = useToastStore()
/* ---------- 列表 ---------- */
const files = ref<UploadFile[]>([])
const storage = ref<'local' | 'oss' | ''>('')
const loading = ref(true)
const loadError = ref('')
const flash = ref('')
const flashKind = ref<'ok' | 'err'>('ok')
let flashTimer: ReturnType<typeof setTimeout> | null = null
const showFlash = (msg: string, kind: 'ok' | 'err' = 'ok') => {
flash.value = msg
flashKind.value = kind
if (flashTimer) clearTimeout(flashTimer)
flashTimer = setTimeout(() => {
flash.value = ''
}, 3000)
}
const loadFiles = async () => {
loading.value = true
loadError.value = ''
try {
const data = await $fetch<{ files: UploadFile[] }>('/api/admin/uploads')
const data = await $fetch<{ files: UploadFile[]; storage: 'local' | 'oss' }>('/api/admin/uploads')
files.value = data.files
storage.value = data.storage
} catch (err) {
console.error('load uploads error:', err)
loadError.value = '加载失败,请重试'
@@ -128,15 +39,57 @@ const loadFiles = async () => {
}
}
const removeFile = async (f: UploadFile) => {
if (!window.confirm(`确定删除图片「${f.name}」吗?此操作不可恢复。`)) return
onMounted(loadFiles)
/* ---------- 搜索 / 分页 ---------- */
const keyword = ref('')
const filteredFiles = computed(() => {
const kw = keyword.value.trim().toLowerCase()
if (!kw) return files.value
return files.value.filter((f) => f.name.toLowerCase().includes(kw))
})
const pageSize = 12
const page = ref(1)
const totalPages = computed(() => Math.max(1, Math.ceil(filteredFiles.value.length / pageSize)))
const pagedFiles = computed(() => {
const p = Math.min(page.value, totalPages.value)
const start = (p - 1) * pageSize
return filteredFiles.value.slice(start, start + pageSize)
})
watch(keyword, () => {
page.value = 1
})
const changePage = (p: number) => {
page.value = Math.min(Math.max(1, p), totalPages.value)
}
const totalSize = computed(() => files.value.reduce((sum, f) => sum + f.size, 0))
/* ---------- 删除 ---------- */
const confirmDelete = ref<UploadFile | null>(null)
const deleting = ref(false)
const askDelete = (f: UploadFile) => {
confirmDelete.value = f
}
const doDelete = async () => {
const f = confirmDelete.value
if (!f) return
deleting.value = true
try {
await $fetch(`/api/admin/uploads/${encodeURIComponent(f.name)}`, { method: 'DELETE' })
await $fetch('/api/admin/uploads', { method: 'DELETE', query: { name: f.name } })
files.value = files.value.filter((x) => x.name !== f.name)
showFlash('已删除;如被内容引用请同步更新')
} catch (err) {
console.error('delete upload error:', err)
showFlash((err as any)?.data?.message || '删除失败,请重试', 'err')
toast.success('已删除;如被内容引用请同步更新')
confirmDelete.value = null
} catch (err: any) {
toast.error(err?.data?.message || '删除失败,请重试')
} finally {
deleting.value = false
}
}
@@ -160,6 +113,113 @@ const formatDate = (raw?: string) => {
minute: '2-digit',
}).format(d)
}
onMounted(loadFiles)
</script>
<template>
<div>
<AdminPageHeader title="图片管理" subtitle="站点上传的图片文件,删除前请确认未被动态/作品引用。">
<template #actions>
<AdminButton variant="secondary" size="sm" @click="loadFiles">
<Icon name="ph:arrows-clockwise" class="w-4 h-4" /> 刷新
</AdminButton>
</template>
</AdminPageHeader>
<!-- 统计 + 工具栏 -->
<div class="mb-4 flex flex-wrap items-center gap-x-4 gap-y-2">
<span class="text-sm text-gray-500">共 {{ files.length }} 张图片</span>
<span class="text-sm text-gray-400">· 共 {{ formatSize(totalSize) }}</span>
<AdminBadge :tone="storage === 'oss' ? 'blue' : 'gray'">
<Icon :name="storage === 'oss' ? 'ph:cloud' : 'ph:hard-drives'" class="w-3.5 h-3.5" />
{{ storage === 'oss' ? 'OSS 存储' : '本地存储' }}
</AdminBadge>
</div>
<div class="mb-5">
<div class="relative flex-1 sm:max-w-xs">
<Icon name="ph:magnifying-glass" class="w-4 h-4 text-gray-400 absolute left-3.5 top-1/2 -translate-y-1/2 pointer-events-none" />
<input
v-model="keyword"
type="text"
placeholder="搜索文件名…"
class="w-full rounded-xl border border-gray-200 bg-white py-2.5 pl-10 pr-9 text-sm outline-none transition-all focus:border-black focus:ring-2 focus:ring-black/10"
/>
<button
v-if="keyword"
@click="keyword = ''"
class="absolute right-2.5 top-1/2 -translate-y-1/2 w-5 h-5 rounded-full text-gray-400 hover:text-gray-600 hover:bg-gray-100 flex items-center justify-center"
aria-label="清空筛选"
>
<Icon name="ph:x" class="w-3.5 h-3.5" />
</button>
</div>
</div>
<!-- 加载态 -->
<AdminCard v-if="loading">
<AdminSkeleton :rows="6" />
</AdminCard>
<!-- 错误态 -->
<AdminCard v-else-if="loadError">
<div class="py-10 text-center">
<Icon name="ph:warning-circle" class="w-10 h-10 text-gray-300 mx-auto mb-4" />
<p class="text-gray-500 mb-4">{{ loadError }}</p>
<AdminButton size="sm" @click="loadFiles">重新加载</AdminButton>
</div>
</AdminCard>
<!-- 空态 -->
<AdminEmptyState v-else-if="!files.length" icon="ph:image" title="暂无图片" description="通过动态/作品的图片上传功能产生的文件会出现在这里。" />
<AdminEmptyState
v-else-if="!filteredFiles.length"
icon="ph:magnifying-glass"
title="没有匹配的图片"
description="换个文件名关键词试试。"
/>
<!-- 图片网格 -->
<template v-else>
<div class="grid grid-cols-2 sm:grid-cols-3 lg:grid-cols-4 xl:grid-cols-5 gap-4">
<div
v-for="f in pagedFiles"
:key="f.name"
class="bg-white rounded-2xl border border-gray-100 shadow-sm overflow-hidden group"
>
<div class="relative aspect-square bg-gray-50">
<img :src="f.url" :alt="f.name" loading="lazy" class="w-full h-full object-cover" />
<button
@click="askDelete(f)"
class="absolute top-2 right-2 w-8 h-8 rounded-full bg-black/60 text-white flex items-center justify-center opacity-0 group-hover:opacity-100 transition-opacity hover:bg-red-600"
title="删除图片"
>
<Icon name="ph:trash" class="w-4 h-4" />
</button>
</div>
<div class="p-3">
<p class="text-xs font-semibold text-gray-800 truncate" :title="f.name">{{ f.name }}</p>
<div class="mt-1 flex items-center justify-between gap-2 text-[11px] text-gray-400">
<span class="flex-shrink-0">{{ formatSize(f.size) }}</span>
<span class="truncate">{{ formatDate(f.modified) }}</span>
</div>
</div>
</div>
</div>
<div class="mt-4">
<AdminPagination :total="filteredFiles.length" :page="page" :page-size="pageSize" @page="changePage" />
</div>
</template>
<!-- 删除确认 -->
<AdminConfirm
:open="!!confirmDelete"
:loading="deleting"
danger
:message="`确定删除图片「${confirmDelete?.name}」吗?此操作不可恢复。`"
@update:open="confirmDelete = null"
@confirm="doDelete"
/>
</div>
</template>
+215 -151
View File
@@ -1,129 +1,14 @@
<template>
<section class="p-4 md:p-8 lg:p-10">
<header class="mb-8">
<div class="flex items-center gap-3">
<div class="w-11 h-11 rounded-2xl bg-black text-white flex items-center justify-center flex-shrink-0">
<Icon name="ph:users-three" class="w-6 h-6" />
</div>
<div>
<h1 class="text-2xl font-bold text-black leading-tight">用户管理</h1>
<p class="text-sm text-gray-500 mt-1">管理站点注册用户,调整角色或删除账号。</p>
</div>
</div>
</header>
<!-- 操作反馈 -->
<div
v-if="flash"
class="mb-6 px-4 py-3 rounded-xl text-sm font-medium flex items-center gap-2"
:class="flashKind === 'ok' ? 'bg-green-50 text-green-700 border border-green-200' : 'bg-red-50 text-red-700 border border-red-200'"
>
<Icon :name="flashKind === 'ok' ? 'ph:check-circle' : 'ph:warning-circle'" class="w-4 h-4" />
{{ flash }}
</div>
<div class="flex items-center gap-2 mb-4">
<span class="text-sm text-gray-500">共 {{ users.length }} 个用户</span>
</div>
<!-- 加载中 -->
<div v-if="loading" class="py-24 flex flex-col items-center gap-3 text-gray-400">
<Icon name="ph:circle-notch" class="w-8 h-8 animate-spin" />
<p class="text-sm">加载中…</p>
</div>
<!-- 加载失败 -->
<div v-else-if="loadError" class="py-24 text-center">
<div class="inline-flex flex-col items-center gap-3 text-gray-500">
<Icon name="ph:warning-circle" class="w-8 h-8 text-red-500" />
<p class="text-sm">{{ loadError }}</p>
<button @click="loadUsers" class="px-5 py-2 rounded-full bg-black text-white text-sm font-semibold hover:bg-gray-800 transition-colors">
重试
</button>
</div>
</div>
<!-- 空态 -->
<div v-else-if="!users.length" class="py-24 flex flex-col items-center gap-3 text-gray-400">
<Icon name="ph:users-three" class="w-10 h-10" />
<p class="text-sm">暂无用户</p>
</div>
<!-- 用户表格 -->
<div v-else class="bg-white rounded-2xl border border-gray-100 shadow-sm overflow-hidden">
<div class="overflow-x-auto">
<table class="w-full text-sm">
<thead>
<tr class="text-left text-gray-500 border-b border-gray-100 bg-gray-50">
<th class="px-6 py-4 font-semibold text-xs uppercase tracking-wider whitespace-nowrap">ID</th>
<th class="px-6 py-4 font-semibold text-xs uppercase tracking-wider">用户名</th>
<th class="px-6 py-4 font-semibold text-xs uppercase tracking-wider">邮箱</th>
<th class="px-6 py-4 font-semibold text-xs uppercase tracking-wider">手机号</th>
<th class="px-6 py-4 font-semibold text-xs uppercase tracking-wider">角色</th>
<th class="px-6 py-4 font-semibold text-xs uppercase tracking-wider whitespace-nowrap">注册时间</th>
<th class="px-6 py-4 font-semibold text-xs uppercase tracking-wider text-right">操作</th>
</tr>
</thead>
<tbody>
<tr
v-for="u in users"
:key="u.id"
class="border-b border-gray-100 last:border-b-0 hover:bg-gray-50/70 transition-colors"
>
<td class="px-6 py-4 text-gray-400 font-mono text-xs whitespace-nowrap">#{{ u.id }}</td>
<td class="px-6 py-4 font-semibold text-black whitespace-nowrap">{{ u.username }}</td>
<td class="px-6 py-4 text-gray-600">{{ u.email || '—' }}</td>
<td class="px-6 py-4 text-gray-600 whitespace-nowrap">{{ u.phone || '—' }}</td>
<td class="px-6 py-4 whitespace-nowrap">
<span
class="inline-flex items-center gap-1 px-2.5 py-1 rounded-full text-xs font-semibold"
:class="u.role === 'admin' ? 'bg-black text-white' : 'bg-gray-100 text-gray-600'"
>
<Icon v-if="u.role === 'admin'" name="ph:crown-simple" class="w-3.5 h-3.5" />
{{ u.role === 'admin' ? '管理员' : '用户' }}
</span>
</td>
<td class="px-6 py-4 text-gray-500 text-xs whitespace-nowrap">{{ formatDate(u.createdAt) }}</td>
<td class="px-6 py-4">
<div class="flex items-center justify-end gap-2">
<template v-if="u.id !== meId">
<button
@click="toggleRole(u)"
class="px-3 py-1.5 rounded-full text-xs font-semibold border transition-colors"
:class="u.role === 'admin'
? 'border-gray-200 bg-gray-100 text-gray-600 hover:bg-gray-200'
: 'border-black bg-black text-white hover:bg-gray-800'"
:title="u.role === 'admin' ? '设为普通用户' : '设为管理员'"
>
{{ u.role === 'admin' ? '设为用户' : '设为管理员' }}
</button>
<button
@click="removeUser(u)"
class="w-8 h-8 rounded-full flex items-center justify-center text-gray-400 hover:bg-red-50 hover:text-red-600 transition-colors"
title="删除用户"
>
<Icon name="ph:trash" class="w-4 h-4" />
</button>
</template>
<span v-else class="px-3 py-1.5 rounded-full text-xs font-semibold bg-gray-50 text-gray-400 border border-gray-100">
当前账号
</span>
</div>
</td>
</tr>
</tbody>
</table>
</div>
</div>
</section>
</template>
<script setup lang="ts">
import { computed, onMounted, ref } from 'vue'
/**
* 后台用户管理:列表 + 搜索/角色筛选 + 角色切换 + 删除确认 + 前端分页。
* - GET /api/admin/users;PATCH /api/admin/users/[id](角色切换,不能操作自己);DELETE /api/admin/users/[id]
*/
import { computed, onMounted, ref, watch } from 'vue'
import { useUserStore } from '~/stores/user'
import { useToastStore } from '~/stores/toast'
definePageMeta({ middleware: 'admin', layout: 'admin' })
useSeoMeta({ title: '用户管理' })
useHead({ title: '用户管理' })
interface AdminUser {
id: number
@@ -134,25 +19,15 @@ interface AdminUser {
createdAt: string
}
const toast = useToastStore()
const userStore = useUserStore()
const meId = computed(() => userStore.user?.id)
/* ---------- 列表 ---------- */
const users = ref<AdminUser[]>([])
const loading = ref(true)
const loadError = ref('')
const flash = ref('')
const flashKind = ref<'ok' | 'err'>('ok')
let flashTimer: ReturnType<typeof setTimeout> | null = null
const showFlash = (msg: string, kind: 'ok' | 'err' = 'ok') => {
flash.value = msg
flashKind.value = kind
if (flashTimer) clearTimeout(flashTimer)
flashTimer = setTimeout(() => {
flash.value = ''
}, 3000)
}
const loadUsers = async () => {
loading.value = true
loadError.value = ''
@@ -167,31 +42,83 @@ const loadUsers = async () => {
}
}
// 切换角色(user ↔ admin),后端拒绝修改自己的角色
onMounted(loadUsers)
/* ---------- 搜索 / 筛选 ---------- */
const keyword = ref('')
const roleFilter = ref<'all' | 'admin' | 'user'>('all')
const filteredUsers = computed(() => {
const kw = keyword.value.trim().toLowerCase()
return users.value.filter((u) => {
if (roleFilter.value !== 'all' && u.role !== roleFilter.value) return false
if (!kw) return true
return (
u.username.toLowerCase().includes(kw) ||
(u.email || '').toLowerCase().includes(kw) ||
(u.phone || '').toLowerCase().includes(kw)
)
})
})
const adminCount = computed(() => users.value.filter((u) => u.role === 'admin').length)
/* ---------- 前端分页 ---------- */
const pageSize = 15
const page = ref(1)
const totalPages = computed(() => Math.max(1, Math.ceil(filteredUsers.value.length / pageSize)))
const pagedUsers = computed(() => {
const p = Math.min(page.value, totalPages.value)
const start = (p - 1) * pageSize
return filteredUsers.value.slice(start, start + pageSize)
})
watch([keyword, roleFilter], () => {
page.value = 1
})
const changePage = (p: number) => {
page.value = Math.min(Math.max(1, p), totalPages.value)
}
/* ---------- 角色切换 ---------- */
const togglingId = ref<number | null>(null)
const toggleRole = async (u: AdminUser) => {
const next: AdminUser['role'] = u.role === 'admin' ? 'user' : 'admin'
togglingId.value = u.id
try {
await $fetch(`/api/admin/users/${u.id}`, {
method: 'PATCH',
body: { role: next },
})
await $fetch(`/api/admin/users/${u.id}`, { method: 'PATCH', body: { role: next } })
u.role = next
showFlash(`已将「${u.username}」设为${next === 'admin' ? '管理员' : '普通用户'}`)
} catch (err) {
console.error('toggle role error:', err)
showFlash((err as any)?.data?.message || '操作失败,请重试', 'err')
toast.success(`已将「${u.username}」设为${next === 'admin' ? '管理员' : '普通用户'}`)
} catch (err: any) {
toast.error(err?.data?.message || '操作失败,请重试')
} finally {
togglingId.value = null
}
}
const removeUser = async (u: AdminUser) => {
if (!window.confirm(`确定删除用户「${u.username}」吗?此操作不可恢复。`)) return
/* ---------- 删除 ---------- */
const confirmDelete = ref<AdminUser | null>(null)
const deleting = ref(false)
const askDelete = (u: AdminUser) => {
confirmDelete.value = u
}
const doDelete = async () => {
const u = confirmDelete.value
if (!u) return
deleting.value = true
try {
await $fetch(`/api/admin/users/${u.id}`, { method: 'DELETE' })
users.value = users.value.filter((x) => x.id !== u.id)
showFlash(`已删除用户「${u.username}」`)
} catch (err) {
console.error('delete user error:', err)
showFlash((err as any)?.data?.message || '删除失败,请重试', 'err')
toast.success(`已删除用户「${u.username}」`)
confirmDelete.value = null
} catch (err: any) {
toast.error(err?.data?.message || '删除失败,请重试')
} finally {
deleting.value = false
}
}
@@ -207,6 +134,143 @@ const formatDate = (raw?: string) => {
minute: '2-digit',
}).format(d)
}
onMounted(loadUsers)
</script>
<template>
<div>
<AdminPageHeader title="用户管理" subtitle="管理站点注册用户,调整角色或删除账号。">
<template #actions>
<AdminButton variant="secondary" size="sm" @click="loadUsers">
<Icon name="ph:arrows-clockwise" class="w-4 h-4" /> 刷新
</AdminButton>
</template>
</AdminPageHeader>
<!-- 统计 + 工具栏 -->
<div class="mb-4 flex flex-wrap items-center gap-x-4 gap-y-2">
<span class="text-sm text-gray-500">共 {{ users.length }} 个用户</span>
<span class="text-sm text-gray-400">· 管理员 {{ adminCount }} · 普通用户 {{ users.length - adminCount }}</span>
</div>
<div class="mb-5 flex flex-col sm:flex-row gap-3">
<div class="relative flex-1 sm:max-w-xs">
<Icon name="ph:magnifying-glass" class="w-4 h-4 text-gray-400 absolute left-3.5 top-1/2 -translate-y-1/2 pointer-events-none" />
<input
v-model="keyword"
type="text"
placeholder="搜索用户名 / 邮箱 / 手机号"
class="w-full rounded-xl border border-gray-200 bg-white py-2.5 pl-10 pr-9 text-sm outline-none transition-all focus:border-black focus:ring-2 focus:ring-black/10"
/>
<button
v-if="keyword"
@click="keyword = ''"
class="absolute right-2.5 top-1/2 -translate-y-1/2 w-5 h-5 rounded-full text-gray-400 hover:text-gray-600 hover:bg-gray-100 flex items-center justify-center"
aria-label="清空筛选"
>
<Icon name="ph:x" class="w-3.5 h-3.5" />
</button>
</div>
<AdminSelect
v-model="roleFilter"
:options="[
{ value: 'all', label: '全部角色' },
{ value: 'admin', label: '管理员' },
{ value: 'user', label: '普通用户' },
]"
class="w-full sm:w-40"
/>
</div>
<!-- 加载态 -->
<AdminCard v-if="loading">
<AdminSkeleton :rows="6" />
</AdminCard>
<!-- 错误态 -->
<AdminCard v-else-if="loadError">
<div class="py-10 text-center">
<Icon name="ph:warning-circle" class="w-10 h-10 text-gray-300 mx-auto mb-4" />
<p class="text-gray-500 mb-4">{{ loadError }}</p>
<AdminButton size="sm" @click="loadUsers">重新加载</AdminButton>
</div>
</AdminCard>
<!-- 空态 -->
<AdminEmptyState v-else-if="!users.length" icon="ph:users-three" title="暂无用户" description="还没有注册用户。" />
<AdminEmptyState
v-else-if="!filteredUsers.length"
icon="ph:magnifying-glass"
title="没有匹配的用户"
description="换个关键词或筛选条件试试。"
/>
<!-- 用户表格 -->
<template v-else>
<div class="rounded-2xl border border-gray-100 bg-white shadow-sm overflow-hidden">
<div class="overflow-x-auto">
<table class="w-full text-sm">
<thead>
<tr class="text-left text-gray-400 border-b border-gray-100 bg-gray-50">
<th class="px-5 py-4 font-semibold text-xs uppercase tracking-wider whitespace-nowrap">ID</th>
<th class="px-5 py-4 font-semibold text-xs uppercase tracking-wider">用户名</th>
<th class="px-5 py-4 font-semibold text-xs uppercase tracking-wider">邮箱</th>
<th class="px-5 py-4 font-semibold text-xs uppercase tracking-wider">手机号</th>
<th class="px-5 py-4 font-semibold text-xs uppercase tracking-wider">角色</th>
<th class="px-5 py-4 font-semibold text-xs uppercase tracking-wider whitespace-nowrap">注册时间</th>
<th class="px-5 py-4 font-semibold text-xs uppercase tracking-wider text-right">操作</th>
</tr>
</thead>
<tbody class="divide-y divide-gray-50">
<tr v-for="u in pagedUsers" :key="u.id" class="hover:bg-gray-50/60 transition-colors">
<td class="px-5 py-4 text-gray-400 font-mono text-xs whitespace-nowrap">#{{ u.id }}</td>
<td class="px-5 py-4 font-semibold text-black whitespace-nowrap">{{ u.username }}</td>
<td class="px-5 py-4 text-gray-600">{{ u.email || '—' }}</td>
<td class="px-5 py-4 text-gray-600 whitespace-nowrap">{{ u.phone || '—' }}</td>
<td class="px-5 py-4 whitespace-nowrap">
<AdminBadge :tone="u.role === 'admin' ? 'black' : 'gray'">
<Icon v-if="u.role === 'admin'" name="ph:crown-simple" class="w-3 h-3" />
{{ u.role === 'admin' ? '管理员' : '用户' }}
</AdminBadge>
</td>
<td class="px-5 py-4 text-gray-500 text-xs whitespace-nowrap">{{ formatDate(u.createdAt) }}</td>
<td class="px-5 py-4">
<div class="flex items-center justify-end gap-2">
<template v-if="u.id !== meId">
<AdminButton
size="sm"
:variant="u.role === 'admin' ? 'secondary' : 'primary'"
:loading="togglingId === u.id"
@click="toggleRole(u)"
>
{{ u.role === 'admin' ? '设为用户' : '设为管理员' }}
</AdminButton>
<AdminButton size="sm" variant="danger" @click="askDelete(u)">
<Icon name="ph:trash" class="w-3.5 h-3.5" /> 删除
</AdminButton>
</template>
<AdminBadge v-else tone="gray">当前账号</AdminBadge>
</div>
</td>
</tr>
</tbody>
</table>
</div>
</div>
<div class="mt-4">
<AdminPagination :total="filteredUsers.length" :page="page" :page-size="pageSize" @page="changePage" />
</div>
</template>
<!-- 删除确认 -->
<AdminConfirm
:open="!!confirmDelete"
:loading="deleting"
danger
:message="`确定删除用户「${confirmDelete?.username}」吗?此操作不可恢复。`"
@update:open="confirmDelete = null"
@confirm="doDelete"
/>
</div>
</template>
+196 -269
View File
@@ -1,14 +1,14 @@
<script setup lang="ts">
/**
* 后台作品管理:列表 + 新建/编辑表单。
* 后台作品管理:列表(搜索/分类/状态筛选 + 前端分页)+ 新建/编辑表单。
* - 列表来自 /api/admin/works(含未发布)
* - 新建 POST /api/admin/works;编辑 PATCH /api/admin/works/[id];删除 DELETE /api/admin/works/[id]
* - tags 逗号分隔输入;gallery 多 URL 行(每行可上传)
*/
import { onMounted, reactive, ref } from 'vue'
import { computed, onMounted, reactive, ref, watch } from 'vue'
import { useToastStore } from '~/stores/toast'
definePageMeta({ middleware: 'admin', layout: 'admin' })
useHead({ title: '作品管理' })
interface Work {
@@ -39,6 +39,8 @@ interface Work {
updatedAt: string
}
const toast = useToastStore()
const CATEGORIES = [
{ value: 'webDesign', label: '网页设计' },
{ value: 'branding', label: '品牌设计' },
@@ -66,18 +68,50 @@ const loadWorks = async () => {
onMounted(loadWorks)
/* ---------- 提示 ---------- */
const message = ref('')
const messageType = ref<'success' | 'error'>('success')
let toastTimer: ReturnType<typeof setTimeout> | undefined
/* ---------- 搜索 / 筛选 / 分页 ---------- */
const keyword = ref('')
const categoryFilter = ref<'all' | Work['category']>('all')
const statusFilter = ref<'all' | 'published' | 'draft'>('all')
const toast = (text: string, type: 'success' | 'error' = 'success') => {
message.value = text
messageType.value = type
if (toastTimer) clearTimeout(toastTimer)
toastTimer = setTimeout(() => (message.value = ''), 3000)
const filteredWorks = computed(() => {
const kw = keyword.value.trim().toLowerCase()
return works.value.filter((w) => {
if (categoryFilter.value !== 'all' && w.category !== categoryFilter.value) return false
if (statusFilter.value === 'published' && !w.published) return false
if (statusFilter.value === 'draft' && w.published) return false
if (!kw) return true
return (
w.titleZh.toLowerCase().includes(kw) ||
w.titleEn.toLowerCase().includes(kw) ||
w.slug.toLowerCase().includes(kw) ||
w.tags.some((t) => t.toLowerCase().includes(kw))
)
})
})
const pageSize = 10
const page = ref(1)
const totalPages = computed(() => Math.max(1, Math.ceil(filteredWorks.value.length / pageSize)))
const pagedWorks = computed(() => {
const p = Math.min(page.value, totalPages.value)
const start = (p - 1) * pageSize
return filteredWorks.value.slice(start, start + pageSize)
})
watch([keyword, categoryFilter, statusFilter], () => {
page.value = 1
})
const changePage = (p: number) => {
page.value = Math.min(Math.max(1, p), totalPages.value)
}
const headerSubtitle = computed(() => {
if (view.value === 'form') return editingId.value != null ? '编辑作品' : '新建作品'
return `共 ${works.value.length} 个作品`
})
/* ---------- 表单 ---------- */
const view = ref<'list' | 'form'>('list')
const editingId = ref<number | null>(null)
@@ -121,7 +155,7 @@ const openCreate = () => {
const openEdit = (w: Work) => {
if (w.id == null) {
toast('该条目缺少 id 字段,暂时无法编辑(后端待补)', 'error')
toast.error('该条目缺少 id 字段,暂时无法编辑(后端待补)')
return
}
editingId.value = w.id
@@ -197,10 +231,10 @@ const save = async () => {
}
if (editingId.value != null) {
await $fetch(`/api/admin/works/${editingId.value}`, { method: 'PATCH', body: payload })
toast('作品已更新')
toast.success('作品已更新')
} else {
await $fetch('/api/admin/works', { method: 'POST', body: payload })
toast('作品已创建')
toast.success('作品已创建')
}
await loadWorks()
view.value = 'list'
@@ -217,7 +251,7 @@ const deleting = ref(false)
const askDelete = (w: Work) => {
if (w.id == null) {
toast('该条目缺少 id 字段,暂时无法删除(后端待补)', 'error')
toast.error('该条目缺少 id 字段,暂时无法删除(后端待补)')
return
}
confirmDelete.value = w
@@ -229,11 +263,11 @@ const doDelete = async () => {
deleting.value = true
try {
await $fetch(`/api/admin/works/${w.id}`, { method: 'DELETE' })
toast(`已删除「${w.titleZh}」`)
toast.success(`已删除「${w.titleZh}」`)
confirmDelete.value = null
await loadWorks()
} catch (err: any) {
toast(err?.data?.message || '删除失败', 'error')
toast.error(err?.data?.message || '删除失败')
} finally {
deleting.value = false
}
@@ -279,87 +313,104 @@ const removeGalleryRow = (i: number) => form.gallery.splice(i, 1)
<template>
<div>
<!-- 页头 -->
<div class="flex items-center justify-between gap-4 mb-8">
<div>
<h1 class="text-2xl md:text-3xl font-bold text-black tracking-tight">作品管理</h1>
<p v-if="view === 'list'" class="mt-1 text-sm text-gray-500">共 {{ works.length }} 个作品</p>
</div>
<button
v-if="view === 'list'"
type="button"
@click="openCreate"
class="inline-flex items-center gap-2 px-4 py-2 rounded-lg bg-black text-white text-sm font-semibold hover:bg-gray-800 transition-colors"
>
<AdminPageHeader title="作品管理" :subtitle="headerSubtitle">
<template #actions>
<AdminButton v-if="view === 'list'" size="sm" @click="openCreate">
<Icon name="ph:plus" class="w-4 h-4" /> 新建作品
</button>
<button
v-else
type="button"
@click="backToList"
class="inline-flex items-center gap-2 px-4 py-2 rounded-lg border border-gray-200 bg-white text-sm font-semibold text-gray-700 hover:bg-gray-100 transition-colors"
>
</AdminButton>
<AdminButton v-else size="sm" variant="secondary" @click="backToList">
<Icon name="ph:arrow-left" class="w-4 h-4" /> 返回列表
</button>
</div>
<!-- 提示 -->
<div
v-if="message"
class="mb-6 px-4 py-3 rounded-xl text-sm font-medium border"
:class="messageType === 'success' ? 'bg-green-50 border-green-200 text-green-700' : 'bg-red-50 border-red-200 text-red-700'"
>
{{ message }}
</div>
</AdminButton>
</template>
</AdminPageHeader>
<!-- ==================== 列表视图 ==================== -->
<template v-if="view === 'list'">
<div v-if="loading" class="space-y-3">
<div
v-for="i in 6"
:key="i"
class="rounded-2xl bg-white border border-gray-100 shadow-sm p-5 h-16 animate-pulse"
></div>
</div>
<div
v-else-if="error"
class="rounded-2xl bg-white border border-gray-100 shadow-sm p-10 text-center"
>
<Icon name="ph:warning-circle" class="w-10 h-10 text-gray-300 mx-auto mb-4" />
<p class="text-gray-500 mb-4">{{ error }}</p>
<!-- 工具栏 -->
<div class="mb-5 flex flex-col sm:flex-row gap-3">
<div class="relative flex-1 sm:max-w-xs">
<Icon name="ph:magnifying-glass" class="w-4 h-4 text-gray-400 absolute left-3.5 top-1/2 -translate-y-1/2 pointer-events-none" />
<input
v-model="keyword"
type="text"
placeholder="搜索标题 / slug / 标签…"
class="w-full rounded-xl border border-gray-200 bg-white py-2.5 pl-10 pr-9 text-sm outline-none transition-all focus:border-black focus:ring-2 focus:ring-black/10"
/>
<button
type="button"
@click="loadWorks"
class="px-5 py-2 rounded-lg bg-black text-white text-sm font-semibold hover:bg-gray-800 transition-colors"
v-if="keyword"
@click="keyword = ''"
class="absolute right-2.5 top-1/2 -translate-y-1/2 w-5 h-5 rounded-full text-gray-400 hover:text-gray-600 hover:bg-gray-100 flex items-center justify-center"
aria-label="清空筛选"
>
重新加载
<Icon name="ph:x" class="w-3.5 h-3.5" />
</button>
</div>
<div
v-else-if="!works.length"
class="rounded-2xl bg-white border border-gray-100 shadow-sm p-14 text-center"
>
<Icon name="ph:image-square" class="w-10 h-10 text-gray-300 mx-auto mb-4" />
<p class="text-gray-500 mb-4">还没有作品,点击右上角「新建作品」创建第一个</p>
<AdminSelect
v-model="categoryFilter"
:options="[
{ value: 'all', label: '全部分类' },
...CATEGORIES,
]"
class="w-full sm:w-40"
/>
<AdminSelect
v-model="statusFilter"
:options="[
{ value: 'all', label: '全部状态' },
{ value: 'published', label: '已发布' },
{ value: 'draft', label: '草稿' },
]"
class="w-full sm:w-36"
/>
</div>
<div v-else class="rounded-2xl bg-white border border-gray-100 shadow-sm overflow-hidden">
<!-- 加载态 -->
<AdminCard v-if="loading">
<AdminSkeleton :rows="6" />
</AdminCard>
<!-- 错误态 -->
<AdminCard v-else-if="error">
<div class="py-10 text-center">
<Icon name="ph:warning-circle" class="w-10 h-10 text-gray-300 mx-auto mb-4" />
<p class="text-gray-500 mb-4">{{ error }}</p>
<AdminButton size="sm" @click="loadWorks">重新加载</AdminButton>
</div>
</AdminCard>
<!-- 空态 -->
<AdminEmptyState
v-else-if="!works.length"
icon="ph:image-square"
title="还没有作品"
description="点击右上角「新建作品」创建第一个。"
/>
<AdminEmptyState
v-else-if="!filteredWorks.length"
icon="ph:magnifying-glass"
title="没有匹配的作品"
description="换个关键词或筛选条件试试。"
/>
<!-- 列表 -->
<template v-else>
<div class="rounded-2xl border border-gray-100 bg-white shadow-sm overflow-hidden">
<div class="overflow-x-auto">
<table class="w-full text-sm">
<thead>
<tr class="text-left text-gray-400 border-b border-gray-100">
<th class="px-5 py-4 font-semibold">标题</th>
<th class="px-5 py-4 font-semibold">分类</th>
<th class="px-5 py-4 font-semibold">年份</th>
<th class="px-5 py-4 font-semibold">标签</th>
<th class="px-5 py-4 font-semibold">状态</th>
<th class="px-5 py-4 font-semibold text-right">操作</th>
<tr class="text-left text-gray-400 border-b border-gray-100 bg-gray-50">
<th class="px-5 py-4 font-semibold text-xs uppercase tracking-wider">标题</th>
<th class="px-5 py-4 font-semibold text-xs uppercase tracking-wider">分类</th>
<th class="px-5 py-4 font-semibold text-xs uppercase tracking-wider">年份</th>
<th class="px-5 py-4 font-semibold text-xs uppercase tracking-wider">标签</th>
<th class="px-5 py-4 font-semibold text-xs uppercase tracking-wider">状态</th>
<th class="px-5 py-4 font-semibold text-xs uppercase tracking-wider text-right">操作</th>
</tr>
</thead>
<tbody class="divide-y divide-gray-50">
<tr
v-for="w in works"
v-for="w in pagedWorks"
:key="w.slug"
class="hover:bg-gray-50/60 transition-colors"
>
@@ -381,9 +432,7 @@ const removeGalleryRow = (i: number) => form.gallery.splice(i, 1)
</div>
</td>
<td class="px-5 py-4">
<span class="px-2.5 py-1 rounded-full bg-gray-100 text-gray-700 text-xs font-medium">
{{ catLabel(w.category) }}
</span>
<AdminBadge tone="gray">{{ catLabel(w.category) }}</AdminBadge>
</td>
<td class="px-5 py-4 text-gray-600 whitespace-nowrap">{{ w.year || '-' }}</td>
<td class="px-5 py-4">
@@ -399,33 +448,22 @@ const removeGalleryRow = (i: number) => form.gallery.splice(i, 1)
</div>
</td>
<td class="px-5 py-4">
<AdminBadge :tone="w.published ? 'green' : 'amber'">
<span
class="px-2.5 py-1 rounded-full text-xs font-semibold inline-flex items-center gap-1"
:class="w.published ? 'bg-green-50 text-green-700' : 'bg-amber-50 text-amber-700'"
>
<span
class="w-1.5 h-1.5 rounded-full"
class="w-1.5 h-1.5 rounded-full inline-block"
:class="w.published ? 'bg-green-500' : 'bg-amber-500'"
></span>
{{ w.published ? '已发布' : '草稿' }}
</span>
</AdminBadge>
</td>
<td class="px-5 py-4">
<div class="flex items-center justify-end gap-2">
<button
type="button"
@click="openEdit(w)"
class="inline-flex items-center gap-1.5 px-3 py-1.5 rounded-lg bg-gray-100 text-gray-700 text-xs font-semibold hover:bg-gray-200 transition-colors"
>
<AdminButton size="sm" variant="secondary" @click="openEdit(w)">
<Icon name="ph:pencil-simple" class="w-3.5 h-3.5" /> 编辑
</button>
<button
type="button"
@click="askDelete(w)"
class="inline-flex items-center gap-1.5 px-3 py-1.5 rounded-lg bg-red-50 text-red-600 text-xs font-semibold hover:bg-red-100 transition-colors"
>
</AdminButton>
<AdminButton size="sm" variant="danger" @click="askDelete(w)">
<Icon name="ph:trash" class="w-3.5 h-3.5" /> 删除
</button>
</AdminButton>
</div>
</td>
</tr>
@@ -433,202 +471,103 @@ const removeGalleryRow = (i: number) => form.gallery.splice(i, 1)
</table>
</div>
</div>
<div class="mt-4">
<AdminPagination :total="filteredWorks.length" :page="page" :page-size="pageSize" @page="changePage" />
</div>
</template>
</template>
<!-- ==================== 表单视图 ==================== -->
<template v-else>
<div class="space-y-6 max-w-4xl">
<!-- 基本信息 -->
<section class="rounded-2xl bg-white border border-gray-100 shadow-sm p-5 md:p-6">
<h3 class="text-sm font-bold text-gray-900 mb-4 flex items-center gap-2">
<Icon name="ph:info" class="w-4 h-4 text-gray-400" /> 基本信息
</h3>
<AdminCard title="基本信息">
<div class="grid grid-cols-1 md:grid-cols-2 gap-5">
<div>
<label class="block text-sm font-semibold text-gray-800 mb-2">
slug<span class="text-red-500">*</span>
</label>
<input
<AdminInput
v-model="form.slug"
type="text"
label="slug"
required
placeholder="如 forma-digital"
class="w-full px-3 py-2.5 rounded-lg border border-gray-200 bg-white text-sm outline-none transition-all focus:border-black focus:ring-2 focus:ring-black/5 font-mono"
:error="formError && !/^[a-z0-9-]{2,64}$/.test(form.slug) ? 'slug 需为 2-64 位小写字母/数字/中划线' : ''"
/>
<p class="mt-1 text-xs text-gray-400">2-64 位小写字母 / 数字 / 中划线,用于前台链接</p>
</div>
<div>
<label class="block text-sm font-semibold text-gray-800 mb-2">分类</label>
<select
<AdminSelect
v-model="form.category"
class="w-full px-3 py-2.5 rounded-lg border border-gray-200 bg-white text-sm outline-none focus:border-black"
>
<option v-for="c in CATEGORIES" :key="c.value" :value="c.value">{{ c.label }}</option>
</select>
</div>
<div>
<label class="block text-sm font-semibold text-gray-800 mb-2">年份</label>
<input
v-model="form.year"
type="text"
placeholder="如 2026"
class="w-full px-3 py-2.5 rounded-lg border border-gray-200 bg-white text-sm outline-none focus:border-black"
label="分类"
:options="CATEGORIES"
/>
<AdminInput v-model="form.year" label="年份" placeholder="如 2026" />
<AdminInput v-model="tagsText" label="标签" placeholder="Web Design, React, E-commerce" />
<div>
<AdminInput v-model="form.url" label="外部链接(可选)" placeholder="https://… 留空则前台不显示访问按钮" />
</div>
<div>
<label class="block text-sm font-semibold text-gray-800 mb-2">
标签<span class="text-gray-400 font-normal">(逗号分隔)</span>
</label>
<input
v-model="tagsText"
type="text"
placeholder="Web Design, React, E-commerce"
class="w-full px-3 py-2.5 rounded-lg border border-gray-200 bg-white text-sm outline-none focus:border-black"
/>
</div>
<div>
<label class="block text-sm font-semibold text-gray-800 mb-2">
外部链接<span class="text-gray-400 font-normal">(可选)</span>
</label>
<input
v-model="form.url"
type="text"
placeholder="https://… 留空则前台不显示访问按钮"
class="w-full px-3 py-2.5 rounded-lg border border-gray-200 bg-white text-sm outline-none focus:border-black"
/>
</div>
<div>
<label class="block text-sm font-semibold text-gray-800 mb-2">发布状态</label>
<button
type="button"
class="inline-flex items-center gap-3 group mt-1"
@click="form.published = !form.published"
>
<span
class="relative w-11 h-6 rounded-full transition-colors duration-300"
:class="form.published ? 'bg-black' : 'bg-gray-300'"
>
<span
class="absolute top-0.5 left-0.5 w-5 h-5 rounded-full bg-white shadow transition-transform duration-300"
:class="form.published ? 'translate-x-5' : ''"
></span>
</span>
<p class="block text-sm font-semibold text-gray-800 mb-1.5">发布状态</p>
<div class="flex items-center gap-3 mt-1">
<AdminToggle v-model="form.published" />
<span class="text-sm" :class="form.published ? 'text-green-700 font-semibold' : 'text-gray-500'">
{{ form.published ? '已发布(前台可见)' : '草稿(前台隐藏)' }}
</span>
</button>
</div>
</div>
</section>
</div>
</AdminCard>
<!-- 标题与简介 -->
<section class="rounded-2xl bg-white border border-gray-100 shadow-sm p-5 md:p-6">
<h3 class="text-sm font-bold text-gray-900 mb-4 flex items-center gap-2">
<Icon name="ph:text-aa" class="w-4 h-4 text-gray-400" /> 标题与简介
</h3>
<AdminCard title="标题与简介">
<div class="grid grid-cols-1 lg:grid-cols-2 gap-5">
<div class="space-y-4">
<div>
<label class="block text-sm font-semibold text-gray-800 mb-2">中文标题<span class="text-red-500">*</span></label>
<input v-model="form.titleZh" type="text" class="w-full px-3 py-2.5 rounded-lg border border-gray-200 bg-white text-sm outline-none transition-all focus:border-black focus:ring-2 focus:ring-black/5" />
</div>
<div>
<label class="block text-sm font-semibold text-gray-800 mb-2">中文简介</label>
<textarea v-model="form.descriptionZh" rows="3" class="w-full px-3 py-2.5 rounded-lg border border-gray-200 bg-white text-sm outline-none transition-all focus:border-black focus:ring-2 focus:ring-black/5 resize-y"></textarea>
</div>
<AdminInput v-model="form.titleZh" label="中文标题" required />
<AdminTextarea v-model="form.descriptionZh" label="中文简介" :rows="3" />
</div>
<div class="space-y-4">
<div>
<label class="block text-sm font-semibold text-gray-800 mb-2">English Title<span class="text-red-500">*</span></label>
<input v-model="form.titleEn" type="text" class="w-full px-3 py-2.5 rounded-lg border border-gray-200 bg-white text-sm outline-none transition-all focus:border-black focus:ring-2 focus:ring-black/5" />
</div>
<div>
<label class="block text-sm font-semibold text-gray-800 mb-2">English Description</label>
<textarea v-model="form.descriptionEn" rows="3" class="w-full px-3 py-2.5 rounded-lg border border-gray-200 bg-white text-sm outline-none transition-all focus:border-black focus:ring-2 focus:ring-black/5 resize-y"></textarea>
<AdminInput v-model="form.titleEn" label="English Title" required />
<AdminTextarea v-model="form.descriptionEn" label="English Description" :rows="3" />
</div>
</div>
</div>
</section>
</AdminCard>
<!-- 项目详情(中英) -->
<section class="rounded-2xl bg-white border border-gray-100 shadow-sm p-5 md:p-6">
<h3 class="text-sm font-bold text-gray-900 mb-4 flex items-center gap-2">
<Icon name="ph:notebook" class="w-4 h-4 text-gray-400" /> 项目详情(中英各一组)
</h3>
<AdminCard title="项目详情(中英各一组)">
<div class="space-y-6">
<div class="grid grid-cols-1 lg:grid-cols-2 gap-5">
<div class="space-y-4">
<div>
<label class="block text-sm font-semibold text-gray-800 mb-2">中文概述(Overview)</label>
<textarea v-model="form.overviewZh" rows="4" class="w-full px-3 py-2.5 rounded-lg border border-gray-200 bg-white text-sm outline-none transition-all focus:border-black focus:ring-2 focus:ring-black/5 resize-y"></textarea>
</div>
<div>
<label class="block text-sm font-semibold text-gray-800 mb-2">中文挑战(Challenge)</label>
<textarea v-model="form.challengeZh" rows="3" class="w-full px-3 py-2.5 rounded-lg border border-gray-200 bg-white text-sm outline-none transition-all focus:border-black focus:ring-2 focus:ring-black/5 resize-y"></textarea>
</div>
<div>
<label class="block text-sm font-semibold text-gray-800 mb-2">中文方案(Solution)</label>
<textarea v-model="form.solutionZh" rows="3" class="w-full px-3 py-2.5 rounded-lg border border-gray-200 bg-white text-sm outline-none transition-all focus:border-black focus:ring-2 focus:ring-black/5 resize-y"></textarea>
</div>
<AdminTextarea v-model="form.overviewZh" label="中文概述(Overview)" :rows="4" />
<AdminTextarea v-model="form.challengeZh" label="中文挑战(Challenge)" :rows="3" />
<AdminTextarea v-model="form.solutionZh" label="中文方案(Solution)" :rows="3" />
</div>
<div class="space-y-4">
<div>
<label class="block text-sm font-semibold text-gray-800 mb-2">English Overview</label>
<textarea v-model="form.overviewEn" rows="4" class="w-full px-3 py-2.5 rounded-lg border border-gray-200 bg-white text-sm outline-none transition-all focus:border-black focus:ring-2 focus:ring-black/5 resize-y"></textarea>
</div>
<div>
<label class="block text-sm font-semibold text-gray-800 mb-2">English Challenge</label>
<textarea v-model="form.challengeEn" rows="3" class="w-full px-3 py-2.5 rounded-lg border border-gray-200 bg-white text-sm outline-none transition-all focus:border-black focus:ring-2 focus:ring-black/5 resize-y"></textarea>
</div>
<div>
<label class="block text-sm font-semibold text-gray-800 mb-2">English Solution</label>
<textarea v-model="form.solutionEn" rows="3" class="w-full px-3 py-2.5 rounded-lg border border-gray-200 bg-white text-sm outline-none transition-all focus:border-black focus:ring-2 focus:ring-black/5 resize-y"></textarea>
</div>
<AdminTextarea v-model="form.overviewEn" label="English Overview" :rows="4" />
<AdminTextarea v-model="form.challengeEn" label="English Challenge" :rows="3" />
<AdminTextarea v-model="form.solutionEn" label="English Solution" :rows="3" />
</div>
</div>
<div class="grid grid-cols-1 lg:grid-cols-2 gap-5">
<div>
<label class="block text-sm font-semibold text-gray-800 mb-2">中文客户(Client)</label>
<input v-model="form.clientZh" type="text" class="w-full px-3 py-2.5 rounded-lg border border-gray-200 bg-white text-sm outline-none focus:border-black" />
</div>
<div>
<label class="block text-sm font-semibold text-gray-800 mb-2">English Client</label>
<input v-model="form.clientEn" type="text" class="w-full px-3 py-2.5 rounded-lg border border-gray-200 bg-white text-sm outline-none focus:border-black" />
</div>
<div>
<label class="block text-sm font-semibold text-gray-800 mb-2">中文周期(Duration)</label>
<input v-model="form.durationZh" type="text" placeholder="如 3 个月" class="w-full px-3 py-2.5 rounded-lg border border-gray-200 bg-white text-sm outline-none focus:border-black" />
</div>
<div>
<label class="block text-sm font-semibold text-gray-800 mb-2">English Duration</label>
<input v-model="form.durationEn" type="text" placeholder="如 3 months" class="w-full px-3 py-2.5 rounded-lg border border-gray-200 bg-white text-sm outline-none focus:border-black" />
<AdminInput v-model="form.clientZh" label="中文客户(Client)" />
<AdminInput v-model="form.clientEn" label="English Client" />
<AdminInput v-model="form.durationZh" label="中文周期(Duration)" placeholder="如 3 个月" />
<AdminInput v-model="form.durationEn" label="English Duration" placeholder="如 3 months" />
</div>
</div>
</div>
</section>
</AdminCard>
<!-- 封面图 -->
<section class="rounded-2xl bg-white border border-gray-100 shadow-sm p-5 md:p-6">
<h3 class="text-sm font-bold text-gray-900 mb-4 flex items-center gap-2">
<Icon name="ph:image" class="w-4 h-4 text-gray-400" /> 封面图
</h3>
<AdminCard title="封面图">
<AdminImageUpload v-model="form.image" label="封面图" />
</section>
</AdminCard>
<!-- 作品图集 -->
<section class="rounded-2xl bg-white border border-gray-100 shadow-sm p-5 md:p-6">
<div class="flex items-center justify-between mb-4">
<h3 class="text-sm font-bold text-gray-900 flex items-center gap-2">
<Icon name="ph:images" class="w-4 h-4 text-gray-400" /> 作品图集(Gallery)
</h3>
<button
type="button"
@click="addGalleryRow"
class="flex items-center gap-1.5 px-3 py-1.5 rounded-lg border border-gray-200 text-xs font-semibold text-gray-700 hover:bg-gray-50 transition-colors"
>
<AdminCard>
<template #actions>
<AdminButton size="sm" variant="secondary" @click="addGalleryRow">
<Icon name="ph:plus" class="w-3.5 h-3.5" /> 添加图片
</button>
</div>
</AdminButton>
</template>
<template #default>
<div class="space-y-3">
<div
v-for="(url, i) in form.gallery"
@@ -670,40 +609,28 @@ const removeGalleryRow = (i: number) => form.gallery.splice(i, 1)
<p v-if="galleryError" class="text-xs text-red-600">{{ galleryError }}</p>
</div>
<input ref="galleryFileInput" type="file" accept="image/*" class="hidden" @change="onGalleryFile" />
</section>
</template>
</AdminCard>
<!-- 提交 -->
<div class="flex items-center justify-end gap-3">
<p v-if="formError" class="mr-auto text-sm text-red-600">{{ formError }}</p>
<button
type="button"
@click="backToList"
class="px-5 py-2.5 rounded-lg border border-gray-200 bg-white text-sm font-semibold text-gray-700 hover:bg-gray-100 transition-colors"
>
取消
</button>
<button
type="button"
:disabled="saving"
@click="save"
class="px-6 py-2.5 rounded-lg bg-black text-white text-sm font-semibold hover:bg-gray-800 transition-colors disabled:opacity-60 inline-flex items-center gap-2"
>
<Icon v-if="saving" name="ph:circle-notch" class="w-4 h-4 animate-spin" />
<AdminButton variant="secondary" @click="backToList">取消</AdminButton>
<AdminButton :loading="saving" @click="save">
{{ saving ? '保存中…' : editingId != null ? '保存修改' : '创建作品' }}
</button>
</AdminButton>
</div>
</div>
</template>
<!-- 删除确认 -->
<AdminConfirmDialog
<AdminConfirm
:open="!!confirmDelete"
:loading="deleting"
title="删除作品"
danger
:message="`确定要删除「${confirmDelete?.titleZh}」吗?该作品下的所有收藏将一并删除,此操作不可撤销。`"
confirm-text="删除"
@update:open="confirmDelete = null"
@confirm="doDelete"
@cancel="confirmDelete = null"
/>
</div>
</template>
+6 -11
View File
@@ -139,7 +139,7 @@
</div>
<div>
<h3 class="text-base md:text-lg font-bold text-gray-900 mb-2">Email</h3>
<a :href="`mailto:${siteConfig.email}`" class="text-sm md:text-base text-gray-600 hover:text-black transition-colors duration-300">
<a :href="`mailto:${settings?.contact.email}`" class="text-sm md:text-base text-gray-600 hover:text-black transition-colors duration-300">
{{ t('contact.info.email') }}
</a>
</div>
@@ -193,15 +193,16 @@
</template>
<script setup lang="ts">
import { nextTick, onBeforeUnmount, onMounted, ref, reactive } from 'vue'
import { nextTick, onBeforeUnmount, onMounted, ref, reactive, computed } from 'vue'
import { useI18n } from 'vue-i18n'
import { useSeoMeta } from '#imports'
import gsap from 'gsap'
import { useAppStore } from '~/stores/app'
import { siteConfig } from '~/config/site'
import { useSiteSettings } from '~/composables/useSiteSettings'
const { t } = useI18n()
const appStore = useAppStore()
const { settings } = useSiteSettings()
const headerWrapRef = ref<HTMLElement | null>(null)
const titleRef = ref<HTMLElement | null>(null)
@@ -350,14 +351,8 @@ onBeforeUnmount(() => {
contactCtx?.revert()
})
interface SocialLink {
name: string
icon: string
url: string
}
// 社交链接统一取自站点配置(单一事实源)
const socials: SocialLink[] = siteConfig.socials
// 社交链接统一取自站点动态配置(后台可改)
const socials = computed(() => settings?.socials ?? [])
</script>
<style scoped>
+4 -35
View File
@@ -15,7 +15,7 @@
style="opacity: 0; visibility: hidden;"
>
<a
v-for="tool in toolsData"
v-for="tool in settings?.tools ?? []"
:key="tool.id"
:href="tool.url"
target="_blank"
@@ -38,7 +38,7 @@
</div>
<h3 class="text-lg md:text-2xl font-bold mb-2 md:mb-3 text-black">{{ tool.name }}</h3>
<p class="text-sm md:text-base text-gray-600 leading-snug md:leading-relaxed flex-grow">{{ t(`tools.items.${tool.id}`) }}</p>
<p class="text-sm md:text-base text-gray-600 leading-snug md:leading-relaxed flex-grow">{{ locale === 'zh' ? tool.descZh : tool.descEn }}</p>
</div>
</a>
</div>
@@ -52,8 +52,9 @@ import { useSeoMeta } from '#imports'
import gsap from 'gsap'
import { useAppStore } from '~/stores/app'
const { t } = useI18n()
const { t, locale } = useI18n()
const appStore = useAppStore()
const { settings } = useSiteSettings()
const headerWrapRef = ref<HTMLElement | null>(null)
const titleRef = ref<HTMLElement | null>(null)
@@ -123,38 +124,6 @@ onMounted(() => {
onBeforeUnmount(() => {
cardsCtx?.revert()
})
interface ToolItem {
id: string
name: string
url: string
icon: string
color: string
}
const toolsData: ToolItem[] = [
{
id: 'drawio',
name: 'Drawio',
url: 'https://drawio.virtheart.com',
icon: 'ph:flow-arrow-duotone',
color: 'from-orange-50/50 to-amber-100/50'
},
{
id: 'excalidraw',
name: 'Excalidraw',
url: 'https://excalidraw.virtheart.com',
icon: 'ph:pencil-circle-duotone',
color: 'from-purple-50/50 to-indigo-100/50'
},
{
id: 'itTools',
name: 'IT-Tools',
url: 'https://ittools.virtheart.com',
icon: 'ph:wrench-duotone',
color: 'from-blue-50/50 to-cyan-100/50'
}
]
</script>
<style scoped>
+31
View File
@@ -0,0 +1,31 @@
import { defineStore } from 'pinia'
import { ref } from 'vue'
export interface ToastItem {
id: number
type: 'success' | 'error' | 'info'
message: string
}
/** 全局 toast 通知(后台各页统一反馈) */
export const useToastStore = defineStore('toast', () => {
const toasts = ref<ToastItem[]>([])
let seq = 0
const remove = (id: number) => {
toasts.value = toasts.value.filter((t) => t.id !== id)
}
const show = (type: ToastItem['type'], message: string) => {
const id = ++seq
toasts.value.push({ id, type, message })
setTimeout(() => remove(id), 3200)
return id
}
const success = (message: string) => show('success', message)
const error = (message: string) => show('error', message)
const info = (message: string) => show('info', message)
return { toasts, show, success, error, info, remove }
})
+6
View File
@@ -90,6 +90,12 @@ kubectl create secret generic app-secrets -n "${NAMESPACE}" \
--from-literal="NUXT_CONTACT_TO=${CONTACT_TO:-}" \
--from-literal="NUXT_ADMIN_EMAILS=${ADMIN_EMAILS:-}" \
--from-literal="NUXT_ADMIN_INITIAL_PASSWORD=${ADMIN_INITIAL_PASSWORD}" \
--from-literal="NUXT_OSS_ENDPOINT=${OSS_ENDPOINT:-}" \
--from-literal="NUXT_OSS_ACCESS_KEY=${OSS_ACCESS_KEY:-}" \
--from-literal="NUXT_OSS_SECRET_KEY=${OSS_SECRET_KEY:-}" \
--from-literal="NUXT_OSS_BUCKET=${OSS_BUCKET:-}" \
--from-literal="NUXT_OSS_REGION=${OSS_REGION:-us-east-1}" \
--from-literal="NUXT_OSS_PUBLIC_BASE=${OSS_PUBLIC_BASE:-}" \
--dry-run=client -o yaml | kubectl apply -f - >/dev/null
kubectl create configmap app-config -n "${NAMESPACE}" \
+4 -1
View File
@@ -450,7 +450,10 @@
"success": "Account deleted",
"wrongPassword": "Incorrect password",
"confirmText": "Delete your account permanently? This cannot be undone."
}
},
"statFavorites": "Favorites",
"statComments": "Comments",
"statJoined": "Joined"
},
"comments": {
"title": "Comments",
+4 -1
View File
@@ -450,7 +450,10 @@
"success": "账号已删除",
"wrongPassword": "密码不正确",
"confirmText": "确定要永久删除账号吗?此操作不可撤销。"
}
},
"statFavorites": "收藏",
"statComments": "评论",
"statJoined": "加入于"
},
"comments": {
"title": "评论",
+7
View File
@@ -33,6 +33,13 @@ export default defineNuxtConfig({
contactTo: '',
adminEmails: '',
adminInitialPassword: '',
// OSS 文件存储(RustFS / S3 v4 兼容;凭据仅走环境变量注入,绝不写入仓库)
ossEndpoint: '',
ossAccessKey: '',
ossSecretKey: '',
ossBucket: '',
ossRegion: 'us-east-1',
ossPublicBase: '',
public: {
// 客户端可见(环境变量:NUXT_PUBLIC_SITE_URL),用于 sitemap/robots/og 等绝对链接
siteUrl: '',
+10
View File
@@ -0,0 +1,10 @@
import { requireAdmin } from '../../utils/auth'
import { getSettings } from '../../utils/settings'
/**
* 后台读取站点配置
*/
export default defineEventHandler((event) => {
requireAdmin(event)
return getSettings()
})
+44
View File
@@ -0,0 +1,44 @@
import { readBody, createError } from 'h3'
import { requireAdmin } from '../../utils/auth'
import { getSettings, updateSetting } from '../../utils/settings'
import { writeAudit } from '../../utils/audit'
/**
* 后台更新站点配置。
* body: { settings: Partial<SiteSettings> } —— 按叶节点展开写库,未提供的项保持不变。
*/
export default defineEventHandler(async (event) => {
requireAdmin(event)
const body = await readBody(event)
const patch = body?.settings
if (!patch || typeof patch !== 'object' || Array.isArray(patch)) {
throw createError({ statusCode: 400, message: '缺少配置内容', data: { code: 'VALIDATION_ERROR' } })
}
// 将嵌套对象展开为点分叶键(数组整体作为一个值)
const flatten = (obj: Record<string, unknown>, prefix = '', out: Record<string, unknown> = {}) => {
for (const [k, v] of Object.entries(obj)) {
const key = prefix ? `${prefix}.${k}` : k
if (v && typeof v === 'object' && !Array.isArray(v)) {
flatten(v as Record<string, unknown>, key, out)
} else {
out[key] = v
}
}
return out
}
const flat = flatten(patch)
const keys = Object.keys(flat)
if (keys.length === 0) {
throw createError({ statusCode: 400, message: '没有可更新的配置', data: { code: 'VALIDATION_ERROR' } })
}
for (const [k, v] of Object.entries(flat)) {
updateSetting(k, v)
}
writeAudit(event, 'update', 'settings', keys.slice(0, 5).join(','))
return { ok: true, settings: getSettings() }
})
+17 -6
View File
@@ -4,6 +4,7 @@ import { dirname, join } from 'node:path'
import { randomBytes } from 'node:crypto'
import { requireAdmin } from '../../utils/auth'
import { getConfig } from '../../utils/config'
import { getOssConfig, putObject } from '../../utils/s3'
import { writeAudit } from '../../utils/audit'
const MAX_SIZE = 8 * 1024 * 1024 // 8MB
@@ -17,8 +18,9 @@ const EXT_BY_TYPE: Record<string, string> = {
}
/**
* 后台图片上传 -> 保存到 PVC 的 uploads 目录(/data/uploads),
* 通过 /uploads/<name> 对外提供。
* 后台图片上传:
* - OSS 已配置 -> 上传到桶 arcticnewone(key: images/<name>),URL /uploads/images/<name>
* - OSS 未配置 -> 回退写入本地 /data/uploads(兼容无 OSS 环境)
*/
export default defineEventHandler(async (event) => {
requireAdmin(event)
@@ -39,10 +41,19 @@ export default defineEventHandler(async (event) => {
}
const name = `${Date.now()}-${randomBytes(6).toString('hex')}.${ext}`
const oss = getOssConfig()
if (oss) {
const key = `images/${name}`
await putObject(key, Buffer.from(file.data), type)
writeAudit(event, 'upload', `oss:${key}`)
return { ok: true, url: `/uploads/images/${name}` }
}
// 本地回退(保留历史行为,兼容无 OSS 环境)
const dir = join(dirname(getConfig().dbPath), 'uploads')
mkdirSync(dir, { recursive: true })
writeFileSync(join(dir, name), file.data)
writeAudit(event, 'upload', `upload:${name}`)
return { ok: true, url: `/uploads/${name}` }
writeFileSync(join(dir, name), Buffer.from(file.data))
writeAudit(event, 'upload', `local:${name}`)
return { ok: true, url: `/uploads/${name}` }
})
+41
View File
@@ -0,0 +1,41 @@
import { getQuery, createError } from 'h3'
import { requireAdmin } from '../../utils/auth'
import { getConfig } from '../../utils/config'
import { getOssConfig, deleteObject } from '../../utils/s3'
import { writeAudit } from '../../utils/audit'
import { unlinkSync, existsSync } from 'node:fs'
import { join, dirname } from 'node:path'
/**
* 后台删除上传的文件(DELETE /api/admin/uploads?name=<key>)
* - OSS 已配置 -> deleteObject(name)(name 为完整对象 key,如 images/abc.png)
* - 否则回退删除本地文件
*/
export default defineEventHandler((event) => {
requireAdmin(event)
const q = getQuery(event)
const name = String(q?.name ?? '')
if (!name || name.includes('..')) {
throw createError({ statusCode: 400, message: '非法文件名', data: { code: 'VALIDATION_ERROR' } })
}
const oss = getOssConfig()
if (oss) {
deleteObject(name).then(() => writeAudit(event, 'delete', `oss:${name}`))
return { ok: true }
}
// 本地回退:仅允许纯文件名
const basename = name.split('/').pop() ?? ''
if (!basename || basename.includes('\\')) {
throw createError({ statusCode: 400, message: '非法文件名', data: { code: 'VALIDATION_ERROR' } })
}
const filePath = join(dirname(getConfig().dbPath), 'uploads', basename)
if (!existsSync(filePath)) {
throw createError({ statusCode: 404, message: '文件不存在', data: { code: 'NOT_FOUND' } })
}
unlinkSync(filePath)
writeAudit(event, 'delete', `local:${basename}`)
return { ok: true }
})
+13 -5
View File
@@ -1,15 +1,24 @@
import { requireAdmin } from '../../utils/auth'
import { getConfig } from '../../utils/config'
import { getOssConfig, listObjectsV2 } from '../../utils/s3'
import { readdirSync, statSync } from 'node:fs'
import { join, dirname } from 'node:path'
/**
* 后台图片管理:列出 /data/uploads 下的文件
* 后台图片管理:列出上传的文件
* - OSS 已配置 -> ListObjectsV2(prefix=images/)
* - 否则回退本地 /data/uploads
*/
export default defineEventHandler((event) => {
export default defineEventHandler(async (event) => {
requireAdmin(event)
const dir = join(dirname(getConfig().dbPath), 'uploads')
const oss = getOssConfig()
if (oss) {
const files = await listObjectsV2('images/')
return { files, storage: 'oss' }
}
const dir = join(dirname(getConfig().dbPath), 'uploads')
const files: Array<{ name: string; size: number; modified: string; url: string }> = []
try {
for (const name of readdirSync(dir)) {
@@ -21,7 +30,6 @@ export default defineEventHandler((event) => {
} catch {
// 目录可能尚不存在
}
files.sort((a, b) => b.modified.localeCompare(a.modified))
return { files }
return { files, storage: 'local' }
})
-28
View File
@@ -1,28 +0,0 @@
import { createError } from 'h3'
import { requireAdmin } from '../../../utils/auth'
import { getConfig } from '../../../utils/config'
import { writeAudit } from '../../../utils/audit'
import { unlinkSync, existsSync } from 'node:fs'
import { join, dirname } from 'node:path'
/**
* 后台删除上传的图片
*/
export default defineEventHandler((event) => {
requireAdmin(event)
const name = getRouterParam(event, 'name') ?? ''
// 防目录穿越:仅允许纯文件名
if (!name || name.includes('/') || name.includes('\\') || name.includes('..')) {
throw createError({ statusCode: 400, message: '非法文件名', data: { code: 'VALIDATION_ERROR' } })
}
const filePath = join(dirname(getConfig().dbPath), 'uploads', name)
if (!existsSync(filePath)) {
throw createError({ statusCode: 404, message: '文件不存在', data: { code: 'NOT_FOUND' } })
}
unlinkSync(filePath)
writeAudit(event, 'delete', `upload:${name}`)
return { ok: true }
})
+8
View File
@@ -0,0 +1,8 @@
import { getSettings } from '../utils/settings'
/**
* 站点公开配置(前台读取,SSR 友好)
*/
export default defineEventHandler(() => {
return getSettings()
})
+4 -2
View File
@@ -1,4 +1,5 @@
import { getConfig } from '../utils/config'
import { getSettings } from '../utils/settings'
import { listArticles } from '../utils/content'
const escapeXml = (s: string) =>
@@ -13,6 +14,7 @@ const escapeXml = (s: string) =>
*/
export default defineEventHandler(() => {
const { siteUrl } = getConfig()
const { site } = getSettings()
const articles = listArticles({ publishedOnly: true })
const items = articles
@@ -36,9 +38,9 @@ export default defineEventHandler(() => {
const xml = `<?xml version="1.0" encoding="UTF-8"?>
<rss version="2.0" xmlns:atom="http://www.w3.org/2005/Atom">
<channel>
<title>ArcticNewOne</title>
<title>${escapeXml(site.name)}</title>
<link>${siteUrl}</link>
<description>北极新一工作室的最新动态与洞察</description>
<description>${escapeXml(site.description.zh)}</description>
<language>zh-cn</language>
<atom:link href="${siteUrl}/feed.xml" rel="self" type="application/rss+xml"/>
${items}
+32 -12
View File
@@ -2,6 +2,7 @@ import { createError } from 'h3'
import { readFileSync, existsSync } from 'node:fs'
import { join, dirname, normalize } from 'node:path'
import { getConfig } from '../../utils/config'
import { getOssConfig, getObject } from '../../utils/s3'
const MIME: Record<string, string> = {
png: 'image/png',
@@ -13,27 +14,46 @@ const MIME: Record<string, string> = {
avif: 'image/avif',
}
/**
* 服务上传的图片(存于 PVC uploads 目录)
*/
export default defineEventHandler((event) => {
const path = getRouterParam(event, 'path') ?? ''
const base = normalize(join(dirname(getConfig().dbPath), 'uploads'))
const filePath = normalize(join(base, path))
const mimeFromName = (name: string) => MIME[name.split('.').pop()?.toLowerCase() ?? ''] || 'application/octet-stream'
// 防目录穿越
if (!filePath.startsWith(base + '/') && filePath !== base) {
/**
* 服务上传的图片:
* - OSS 已配置 -> 从桶 arcticnewone 拉取(key 为 /uploads/<path> 的 path)
* - OSS 无该对象或未配置 -> 回退读取本地 /data/uploads(兼容历史已上传内容)
*/
export default defineEventHandler(async (event) => {
const path = getRouterParam(event, 'path') ?? ''
const oss = getOssConfig()
if (oss) {
try {
const res = await getObject(path)
if (res) {
return new Response(res.body, {
headers: {
'Content-Type': res.headers.get('content-type') || mimeFromName(path),
'Cache-Control': 'public, max-age=31536000, immutable',
},
})
}
} catch (err) {
console.error('[uploads] oss read failed, fallback to local:', err)
}
}
// 本地回退
const base = normalize(join(dirname(getConfig().dbPath), 'uploads'))
const filePath = normalize(join(base, path.split('/').join('/')))
if (!filePath.startsWith(base + '/')) {
throw createError({ statusCode: 403, message: 'Forbidden' })
}
if (!existsSync(filePath)) {
throw createError({ statusCode: 404, message: 'Not Found' })
}
const ext = filePath.split('.').pop()?.toLowerCase() ?? ''
const data = readFileSync(filePath)
return new Response(new Uint8Array(data), {
headers: {
'Content-Type': MIME[ext] || 'application/octet-stream',
'Content-Type': mimeFromName(filePath),
'Cache-Control': 'public, max-age=31536000, immutable',
},
})
+17
View File
@@ -28,6 +28,15 @@ export interface AppConfig {
adminEmails: string[]
/** 首次初始化时预置 admin 账号的密码(NUXT_ADMIN_INITIAL_PASSWORD),未设则不预置 */
adminInitialPassword: string
/** OSS 文件存储(RustFS / S3 v4 兼容) */
oss: {
endpoint: string
accessKey: string
secretKey: string
bucket: string
region: string
publicBase: string
}
siteUrl: string
}
@@ -49,6 +58,14 @@ export function getConfig(): AppConfig {
.map((s) => s.trim().toLowerCase())
.filter(Boolean),
adminInitialPassword: String((c as any).adminInitialPassword || ''),
oss: {
endpoint: String((c as any).ossEndpoint || '').replace(/^https?:\/\//, '').replace(/\/$/, ''),
accessKey: String((c as any).ossAccessKey || ''),
secretKey: String((c as any).ossSecretKey || ''),
bucket: String((c as any).ossBucket || ''),
region: String((c as any).ossRegion || 'us-east-1'),
publicBase: String((c as any).ossPublicBase || '').replace(/\/$/, ''),
},
siteUrl: String((c.public as { siteUrl?: string })?.siteUrl || '').replace(/\/$/, ''),
}
}
+6
View File
@@ -167,6 +167,12 @@ function migrate(db: Database.Database): void {
);
CREATE INDEX IF NOT EXISTS idx_audit_created ON audit_logs(created_at);
-- 业务动态配置(后台可改;value 为 JSON 字符串)
CREATE TABLE IF NOT EXISTS settings (
key TEXT PRIMARY KEY,
value TEXT NOT NULL
);
`)
// 老库迁移:为已存在的表补充新增列(SQLite 不支持 ADD COLUMN IF NOT EXISTS)
+121
View File
@@ -0,0 +1,121 @@
import { getConfig } from './config'
import { sha256Hex, signRequest } from './sigv4'
/**
* 极简 S3 客户端(RustFS / S3 v4 兼容,零第三方依赖)。
* 手写 AWS SigV4 签名:putObject / getObject / deleteObject / listObjectsV2。
* 配置来自 env(NUXT_OSS_*),凭据绝不写入仓库。
*/
export interface OssConfig {
endpoint: string
accessKey: string
secretKey: string
bucket: string
region: string
publicBase: string
}
export function getOssConfig(): OssConfig | null {
const { oss } = getConfig()
if (!oss.endpoint || !oss.accessKey || !oss.secretKey || !oss.bucket) return null
return oss
}
export const isOssConfigured = (): boolean => getOssConfig() !== null
const encodeKey = (key: string) => key.split('/').map(encodeURIComponent).join('/')
const qs = (q: Record<string, string>) => {
const s = Object.keys(q)
.map((k) => `${encodeURIComponent(k)}=${encodeURIComponent(String(q[k]))}`)
.join('&')
return s ? `?${s}` : ''
}
async function s3Request(
method: string,
key: string,
opts: { query?: Record<string, string>; body?: string | Buffer; contentType?: string; isList?: boolean } = {},
): Promise<Response> {
const cfg = getOssConfig()
if (!cfg) throw new Error('OSS 未配置')
const path = opts.isList ? `/${cfg.bucket}` : `/${cfg.bucket}/${encodeKey(key)}`
const body = opts.body ?? ''
const bodyHash = sha256Hex(body)
const date = new Date().toISOString()
const headers: Record<string, string> = {
host: cfg.endpoint,
'x-amz-content-sha256': bodyHash,
...(opts.contentType ? { 'content-type': opts.contentType } : {}),
}
const { authorization, amzDate } = signRequest({
method,
path,
query: opts.query ?? {},
headers,
bodyHash,
date,
accessKey: cfg.accessKey,
secretKey: cfg.secretKey,
region: cfg.region,
})
headers['x-amz-date'] = amzDate
const url = `https://${cfg.endpoint}${path}${qs(opts.query ?? {})}`
return fetch(url, {
method,
headers: { ...headers, authorization },
body: method === 'GET' || method === 'DELETE' ? undefined : body,
})
}
// ---------- 对象操作 ----------
export async function putObject(key: string, body: Buffer, contentType: string): Promise<string> {
const res = await s3Request('PUT', key, { body, contentType })
if (!res.ok) throw new Error(`OSS 上传失败: ${res.status}`)
return key
}
export async function getObject(key: string): Promise<Response | null> {
const res = await s3Request('GET', key)
if (res.status === 404) return null
if (!res.ok) throw new Error(`OSS 读取失败: ${res.status}`)
return res
}
export async function deleteObject(key: string): Promise<boolean> {
const res = await s3Request('DELETE', key)
return res.ok || res.status === 204
}
export interface OssFile {
name: string
size: number
modified: string
url: string
}
export async function listObjectsV2(prefix = ''): Promise<OssFile[]> {
const res = await s3Request('GET', '', {
isList: true,
query: { 'list-type': '2', prefix, 'max-keys': '1000' },
})
if (!res.ok) throw new Error(`OSS 列表失败: ${res.status}`)
const xml = await res.text()
const files: OssFile[] = []
const contentRe = /<Contents>([\s\S]*?)<\/Contents>/g
let m: RegExpExecArray | null
while ((m = contentRe.exec(xml))) {
const item = m[1]
const name = /<Key>([\s\S]*?)<\/Key>/.exec(item)?.[1]
if (!name) continue
const size = Number(/<Size>([\s\S]*?)<\/Size>/.exec(item)?.[1] || 0)
const modified = /<LastModified>([\s\S]*?)<\/LastModified>/.exec(item)?.[1] || ''
files.push({ name, size, modified, url: `/uploads/${encodeKey(name)}` })
}
files.sort((a, b) => b.modified.localeCompare(a.modified))
return files
}
+45
View File
@@ -0,0 +1,45 @@
import { getDb } from './db'
import { defaultSettings, type SiteSettings } from '../../app/config/site'
/**
* 站点业务动态配置。
* DB settings 表优先,未配置项回退到默认值(app/config/site.ts)。
* 后台 /admin/settings 可实时修改,前台经 /api/settings 读取。
*/
// 深拷贝默认值,避免修改默认对象
function cloneDefaults(): SiteSettings {
return JSON.parse(JSON.stringify(defaultSettings)) as SiteSettings
}
/** 按点分路径设置合并后的值(如 site.name -> merged.site.name) */
function setPath(target: Record<string, unknown>, path: string, value: unknown): void {
const parts = path.split('.')
let cur: Record<string, unknown> = target
for (let i = 0; i < parts.length - 1; i += 1) {
cur = cur[parts[i]] as Record<string, unknown>
if (!cur) return
}
cur[parts[parts.length - 1]] = value
}
export function getSettings(): SiteSettings {
const merged = cloneDefaults()
const rows = getDb().prepare('SELECT key, value FROM settings').all() as Array<{ key: string; value: string }>
for (const row of rows) {
try {
setPath(merged as unknown as Record<string, unknown>, row.key, JSON.parse(row.value))
} catch {
// 单个配置损坏不影响其余
}
}
return merged
}
export function updateSetting(key: string, value: unknown): void {
getDb()
.prepare(
'INSERT INTO settings (key, value) VALUES (?, ?) ON CONFLICT(key) DO UPDATE SET value = excluded.value',
)
.run(key, JSON.stringify(value))
}
+60
View File
@@ -0,0 +1,60 @@
import { createHmac, createHash } from 'node:crypto'
/**
* AWS SigV4 签名(S3 v4 兼容,纯函数、无 Nuxt 依赖,便于单元测试)。
* 参考 AWS 文档 CanonicalRequest 算法。
*/
export const sha256Hex = (data: string | Buffer) => createHash('sha256').update(data).digest('hex')
const hmac = (key: Buffer | string, data: string) => createHmac('sha256', key).update(data).digest()
export interface SignRequestInput {
method: string
path: string
query: Record<string, string>
/** 参与签名的头(key 小写),如 host / x-amz-date / x-amz-content-sha256 */
headers: Record<string, string>
bodyHash: string
date: string // ISO 8601,如 2013-05-24T00:00:00.000Z
accessKey: string
secretKey: string
region: string
service?: string
}
export function signRequest(opts: SignRequestInput): { authorization: string; amzDate: string } {
const service = opts.service ?? 's3'
const amzDate = opts.date.replace(/[:-]|\.\d{3}/g, '')
const datestamp = opts.date.slice(0, 10).replace(/-/g, '')
const headerNames = Object.keys(opts.headers).map((h) => h.toLowerCase()).sort()
const canonicalHeaders = headerNames.map((h) => `${h}:${String(opts.headers[h]).trim()}\n`).join('')
const signedHeaders = headerNames.join(';')
const canonicalQuery = Object.keys(opts.query)
.sort()
.map((k) => `${encodeURIComponent(k)}=${encodeURIComponent(String(opts.query[k]))}`)
.join('&')
const canonicalRequest = [
opts.method,
opts.path,
canonicalQuery,
canonicalHeaders,
signedHeaders,
opts.bodyHash,
].join('\n')
const scope = `${datestamp}/${opts.region}/${service}/aws4_request`
const stringToSign = `AWS4-HMAC-SHA256\n${amzDate}\n${scope}\n${sha256Hex(canonicalRequest)}`
const kDate = hmac(`AWS4${opts.secretKey}`, datestamp)
const kRegion = hmac(kDate, opts.region)
const kService = hmac(kRegion, service)
const kSigning = hmac(kService, 'aws4_request')
const signature = createHmac('sha256', kSigning).update(stringToSign).digest('hex')
return {
authorization: `AWS4-HMAC-SHA256 Credential=${opts.accessKey}/${scope}, SignedHeaders=${signedHeaders}, Signature=${signature}`,
amzDate,
}
}
+44
View File
@@ -0,0 +1,44 @@
import { describe, it, expect } from 'vitest'
import { signRequest, sha256Hex } from '../server/utils/sigv4'
describe('SigV4 signing', () => {
it('matches the AWS S3 test vector', () => {
const bodyHash = sha256Hex('')
const { authorization } = signRequest({
method: 'GET',
path: '/test.txt',
query: {},
headers: {
host: 'examplebucket.s3.amazonaws.com',
range: 'bytes=0-9',
'x-amz-date': '20130524T000000Z',
'x-amz-content-sha256': bodyHash,
},
bodyHash,
date: '2013-05-24T00:00:00.000Z',
accessKey: 'AKIAIOSFODNN7EXAMPLE',
secretKey: 'wJalrXUtnFEMI/K7MDENG/bPxRfiCYEXAMPLEKEY',
region: 'us-east-1',
})
expect(authorization).toBe(
'AWS4-HMAC-SHA256 Credential=AKIAIOSFODNN7EXAMPLE/20130524/us-east-1/s3/aws4_request, ' +
'SignedHeaders=host;range;x-amz-content-sha256;x-amz-date, ' +
'Signature=f0e8bdb87c964420e857bd35b5d6ed310bd44f0170aba48dd91039c6036bdb41',
)
})
it('produces a deterministic signature for identical inputs', () => {
const bodyHash = sha256Hex('hello')
const a = signRequest({
method: 'PUT', path: '/bucket/obj', query: {}, headers: { host: 'x.com' },
bodyHash, date: '2026-01-01T00:00:00.000Z',
accessKey: 'AK', secretKey: 'SK', region: 'us-east-1',
})
const b = signRequest({
method: 'PUT', path: '/bucket/obj', query: {}, headers: { host: 'x.com' },
bodyHash, date: '2026-01-01T00:00:00.000Z',
accessKey: 'AK', secretKey: 'SK', region: 'us-east-1',
})
expect(a.authorization).toBe(b.authorization)
})
})
+30
View File
@@ -0,0 +1,30 @@
import { describe, it, expect } from 'vitest'
import { defaultSettings } from '../app/config/site'
describe('default site settings', () => {
it('has required structure', () => {
expect(defaultSettings.site.name).toBeTruthy()
expect(defaultSettings.site.brand).toBeTruthy()
expect(defaultSettings.site.description.zh).toBeTruthy()
expect(defaultSettings.site.description.en).toBeTruthy()
expect(defaultSettings.contact.email).toContain('@')
expect(defaultSettings.contact.infoEmail).toContain('@')
expect(defaultSettings.contact.wechat).toBeTruthy()
expect(defaultSettings.contact.address.zh).toBeTruthy()
expect(defaultSettings.contact.address.en).toBeTruthy()
})
it('has non-empty socials and tools', () => {
expect(defaultSettings.socials.length).toBeGreaterThan(0)
expect(defaultSettings.socials.every((s) => s.name && s.icon && s.url)).toBe(true)
expect(defaultSettings.tools.length).toBeGreaterThan(0)
expect(defaultSettings.tools.every((t) => t.id && t.url && t.descZh && t.descEn)).toBe(true)
})
it('has bilingual footer texts', () => {
for (const k of ['title', 'newsletterTitle', 'newsletterNote', 'copyright'] as const) {
expect(defaultSettings.footer[k].zh).toBeTruthy()
expect(defaultSettings.footer[k].en).toBeTruthy()
}
})
})