feat: 后台管理系统(Admin Backend + 全量 CMS)

- 内容迁入数据库:articles/works 表(中英双语 + 内容块),
  server/utils/seed.ts 灌入现有 6 动态 + 6 作品,站点初始内容不变
- 前台内容 API:/api/news、/api/work(列表/详情,仅已发布),
  页面/首页组件改为 useFetch 拉取并按 locale 选 zh/en 字段
- 后台管理 /admin(admin 中间件守卫):
  - Dashboard 统计、动态/作品增删改(块编辑器、图片上传 /api/admin/upload)
  - 用户管理(角色切换/删除)、评论审核、联系/订阅管理(导出 CSV)
- 预置管理员:NUXT_ADMIN_INITIAL_PASSWORD 首次初始化创建 admin 账号
- 图片自托管:上传存 PVC /data/uploads,/uploads/[...] 路由服务
- sitemap 改查 DB;i18n 移除内容键(305 键对齐);删除 app/data 冗余模块
- 角色以数据库为准(后台可切换);admin 中间件 + 客户端会话恢复插件
This commit is contained in:
2026-08-06 16:15:14 +08:00
parent 5c3f3bca63
commit d67849a311
67 changed files with 4909 additions and 754 deletions
+3
View File
@@ -27,3 +27,6 @@ NUXT_CONTACT_TO=chenchun@virtheart.com
# 管理员邮箱(逗号分隔),命中邮箱的用户在个人中心显示管理面板
NUXT_ADMIN_EMAILS=chenchun@virtheart.com
# 预置管理员初始密码(仅首次初始化数据库时创建 admin 账号用;生产由 deploy.sh 注入)
# NUXT_ADMIN_INITIAL_PASSWORD=change-me
+13 -9
View File
@@ -52,13 +52,17 @@ pnpm dev
| 模块 | 说明 |
| --- | --- |
| 页面 | 首页、工作室、作品(列表/详情)、动态(列表/详情)、工具箱、联系、个人中心 |
| 用户系统 | 真实注册/登录/登出(scrypt 密码哈希 + httpOnly Cookie 会话) |
| 个人中心 | `/account`:资料编辑、作品收藏、我的评论;管理员可见联系/订阅收件箱 |
| **后台管理** | `/admin`:Dashboard 统计、动态/作品增删改(中英双语 CMS)、用户管理、评论审核、联系/订阅管理、图片上传 |
| 用户系统 | 真实注册/登录/登出(scrypt 密码哈希 + httpOnly Cookie 会话);预置 admin 账号 |
| 个人中心 | `/account`:资料编辑、作品收藏、我的评论;管理员可进入 `/admin` |
| 交互 | 作品收藏、新闻评论、分享(X/LinkedIn/复制链接)、搜索、加载更多 |
| 国际化 | 中/英双语,Header 一键切换(`no_prefix`,默认中文) |
| SEO | 动态 `sitemap.xml` / `robots.txt`、JSON-LD、自动生成的 `og-image.png` |
| 国际化 | 中/英双语,Header 一键切换(`no_prefix`,默认中文);内容双语存于数据库 |
| SEO | 动态 `sitemap.xml`(数据来自 DB)/ `robots.txt`、JSON-LD、自动生成的 `og-image.png` |
| 邮件 | SMTP 发送联系/订阅邮件;未配置 SMTP 时数据仍真实写入 SQLite |
> **预置管理员**:首次部署时若设置 `ADMIN_INITIAL_PASSWORD`(或由 `deploy.sh` 自动生成并打印),
> 数据库初始化会自动创建 `admin` 账号(邮箱取 `ADMIN_EMAILS` 第一个)。登录后访问 `/admin` 即可管理内容。
### 环境变量(详见 `.env.example`,Nuxt runtimeConfig 使用 `NUXT_` 前缀)
| 变量 | 说明 |
@@ -69,8 +73,9 @@ pnpm dev
| `NUXT_SMTP_HOST/PORT/USER/PASS/FROM` | SMTP 邮件服务(可选) |
| `NUXT_CONTACT_TO` | 联系表单留言收件邮箱 |
| `NUXT_ADMIN_EMAILS` | 管理员邮箱(逗号分隔),命中者个人中心可见管理面板 |
| `NUXT_ADMIN_INITIAL_PASSWORD` | 预置管理员初始密码(仅首次初始化创建 admin 账号用) |
> `deploy.sh` 中的对外变量名(`SESSION_SECRET`/`SMTP_*`/`CONTACT_TO`/`ADMIN_EMAILS`)会在写入 K8s Secret 时自动加 `NUXT_` 前缀。
> `deploy.sh` 中的对外变量名(`SESSION_SECRET`/`SMTP_*`/`CONTACT_TO`/`ADMIN_EMAILS`/`ADMIN_INITIAL_PASSWORD`)会在写入 K8s Secret 时自动加 `NUXT_` 前缀。
## 项目结构
@@ -79,12 +84,11 @@ pnpm dev
├── app/ # 应用源码(Nuxt 4 约定目录)
│ ├── app.vue # 应用入口(全局 SEO / Meta / JSON-LD)
│ ├── config/ # 站点配置(品牌、邮箱、社交链接)
│ ├── data/ # 内容单一事实源(news / work,列表/详情/首页共用)
│ ├── pages/ # 页面(含 account.vue 个人中心)
│ ├── components/ # 组件(common / home / layouts)
│ ├── pages/ # 页面(含 account.vue 个人中心、admin/ 后台管理)
│ ├── components/ # 组件(common / home / layouts / admin)
│ ├── stores/ # Pinia 状态(用户、认证弹窗)
│ └── ...
├── server/ # Nitro 后端(utils 数据/鉴权/邮件 + api 路由 + sitemap/robots)
├── server/ # Nitro 后端(utils 数据/鉴权/邮件 + api 内容/后台 + sitemap/robots + uploads)
├── i18n/locales/ # 国际化文案(zh.json / en.json)
├── scripts/ # 工具脚本(generate-og.mjs 生成分享图)
├── public/ # 公开静态文件
+130
View File
@@ -0,0 +1,130 @@
<script setup lang="ts">
/**
* 后台正文内容块编辑器(动态/作品共用)。
* v-model 绑定块数组 `{ type, text }[]`,支持添加/删除/上移/下移。
* 图片块以 URL 文本承载。
*/
import { computed } from 'vue'
interface Block {
type: string
text: string
}
const props = withDefaults(defineProps<{ modelValue?: Block[]; label?: string; placeholder?: string }>(), {
modelValue: () => [],
label: '正文内容',
placeholder: '输入内容…',
})
const emit = defineEmits<{ 'update:modelValue': [value: Block[]] }>()
const blocks = computed({
get: () => props.modelValue,
set: (v) => emit('update:modelValue', v),
})
const BLOCK_TYPES = [
{ value: 'paragraph', label: '段落' },
{ value: 'heading', label: '标题' },
{ value: 'quote', label: '引用' },
{ value: 'image', label: '图片' },
]
const addBlock = () => {
blocks.value = [...blocks.value, { type: 'paragraph', text: '' }]
}
const removeBlock = (i: number) => {
blocks.value = blocks.value.filter((_, idx) => idx !== i)
}
const moveUp = (i: number) => {
if (i === 0) return
const arr = [...blocks.value]
const tmp = arr[i - 1]
arr[i - 1] = arr[i]
arr[i] = tmp
blocks.value = arr
}
const moveDown = (i: number) => {
if (i >= blocks.value.length - 1) return
const arr = [...blocks.value]
const tmp = arr[i + 1]
arr[i + 1] = arr[i]
arr[i] = tmp
blocks.value = arr
}
</script>
<template>
<div>
<div class="flex items-center justify-between mb-2">
<label class="text-sm font-semibold text-gray-800">{{ label }}</label>
<button
type="button"
@click="addBlock"
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"
>
<Icon name="ph:plus" class="w-3.5 h-3.5" /> 添加块
</button>
</div>
<div class="space-y-3">
<div
v-if="!blocks.length"
class="text-sm text-gray-400 py-6 text-center border border-dashed border-gray-200 rounded-xl"
>
暂无内容块,点击「添加块」开始
</div>
<div
v-for="(block, i) in blocks"
:key="i"
class="border border-gray-200 rounded-xl bg-white p-3"
>
<div class="flex items-center gap-2 mb-2">
<select
v-model="block.type"
class="px-2 py-1.5 rounded-lg border border-gray-200 text-xs outline-none focus:border-black bg-white"
>
<option v-for="t in BLOCK_TYPES" :key="t.value" :value="t.value">{{ t.label }}</option>
</select>
<span class="text-xs text-gray-400">
{{ block.type === 'image' ? '图片 URL' : '文本内容' }}
</span>
<div class="ml-auto flex items-center gap-1">
<button
type="button"
:disabled="i === 0"
@click="moveUp(i)"
class="w-7 h-7 rounded-lg hover:bg-gray-100 text-gray-500 disabled:opacity-30 flex items-center justify-center transition-colors"
aria-label="上移"
>
<Icon name="ph:arrow-up" class="w-3.5 h-3.5" />
</button>
<button
type="button"
:disabled="i >= blocks.length - 1"
@click="moveDown(i)"
class="w-7 h-7 rounded-lg hover:bg-gray-100 text-gray-500 disabled:opacity-30 flex items-center justify-center transition-colors"
aria-label="下移"
>
<Icon name="ph:arrow-down" class="w-3.5 h-3.5" />
</button>
<button
type="button"
@click="removeBlock(i)"
class="w-7 h-7 rounded-lg hover:bg-red-50 text-gray-400 hover:text-red-600 flex items-center justify-center transition-colors"
aria-label="删除"
>
<Icon name="ph:trash" class="w-3.5 h-3.5" />
</button>
</div>
</div>
<textarea
v-model="block.text"
:rows="block.type === 'image' ? 2 : 4"
:placeholder="block.type === 'image' ? '图片 URL(如 /uploads/xxx 或 https://…)' : placeholder"
class="w-full px-3 py-2 rounded-lg border border-gray-200 bg-gray-50 text-sm outline-none transition-all focus:border-black focus:bg-white resize-y"
></textarea>
</div>
</div>
</div>
</template>
@@ -0,0 +1,88 @@
<script setup lang="ts">
/**
* 后台通用确认弹窗(删除等危险操作)。
* 通过 Teleport 渲染到 body,支持危险色与加载态。
*/
withDefaults(
defineProps<{
open: boolean
title?: string
message?: string
confirmText?: string
danger?: boolean
loading?: boolean
}>(),
{
title: '确认操作',
message: '确定要执行该操作吗?',
confirmText: '确认',
danger: true,
loading: false,
},
)
const emit = defineEmits<{ confirm: []; cancel: [] }>()
</script>
<template>
<Teleport to="body">
<Transition name="confirm-fade">
<div v-if="open" class="fixed inset-0 z-[100] flex items-center justify-center p-4">
<div class="absolute inset-0 bg-black/40 backdrop-blur-sm" @click="emit('cancel')"></div>
<div class="relative w-full max-w-sm bg-white rounded-2xl shadow-2xl p-6">
<div class="flex items-start gap-4">
<div
class="w-10 h-10 rounded-full flex items-center justify-center flex-shrink-0"
:class="danger ? 'bg-red-50 text-red-600' : 'bg-gray-100 text-gray-600'"
>
<Icon name="ph:warning-circle" class="w-5 h-5" />
</div>
<div class="min-w-0">
<h3 class="text-lg font-bold text-black">{{ title }}</h3>
<p class="mt-1 text-sm text-gray-600 break-words">{{ message }}</p>
</div>
</div>
<div class="mt-6 flex justify-end gap-3">
<button
type="button"
@click="emit('cancel')"
class="px-4 py-2 rounded-lg border border-gray-200 text-sm font-semibold text-gray-700 hover:bg-gray-50 transition-colors"
>
取消
</button>
<button
type="button"
:disabled="loading"
@click="emit('confirm')"
class="px-4 py-2 rounded-lg text-sm font-semibold text-white flex items-center gap-2 transition-colors disabled:opacity-50"
:class="danger ? 'bg-red-600 hover:bg-red-700' : 'bg-black hover:bg-gray-800'"
>
<Icon v-if="loading" name="ph:circle-notch" class="w-4 h-4 animate-spin" />
{{ confirmText }}
</button>
</div>
</div>
</div>
</Transition>
</Teleport>
</template>
<style scoped>
.confirm-fade-enter-active,
.confirm-fade-leave-active {
transition: opacity 0.2s ease;
}
.confirm-fade-enter-active .relative,
.confirm-fade-leave-active .relative {
transition: transform 0.2s ease, opacity 0.2s ease;
}
.confirm-fade-enter-from,
.confirm-fade-leave-to {
opacity: 0;
}
.confirm-fade-enter-from .relative,
.confirm-fade-leave-to .relative {
transform: translateY(8px) scale(0.98);
opacity: 0;
}
</style>
+86
View File
@@ -0,0 +1,86 @@
<script setup lang="ts">
/**
* 后台图片字段:URL 输入 + 本地图片上传(调 /api/admin/upload)+ 预览。
* v-model 绑定 URL 字符串。
*/
import { ref } from 'vue'
withDefaults(defineProps<{ modelValue?: string | null; label?: string }>(), {
modelValue: '',
label: '图片',
})
const emit = defineEmits<{ 'update:modelValue': [value: string] }>()
const fileInput = ref<HTMLInputElement | null>(null)
const uploading = ref(false)
const error = ref('')
const choose = () => fileInput.value?.click()
const onFileChange = async (e: Event) => {
const input = e.target as HTMLInputElement
const file = input.files?.[0]
input.value = ''
if (!file) return
uploading.value = true
error.value = ''
try {
const fd = new FormData()
fd.append('file', file)
const res = await $fetch<{ ok: boolean; url: string }>('/api/admin/upload', {
method: 'POST',
body: fd,
})
emit('update:modelValue', res.url)
} catch (err: any) {
error.value = err?.data?.message || '上传失败'
} finally {
uploading.value = false
}
}
</script>
<template>
<div>
<div class="flex items-center justify-between mb-2">
<label class="text-sm font-semibold text-gray-800">{{ label }}</label>
<button
v-if="modelValue"
type="button"
@click="emit('update:modelValue', '')"
class="text-xs text-gray-400 hover:text-red-600 flex items-center gap-1 transition-colors"
>
<Icon name="ph:x-circle" class="w-3.5 h-3.5" /> 清除
</button>
</div>
<div class="flex items-center gap-3">
<input
:value="modelValue"
type="text"
placeholder="图片 URL(本地 /uploads/... 或 https://...)"
@input="emit('update:modelValue', ($event.target as HTMLInputElement).value)"
class="flex-1 min-w-0 px-3 py-2 rounded-lg border border-gray-200 bg-white text-sm outline-none transition-all focus:border-black focus:ring-2 focus:ring-black/5"
/>
<button
type="button"
:disabled="uploading"
@click="choose"
class="flex items-center gap-1.5 px-3 py-2 rounded-lg bg-black text-white text-sm font-semibold hover:bg-gray-800 transition-colors disabled:opacity-60 flex-shrink-0"
>
<Icon v-if="uploading" name="ph:circle-notch" class="w-4 h-4 animate-spin" />
<Icon v-else name="ph:upload-simple" class="w-4 h-4" />
{{ uploading ? '上传中…' : '上传图片' }}
</button>
<input ref="fileInput" type="file" accept="image/*" class="hidden" @change="onFileChange" />
</div>
<div v-if="modelValue" class="mt-3">
<img
:src="modelValue"
alt="图片预览"
class="h-32 w-auto max-w-full rounded-lg border border-gray-100 object-cover"
/>
</div>
<p v-if="error" class="mt-1 text-xs text-red-600">{{ error }}</p>
</div>
</template>
+68
View File
@@ -0,0 +1,68 @@
<script setup lang="ts">
/**
* 后台左侧导航栏(Dashboard / 动态 / 作品 / 用户 / 评论 / 联系 / 订阅 / 返回前台)。
* 高亮当前路由;点击任意导航项时向父级发出 navigate 事件(移动端关闭侧栏)。
*/
import { useRoute } from '#app'
import { siteConfig } from '~/config/site'
const route = useRoute()
const emit = defineEmits<{ navigate: [] }>()
const items = [
{ to: '/admin', label: 'Dashboard', icon: 'ph:gauge' },
{ to: '/admin/news', label: '动态管理', icon: 'ph:newspaper' },
{ to: '/admin/work', label: '作品管理', icon: 'ph:image-square' },
{ 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' },
]
const isActive = (to: string) => route.path === to
</script>
<template>
<div class="flex flex-col h-full bg-black text-white">
<NuxtLink
to="/admin"
class="flex items-center gap-3 px-5 h-16 border-b border-white/10 shrink-0"
@click="emit('navigate')"
>
<div
class="w-8 h-8 rounded-full bg-white text-black flex items-center justify-center font-bold text-sm"
>
A
</div>
<div class="leading-tight">
<p class="text-sm font-bold">{{ siteConfig.brandZh }}</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">
<NuxtLink
v-for="item in 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"
:class="isActive(item.to) ? 'bg-white text-black' : 'text-white/70 hover:bg-white/10 hover:text-white'"
@click="emit('navigate')"
>
<Icon :name="item.icon" class="w-[18px] h-[18px]" />
{{ item.label }}
</NuxtLink>
</nav>
<div class="p-3 border-t border-white/10 shrink-0">
<NuxtLink
to="/"
class="flex items-center gap-3 px-3 py-2.5 rounded-lg text-sm font-medium text-white/70 hover:bg-white/10 hover:text-white transition-colors"
@click="emit('navigate')"
>
<Icon name="ph:arrow-left" class="w-[18px] h-[18px]" />
返回前台
</NuxtLink>
</div>
</div>
</template>
+21 -8
View File
@@ -1,13 +1,26 @@
<script setup lang="ts">
import { onMounted, onUnmounted, ref, nextTick } from 'vue'
import { onMounted, onUnmounted, ref, nextTick, computed } from 'vue'
import { useI18n } from 'vue-i18n'
import gsap from 'gsap'
import { ScrollTrigger } from 'gsap/ScrollTrigger'
import { workItems } from '~/data/work'
gsap.registerPlugin(ScrollTrigger)
const { t } = useI18n()
const { t, locale } = useI18n()
interface WorkItem {
slug: string
titleZh: string
titleEn: string
year: string
image: string | null
}
// 内容 API(仅已发布)
const { data } = await useFetch<{ works: WorkItem[] }>('/api/work')
const works = computed(() => data.value?.works ?? [])
const locText = (zh: string, en: string) => (locale.value === 'zh' ? zh : en)
const rootRef = ref<HTMLElement | null>(null)
const workSectionRef = ref<HTMLElement | null>(null)
@@ -180,7 +193,7 @@ onUnmounted(() => {
<h2 class="text-5xl md:text-6xl font-bold tracking-tighter leading-[0.92]">
{{ t('home.work.title') }}
<span class="text-black/40 text-base md:text-lg align-middle ml-2 font-semibold tracking-tight">
({{ workItems.length }})
({{ works.length }})
</span>
</h2>
</div>
@@ -197,7 +210,7 @@ onUnmounted(() => {
<div class="relative w-full h-[78svh] md:h-[82svh] lg:h-[88svh] p-[clamp(14px,2.4vw,28px)]">
<div class="relative h-full w-full">
<NuxtLink
v-for="(item, idx) in workItems"
v-for="item in works"
:key="item.slug"
:to="`/work/${item.slug}`"
ref="cardRefs"
@@ -205,15 +218,15 @@ onUnmounted(() => {
>
<img
class="h-full w-full object-cover"
:src="item.image"
:alt="t(`work.items.${item.slug}.title`)"
:src="item.image || ''"
:alt="locText(item.titleZh, item.titleEn)"
loading="lazy"
decoding="async"
@load="refresh"
/>
<div class="absolute left-6 top-6 flex items-baseline gap-3">
<p class="text-white text-sm md:text-base font-semibold tracking-tight drop-shadow-[0_10px_18px_rgba(0,0,0,0.4)]">
{{ t(`work.items.${item.slug}.title`) }}
{{ locText(item.titleZh, item.titleEn) }}
</p>
<p class="text-white/80 text-xs md:text-sm font-semibold tracking-tight drop-shadow-[0_10px_18px_rgba(0,0,0,0.4)]">
{{ item.year }} ©
+48 -10
View File
@@ -36,11 +36,11 @@
</div>
<h3 class="text-xl md:text-3xl font-bold mb-3 line-clamp-2">
{{ t(`news.items.${item.slug}.title`) }}
{{ locText(item.titleZh, item.titleEn) }}
</h3>
<p v-if="item.showDescription" class="text-white/90 text-sm md:text-base line-clamp-3">
{{ t(`news.items.${item.slug}.excerpt`) }}
{{ locText(item.excerptZh, item.excerptEn) }}
</p>
</div>
@@ -70,16 +70,25 @@
</template>
<script setup lang="ts">
import { ref, onMounted, onUnmounted, nextTick } from 'vue'
import { ref, onMounted, onUnmounted, nextTick, watch, computed } from 'vue'
import { useI18n } from 'vue-i18n'
import gsap from 'gsap'
import { ScrollTrigger } from 'gsap/ScrollTrigger'
import { newsItems, formatNewsDate } from '~/data/news'
gsap.registerPlugin(ScrollTrigger)
const { t, locale } = useI18n()
interface ArticleItem {
slug: string
category: 'insights' | 'projects' | 'announcements'
titleZh: string
titleEn: string
excerptZh: string
excerptEn: string
date: string | null
}
const rootRef = ref<HTMLElement | null>(null)
const headerRef = ref<HTMLElement | null>(null)
const cardElements = ref<(HTMLElement | null)[]>([])
@@ -89,6 +98,23 @@ const setCardRef = (el: any, index: number) => {
if (el) cardElements.value[index] = el
}
// 内容 API(仅已发布,date 降序)
const { data } = await useFetch<{ articles: ArticleItem[] }>('/api/news')
const articles = computed(() => data.value?.articles ?? [])
const locText = (zh: string, en: string) => (locale.value === 'zh' ? zh : en)
function formatNewsDate(date: string | null, loc: string): string {
if (!date) return ''
const d = new Date(`${date}T00:00:00`)
if (Number.isNaN(d.getTime())) return date
return new Intl.DateTimeFormat(loc === 'zh' ? 'zh-CN' : 'en-US', {
year: 'numeric',
month: 'long',
day: 'numeric',
}).format(d)
}
// Bento 布局(与动态数据一一对应;分类图标/渐变/跨度)
const layout = [
{ categoryIcon: 'ph:article', gradient: 'bg-gradient-to-br from-blue-500 via-purple-500 to-pink-500', gridClass: 'col-span-12 md:col-span-6 md:row-span-2', showDescription: true },
@@ -100,10 +126,12 @@ const layout = [
] as const
// 取前 6 条动态,绑定布局
const updates = newsItems.slice(0, 6).map((item, i) => ({
...item,
...layout[i],
}))
const updates = computed(() =>
articles.value.slice(0, 6).map((item, i) => ({
...item,
...layout[i],
})),
)
// 卡片悬浮效果
const handleCardHover = (index: number, isHover: boolean) => {
@@ -120,9 +148,10 @@ const handleCardHover = (index: number, isHover: boolean) => {
})
}
onMounted(async () => {
const playIntro = async () => {
if (!rootRef.value || !headerRef.value || cardElements.value.length === 0) return
await nextTick()
if (!rootRef.value || !headerRef.value) return
if (ctx) ctx.revert()
ctx = gsap.context(() => {
// 初始状态
@@ -152,8 +181,17 @@ onMounted(async () => {
animation: tl,
})
}, rootRef.value)
}
onMounted(() => {
playIntro()
})
// 若数据异步到达(纯客户端首帧),卡片渲染后补跑入场动画
watch(updates, () => {
if (!ctx) playIntro()
}, { flush: 'post' })
onUnmounted(() => {
ctx?.revert()
})
-98
View File
@@ -1,98 +0,0 @@
/**
* 动态(news)单一事实源。
*
* 列表页、详情页、首页 HomeUpdates 一律引用本模块,杜绝三处重复。
* 标题/摘要/正文属于本地化文案,按 slug 存放在 i18n(news.items.<slug>.*),
* 本模块只保存与语言无关的结构化元数据。
*/
export interface NewsItem {
slug: string
category: 'insights' | 'projects' | 'announcements'
/** 分类徽章 tailwind 类(静态字符串,Tailwind 扫描 ./app/** 可命中) */
badge: string
date: string
readTime: string
author: string
image: string
}
export const newsItems: NewsItem[] = [
{
slug: 'design-trends-2026',
category: 'insights',
badge: 'bg-purple-100 text-purple-700',
date: '2026-05-28',
readTime: '5',
author: 'ArcticNewOne',
image: 'https://picsum.photos/id/1/800/500',
},
{
slug: 'forma-digital-launch',
category: 'projects',
badge: 'bg-blue-100 text-blue-700',
date: '2026-05-15',
readTime: '3',
author: 'ArcticNewOne',
image: 'https://picsum.photos/id/201/800/500',
},
{
slug: 'studio-expansion',
category: 'announcements',
badge: 'bg-green-100 text-green-700',
date: '2026-05-10',
readTime: '2',
author: 'ArcticNewOne',
image: 'https://picsum.photos/id/164/800/500',
},
{
slug: 'ux-research-methods',
category: 'insights',
badge: 'bg-purple-100 text-purple-700',
date: '2026-04-28',
readTime: '7',
author: 'ArcticNewOne',
image: 'https://picsum.photos/id/180/800/500',
},
{
slug: 'bold-moves-case-study',
category: 'projects',
badge: 'bg-blue-100 text-blue-700',
date: '2026-04-20',
readTime: '6',
author: 'ArcticNewOne',
image: 'https://picsum.photos/id/119/800/500',
},
{
slug: 'new-tools-integration',
category: 'announcements',
badge: 'bg-green-100 text-green-700',
date: '2026-04-12',
readTime: '4',
author: 'ArcticNewOne',
image: 'https://picsum.photos/id/326/800/500',
},
]
export const newsBySlug: Record<string, NewsItem> = Object.fromEntries(
newsItems.map((item) => [item.slug, item]),
)
export function getNewsCategories(): Array<NewsItem['category']> {
return ['insights', 'projects', 'announcements']
}
/** 显示用的日期(本地化格式化在组件内完成) */
export function formatNewsDate(date: string, locale: string): string {
const d = new Date(`${date}T00:00:00`)
if (Number.isNaN(d.getTime())) return date
return new Intl.DateTimeFormat(locale === 'zh' ? 'zh-CN' : 'en-US', {
year: 'numeric',
month: 'long',
day: 'numeric',
}).format(d)
}
/** 显示用的阅读时长(本地化文案在 i18n,数字在此) */
export function newsReadTime(item: NewsItem): string {
return item.readTime
}
-108
View File
@@ -1,108 +0,0 @@
/**
* 作品(work)单一事实源。
*
* 列表页、详情页、首页 HomePartnersWork 一律引用本模块,杜绝三处重复。
* 标题/概述属于本地化文案,按 slug 存放在 i18n(work.items.<slug>.*)。
*
* 说明:`url` 只在存在真实线上地址时填写;没有真实地址的作品
* 详情页不渲染「访问项目」按钮,避免 `#` 死链。
*/
export interface WorkItem {
slug: string
category: 'webDesign' | 'branding' | 'development'
year: string
tags: string[]
image: string
gallery: string[]
/** 真实线上地址;不存在时省略,详情页隐藏「访问项目」按钮 */
url?: string
}
export const workItems: WorkItem[] = [
{
slug: 'forma-digital',
category: 'webDesign',
year: '2026',
tags: ['Web Design', 'E-commerce', 'React'],
image: 'https://picsum.photos/id/201/1200/800',
gallery: [
'https://picsum.photos/id/201/800/600',
'https://picsum.photos/id/202/800/600',
'https://picsum.photos/id/203/800/600',
'https://picsum.photos/id/204/800/600',
],
},
{
slug: 'one-step',
category: 'branding',
year: '2024',
tags: ['Branding', 'Marketing', 'UI/UX'],
image: 'https://picsum.photos/id/180/1200/800',
gallery: [
'https://picsum.photos/id/180/800/600',
'https://picsum.photos/id/181/800/600',
'https://picsum.photos/id/182/800/600',
'https://picsum.photos/id/183/800/600',
],
},
{
slug: 'nero-vision',
category: 'development',
year: '2025',
tags: ['Development', 'Vue.js', 'Node.js'],
image: 'https://picsum.photos/id/119/1200/800',
gallery: [
'https://picsum.photos/id/119/800/600',
'https://picsum.photos/id/120/800/600',
'https://picsum.photos/id/121/800/600',
'https://picsum.photos/id/122/800/600',
],
},
{
slug: 'bold-moves',
category: 'webDesign',
year: '2024',
tags: ['Web Design', '3D', 'Three.js'],
image: 'https://picsum.photos/id/164/1200/800',
gallery: [
'https://picsum.photos/id/164/800/600',
'https://picsum.photos/id/165/800/600',
'https://picsum.photos/id/166/800/600',
'https://picsum.photos/id/167/800/600',
],
},
{
slug: 'echo-labs',
category: 'branding',
year: '2025',
tags: ['Branding', 'Visual Identity', 'Corporate'],
image: 'https://picsum.photos/id/101/1200/800',
gallery: [
'https://picsum.photos/id/101/800/600',
'https://picsum.photos/id/102/800/600',
'https://picsum.photos/id/103/800/600',
'https://picsum.photos/id/104/800/600',
],
},
{
slug: 'flux-api',
category: 'development',
year: '2025',
tags: ['Development', 'API', 'Python'],
image: 'https://picsum.photos/id/326/1200/800',
gallery: [
'https://picsum.photos/id/326/800/600',
'https://picsum.photos/id/327/800/600',
'https://picsum.photos/id/328/800/600',
'https://picsum.photos/id/329/800/600',
],
},
]
export const workBySlug: Record<string, WorkItem> = Object.fromEntries(
workItems.map((item) => [item.slug, item]),
)
export function getWorkCategories(): Array<WorkItem['category']> {
return ['webDesign', 'branding', 'development']
}
+71
View File
@@ -0,0 +1,71 @@
<script setup lang="ts">
/**
* 后台管理布局:左侧固定深色侧边栏 + 右侧内容区。
* 不包含站点公共 Header/Footer;移动端侧栏收起为顶栏按钮。
* 由各后台页面通过 definePageMeta({ layout: 'admin' }) 启用。
*/
import { ref } from 'vue'
const sidebarOpen = ref(false)
</script>
<template>
<div class="min-h-screen bg-gray-50">
<!-- 移动端顶栏 -->
<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"
>
<NuxtLink to="/admin" class="flex items-center gap-2" @click="sidebarOpen = false">
<div
class="w-7 h-7 rounded-full bg-white text-black flex items-center justify-center font-bold text-xs"
>
A
</div>
<span class="font-bold text-sm">北极新一 · 后台</span>
</NuxtLink>
<button
type="button"
class="w-9 h-9 rounded-lg hover:bg-white/10 flex items-center justify-center transition-colors"
aria-label="切换菜单"
@click="sidebarOpen = !sidebarOpen"
>
<Icon :name="sidebarOpen ? 'ph:x' : 'ph:list'" class="w-5 h-5" />
</button>
</header>
<!-- 移动端遮罩 -->
<Transition name="admin-fade">
<div
v-if="sidebarOpen"
class="lg:hidden fixed inset-0 z-40 bg-black/50"
@click="sidebarOpen = false"
></div>
</Transition>
<!-- 侧边栏 -->
<aside
class="fixed inset-y-0 left-0 z-50 w-64 shadow-2xl transition-transform duration-300 lg:translate-x-0"
:class="sidebarOpen ? 'translate-x-0' : '-translate-x-full'"
>
<AdminSidebar @navigate="sidebarOpen = false" />
</aside>
<!-- 内容区 -->
<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]">
<slot />
</div>
</main>
</div>
</template>
<style scoped>
.admin-fade-enter-active,
.admin-fade-leave-active {
transition: opacity 0.2s ease;
}
.admin-fade-enter-from,
.admin-fade-leave-to {
opacity: 0;
}
</style>
+23
View File
@@ -0,0 +1,23 @@
import { defineNuxtRouteMiddleware, navigateTo } from '#app'
import { useUserStore } from '~/stores/user'
import { useAuthModalStore } from '~/stores/authModal'
/**
* 后台路由守卫(/admin/**):仅管理员可访问。
* - SSR 不拦截(真实防护在 admin API 的 requireAdmin);
* - 客户端依据已恢复的会话判定,未登录则弹出登录框并回退,非管理员回首页。
*/
export default defineNuxtRouteMiddleware(() => {
if (import.meta.server) return
const userStore = useUserStore()
if (!userStore.isAuthenticated) {
const authModal = useAuthModalStore()
authModal.openLogin()
return navigateTo('/account')
}
if (userStore.user?.role !== 'admin') {
return navigateTo('/')
}
})
+30 -68
View File
@@ -26,6 +26,17 @@
<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
@@ -83,19 +94,19 @@
<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="slug in favorites"
:key="slug"
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/${slug}`" class="block relative aspect-[4/3] overflow-hidden">
<img :src="workBySlug[slug]?.image" :alt="t(`work.items.${slug}.title`)" class="w-full h-full object-cover transition-transform duration-500 group-hover:scale-105" />
<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/${slug}`" class="font-bold text-black group-hover:text-gray-600 transition-colors">
{{ t(`work.items.${slug}.title`) }}
<NuxtLink :to="`/work/${fav.slug}`" class="font-bold text-black group-hover:text-gray-600 transition-colors">
{{ favTitle(fav) }}
</NuxtLink>
<button
@click="removeFavorite(slug)"
@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"
>
@@ -116,48 +127,13 @@
>
<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">
{{ t(`news.items.${comment.newsSlug}.title`) }}
#{{ 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>
<!-- 管理面板 -->
<section v-if="activeTab === 'admin'" class="max-w-4xl mx-auto space-y-12">
<div>
<h3 class="text-xl font-bold text-black mb-5">{{ t('account.admin.contacts') }}</h3>
<p v-if="!adminData.contacts.length" class="text-gray-500 text-center py-8">{{ t('account.admin.emptyContacts') }}</p>
<div v-else class="space-y-4">
<div v-for="c in adminData.contacts" :key="c.id" class="p-5 rounded-2xl bg-white border border-gray-100 shadow-sm">
<div class="flex items-center justify-between mb-2">
<div class="flex items-center gap-3">
<span class="font-semibold text-black">{{ c.name }}</span>
<span class="text-sm text-gray-500">{{ c.email }}</span>
</div>
<span class="text-xs px-2 py-1 rounded-full" :class="c.delivered ? 'bg-green-50 text-green-700' : 'bg-amber-50 text-amber-700'">
{{ c.delivered ? t('account.admin.delivered') : t('account.admin.notDelivered') }}
</span>
</div>
<p class="text-sm font-semibold text-gray-700 mb-1">{{ c.subject }}</p>
<p class="text-sm text-gray-600 whitespace-pre-line break-words mb-2">{{ c.message }}</p>
<p class="text-xs text-gray-400">{{ formatDate(c.createdAt) }}</p>
</div>
</div>
</div>
<div>
<h3 class="text-xl font-bold text-black mb-5">{{ t('account.admin.subscribers') }}</h3>
<p v-if="!adminData.subscribers.length" class="text-gray-500 text-center py-8">{{ t('account.admin.emptySubscribers') }}</p>
<div v-else class="rounded-2xl overflow-hidden border border-gray-100 shadow-sm bg-white">
<div v-for="s in adminData.subscribers" :key="s.id" class="flex items-center justify-between px-5 py-3 border-b border-gray-100 last:border-b-0">
<span class="text-sm font-medium text-gray-700">{{ s.email }}</span>
<span class="text-xs text-gray-400">{{ formatDate(s.createdAt) }}</span>
</div>
</div>
</div>
</section>
</div>
</main>
</template>
@@ -169,7 +145,6 @@ import { useSeoMeta } from '#imports'
import gsap from 'gsap'
import { useUserStore } from '~/stores/user'
import { useAuthModalStore } from '~/stores/authModal'
import { workBySlug } from '~/data/work'
import { useApiError } from '~/composables/useApiError'
const { t, locale } = useI18n()
@@ -187,9 +162,6 @@ const tabs = computed(() => {
{ key: 'favorites', label: t('account.favorites') },
{ key: 'comments', label: t('account.comments') },
]
if (userStore.user?.role === 'admin') {
list.push({ key: 'admin', label: t('account.adminTitle') })
}
return list
})
@@ -198,7 +170,6 @@ const switchTab = (key: string) => {
activeTab.value = key
if (key === 'favorites') loadFavorites()
if (key === 'comments') loadComments()
if (key === 'admin') loadAdmin()
}
const formatDate = (raw?: string) => {
@@ -241,11 +212,18 @@ const saveProfile = async () => {
}
// ---- 收藏 ----
const favorites = ref<string[]>([])
interface FavedWork { slug: string; titleZh: string; titleEn: string; image: string | null }
const favorites = ref<FavedWork[]>([])
const favTitle = (w: FavedWork) => (locale.value === 'zh' ? w.titleZh : w.titleEn)
const loadFavorites = async () => {
try {
const data = await $fetch<{ slugs: string[] }>('/api/favorites')
favorites.value = data.slugs
const [favRes, workRes] = await Promise.all([
$fetch<{ slugs: string[] }>('/api/favorites'),
$fetch<{ works: FavedWork[] }>('/api/work'),
])
const bySlug = new Map(workRes.works.map((w) => [w.slug, w]))
favorites.value = favRes.slugs.map((s) => bySlug.get(s)).filter(Boolean) as FavedWork[]
} catch (err) {
console.error('load favorites error:', err)
}
@@ -253,7 +231,7 @@ const loadFavorites = async () => {
const removeFavorite = async (slug: string) => {
try {
await $fetch('/api/favorites', { method: 'DELETE', body: { workSlug: slug } })
favorites.value = favorites.value.filter((s) => s !== slug)
favorites.value = favorites.value.filter((f) => f.slug !== slug)
} catch (err) {
console.error('remove favorite error:', err)
}
@@ -270,22 +248,6 @@ const loadComments = async () => {
}
}
// ---- 管理面板 ----
const adminData = reactive<{
contacts: Array<{ id: number; name: string; email: string; subject: string; message: string; delivered: number; createdAt: string }>
subscribers: Array<{ id: number; email: string; createdAt: string }>
}>({ contacts: [], subscribers: [] })
const loadAdmin = async () => {
try {
const data = await $fetch<typeof adminData>('/api/account/admin')
adminData.contacts = data.contacts
adminData.subscribers = data.subscribers
} catch (err) {
console.error('load admin error:', err)
}
}
// ---- 页面进场动画 ----
const mainRef = ref<HTMLElement | null>(null)
let ctx: gsap.Context | null = null
+208
View File
@@ -0,0 +1,208 @@
<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">共 {{ comments.length }} 条评论</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>
</section>
</template>
<script setup lang="ts">
import { computed, onMounted, ref } from 'vue'
definePageMeta({ middleware: 'admin', layout: 'admin' })
useSeoMeta({ title: '评论管理' })
interface AdminComment {
id: number
newsSlug: string
content: string
createdAt: string
username: string
}
const comments = ref<AdminComment[]>([])
const keyword = ref('')
const loading = ref(true)
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[] }>('/api/admin/comments')
comments.value = data.comments
} catch (err) {
console.error('load comments error:', err)
loadError.value = '加载失败,请重试'
} finally {
loading.value = false
}
}
const removeComment = async (c: AdminComment) => {
if (!window.confirm('确定删除这条评论吗?此操作不可恢复。')) return
try {
await $fetch(`/api/admin/comments/${c.id}`, { method: 'DELETE' })
comments.value = comments.value.filter((x) => x.id !== c.id)
showFlash('评论已删除')
} catch (err) {
console.error('delete comment error:', err)
showFlash((err as any)?.data?.message || '删除失败,请重试', 'err')
}
}
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('zh-CN', {
year: 'numeric',
month: 'short',
day: 'numeric',
hour: '2-digit',
minute: '2-digit',
}).format(d)
}
onMounted(loadComments)
</script>
+175
View File
@@ -0,0 +1,175 @@
<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>
</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>
<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'
definePageMeta({ middleware: 'admin', layout: 'admin' })
useSeoMeta({ title: '联系消息' })
interface AdminContact {
id: number
name: string
email: string
subject: string
message: string
delivered: number
createdAt: string
}
const contacts = ref<AdminContact[]>([])
const loading = ref(true)
const loadError = ref('')
const deliveredCount = computed(() => contacts.value.filter((c) => Number(c.delivered) === 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 = ''
try {
const data = await $fetch<{ contacts: AdminContact[] }>('/api/admin/contacts')
contacts.value = data.contacts
} catch (err) {
console.error('load contacts error:', err)
loadError.value = '加载失败,请重试'
} finally {
loading.value = false
}
}
const removeContact = async (c: AdminContact) => {
if (!window.confirm(`确定删除「${c.name}」的这条消息吗?此操作不可恢复。`)) return
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')
}
}
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('zh-CN', {
year: 'numeric',
month: 'short',
day: 'numeric',
hour: '2-digit',
minute: '2-digit',
}).format(d)
}
onMounted(loadContacts)
</script>
+135
View File
@@ -0,0 +1,135 @@
<script setup lang="ts">
/**
* 后台 Dashboard:渲染 /api/admin/stats 统计卡片。
*/
import { computed, onMounted, ref } from 'vue'
definePageMeta({ middleware: 'admin', layout: 'admin' })
useHead({ title: 'Dashboard' })
interface Stats {
articles: number
works: number
publishedArticles: number
publishedWorks: number
users: number
comments: number
contacts: number
subscribers: number
favorites: number
}
const stats = ref<Stats | null>(null)
const loading = ref(true)
const error = ref('')
const loadStats = async () => {
loading.value = true
error.value = ''
try {
stats.value = await $fetch<Stats>('/api/admin/stats')
} catch (err: any) {
error.value = err?.data?.message || '统计加载失败'
} finally {
loading.value = false
}
}
onMounted(loadStats)
const cards = computed(() => [
{
label: '动态文章',
value: stats.value?.articles,
sub: () => `已发布 ${stats.value?.publishedArticles ?? 0}`,
icon: 'ph:newspaper',
to: '/admin/news',
},
{
label: '作品',
value: stats.value?.works,
sub: () => `已发布 ${stats.value?.publishedWorks ?? 0}`,
icon: 'ph:image-square',
to: '/admin/work',
},
{ label: '注册用户', value: stats.value?.users, sub: () => '全部用户', icon: 'ph:users-three', to: '/admin/users' },
{ label: '评论', value: stats.value?.comments, sub: () => '全部评论', icon: 'ph:chat-circle-text', to: '/admin/comments' },
{ label: '联系留言', value: stats.value?.contacts, sub: () => '表单留言', icon: 'ph:envelope-simple', to: '/admin/contacts' },
{ label: '订阅邮箱', value: stats.value?.subscribers, sub: () => 'Newsletter', icon: 'ph:paper-plane-tilt', to: '/admin/subscribers' },
{ label: '收藏', value: stats.value?.favorites, sub: () => '作品收藏', icon: 'ph:bookmark-simple', to: '/admin/work' },
])
</script>
<template>
<div>
<!-- 页头 -->
<div class="flex flex-col sm:flex-row sm:items-end sm:justify-between gap-4 mb-8">
<div>
<h1 class="text-2xl md:text-3xl font-bold text-black tracking-tight">Dashboard</h1>
<p class="mt-1 text-sm text-gray-500">站点内容与数据概览</p>
</div>
<div class="flex gap-3">
<NuxtLink
to="/admin/news"
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"
>
<Icon name="ph:plus" class="w-4 h-4" /> 新建动态
</NuxtLink>
<NuxtLink
to="/admin/work"
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"
>
<Icon name="ph:plus" class="w-4 h-4" /> 新建作品
</NuxtLink>
</div>
</div>
<!-- 加载态 -->
<div v-if="loading" class="grid grid-cols-1 sm:grid-cols-2 lg:grid-cols-3 xl:grid-cols-4 gap-5">
<div
v-for="i in 8"
:key="i"
class="rounded-2xl bg-white border border-gray-100 shadow-sm p-6 h-32 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>
<button
type="button"
@click="loadStats"
class="px-5 py-2 rounded-lg bg-black text-white text-sm font-semibold hover:bg-gray-800 transition-colors"
>
重新加载
</button>
</div>
<!-- 统计卡片 -->
<div v-else class="grid grid-cols-1 sm:grid-cols-2 lg:grid-cols-3 xl:grid-cols-4 gap-5">
<NuxtLink
v-for="card in cards"
:key="card.label"
:to="card.to"
class="group rounded-2xl bg-white border border-gray-100 shadow-sm p-6 hover:shadow-lg transition-all duration-300 hover:-translate-y-1"
>
<div class="flex items-center justify-between mb-5">
<div
class="w-11 h-11 rounded-xl bg-gray-100 text-gray-600 flex items-center justify-center group-hover:bg-black group-hover:text-white transition-colors duration-300"
>
<Icon :name="card.icon" class="w-5 h-5" />
</div>
<Icon name="ph:arrow-up-right" class="w-4 h-4 text-gray-300 group-hover:text-gray-500 transition-colors" />
</div>
<p class="text-3xl font-bold text-black">{{ card.value ?? 0 }}</p>
<p class="mt-1 text-sm font-semibold text-gray-800">{{ card.label }}</p>
<p class="mt-0.5 text-xs text-gray-400">{{ card.sub() }}</p>
</NuxtLink>
</div>
</div>
</template>
+533
View File
@@ -0,0 +1,533 @@
<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'
definePageMeta({ middleware: 'admin', layout: 'admin' })
useHead({ title: '动态管理' })
interface Block {
type: string
text: string
}
interface Article {
id?: number
slug: string
category: 'insights' | 'projects' | 'announcements'
titleZh: string
titleEn: string
excerptZh: string
excerptEn: string
contentZh: Block[]
contentEn: Block[]
image: string | null
date: string | null
readTime: number
author: string
published: number
createdAt: string
updatedAt: string
}
const CATEGORIES = [
{ value: 'insights', label: '行业洞察' },
{ value: 'projects', label: '项目动态' },
{ value: 'announcements', label: '公告通知' },
]
const catLabel = (c: string) => CATEGORIES.find((x) => x.value === c)?.label ?? c
/* ---------- 列表 ---------- */
const articles = ref<Article[]>([])
const loading = ref(true)
const error = ref('')
const loadArticles = async () => {
loading.value = true
error.value = ''
try {
const res = await $fetch<{ articles: Article[] }>('/api/admin/articles')
articles.value = res.articles
} catch (err: any) {
error.value = err?.data?.message || '加载失败'
} finally {
loading.value = false
}
}
onMounted(loadArticles)
/* ---------- 提示 ---------- */
const message = ref('')
const messageType = ref<'success' | 'error'>('success')
let toastTimer: ReturnType<typeof setTimeout> | undefined
const toast = (text: string, type: 'success' | 'error' = 'success') => {
message.value = text
messageType.value = type
if (toastTimer) clearTimeout(toastTimer)
toastTimer = setTimeout(() => (message.value = ''), 3000)
}
/* ---------- 表单 ---------- */
const view = ref<'list' | 'form'>('list')
const editingId = ref<number | null>(null)
const saving = ref(false)
const formError = ref('')
const emptyForm = () => ({
slug: '',
category: 'insights' as Article['category'],
titleZh: '',
titleEn: '',
excerptZh: '',
excerptEn: '',
contentZh: [] as Block[],
contentEn: [] as Block[],
image: '',
date: '',
readTime: 5,
author: 'ArcticNewOne',
published: true,
})
const form = reactive(emptyForm())
const openCreate = () => {
Object.assign(form, emptyForm())
editingId.value = null
formError.value = ''
view.value = 'form'
window.scrollTo({ top: 0, behavior: 'smooth' })
}
const openEdit = (a: Article) => {
if (a.id == null) {
toast('该条目缺少 id 字段,暂时无法编辑(后端待补)', 'error')
return
}
editingId.value = a.id
Object.assign(form, {
slug: a.slug,
category: a.category,
titleZh: a.titleZh,
titleEn: a.titleEn,
excerptZh: a.excerptZh,
excerptEn: a.excerptEn,
contentZh: a.contentZh.map((b) => ({ ...b })),
contentEn: a.contentEn.map((b) => ({ ...b })),
image: a.image ?? '',
date: a.date ?? '',
readTime: a.readTime,
author: a.author,
published: !!a.published,
})
formError.value = ''
view.value = 'form'
window.scrollTo({ top: 0, behavior: 'smooth' })
}
const backToList = () => {
view.value = 'list'
window.scrollTo({ top: 0, behavior: 'smooth' })
}
const save = async () => {
formError.value = ''
if (!/^[a-z0-9-]{2,64}$/.test(form.slug)) {
formError.value = 'slug 需为 2-64 位小写字母/数字/中划线'
return
}
if (!form.titleZh.trim() || !form.titleEn.trim()) {
formError.value = '中英文标题均为必填'
return
}
saving.value = true
try {
const payload = {
slug: form.slug,
category: form.category,
titleZh: form.titleZh,
titleEn: form.titleEn,
excerptZh: form.excerptZh,
excerptEn: form.excerptEn,
contentZh: form.contentZh,
contentEn: form.contentEn,
image: form.image || null,
date: form.date || null,
readTime: Number(form.readTime) || 5,
author: form.author.trim() || 'ArcticNewOne',
published: form.published,
}
if (editingId.value != null) {
await $fetch(`/api/admin/articles/${editingId.value}`, { method: 'PATCH', body: payload })
toast('动态已更新')
} else {
await $fetch('/api/admin/articles', { method: 'POST', body: payload })
toast('动态已创建')
}
await loadArticles()
view.value = 'list'
} catch (err: any) {
formError.value = err?.data?.message || '保存失败'
} finally {
saving.value = false
}
}
/* ---------- 删除 ---------- */
const confirmDelete = ref<Article | null>(null)
const deleting = ref(false)
const askDelete = (a: Article) => {
if (a.id == null) {
toast('该条目缺少 id 字段,暂时无法删除(后端待补)', 'error')
return
}
confirmDelete.value = a
}
const doDelete = async () => {
const a = confirmDelete.value
if (!a || a.id == null) return
deleting.value = true
try {
await $fetch(`/api/admin/articles/${a.id}`, { method: 'DELETE' })
toast(`已删除「${a.titleZh}」`)
confirmDelete.value = null
await loadArticles()
} catch (err: any) {
toast(err?.data?.message || '删除失败', 'error')
} finally {
deleting.value = false
}
}
</script>
<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"
>
<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"
>
<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>
<!-- ==================== 列表视图 ==================== -->
<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>
<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"
>
重新加载
</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>
</div>
<!-- 列表 -->
<div v-else class="rounded-2xl bg-white 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-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>
</thead>
<tbody class="divide-y divide-gray-50">
<tr
v-for="a in articles"
:key="a.slug"
class="hover:bg-gray-50/60 transition-colors"
>
<td class="px-5 py-4">
<p class="font-semibold text-black">{{ a.titleZh }}</p>
<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>
</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">
<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="a.published ? 'bg-green-500' : 'bg-amber-500'"
></span>
{{ a.published ? '已发布' : '草稿' }}
</span>
</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"
>
<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"
>
<Icon name="ph:trash" class="w-3.5 h-3.5" /> 删除
</button>
</div>
</td>
</tr>
</tbody>
</table>
</div>
</div>
</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>
<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
v-model="form.slug"
type="text"
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"
/>
<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
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"
/>
</div>
<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"
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"
/>
</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>
</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>
<span class="text-sm" :class="form.published ? 'text-green-700 font-semibold' : 'text-gray-500'">
{{ form.published ? '已发布(前台可见)' : '草稿(前台隐藏)' }}
</span>
</button>
</div>
</div>
</section>
<!-- 标题与摘要 -->
<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>
<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>
</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>
</div>
</div>
</div>
</section>
<!-- 正文内容 -->
<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>
<div class="space-y-6">
<AdminBlockEditor v-model="form.contentZh" label="中文正文" />
<AdminBlockEditor v-model="form.contentEn" label="English Content" />
</div>
</section>
<!-- 封面图 -->
<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>
<AdminImageUpload v-model="form.image" label="封面图" />
</section>
<!-- 提交 -->
<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" />
{{ saving ? '保存中…' : editingId != null ? '保存修改' : '创建动态' }}
</button>
</div>
</div>
</template>
<!-- 删除确认 -->
<AdminConfirmDialog
:open="!!confirmDelete"
:loading="deleting"
title="删除动态"
:message="`确定要删除「${confirmDelete?.titleZh}」吗?该动态下的所有评论将一并删除,此操作不可撤销。`"
confirm-text="删除"
@confirm="doDelete"
@cancel="confirmDelete = null"
/>
</div>
</template>
+171
View File
@@ -0,0 +1,171 @@
<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'
definePageMeta({ middleware: 'admin', layout: 'admin' })
useSeoMeta({ title: '邮件订阅' })
interface AdminSubscriber {
id: number
email: string
createdAt: string
}
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 = ''
try {
const data = await $fetch<{ subscribers: AdminSubscriber[] }>('/api/admin/subscribers')
subscribers.value = data.subscribers
} catch (err) {
console.error('load subscribers error:', err)
loadError.value = '加载失败,请重试'
} finally {
loading.value = false
}
}
const removeSubscriber = async (s: AdminSubscriber) => {
if (!window.confirm(`确定取消订阅「${s.email}」吗?此操作不可恢复。`)) return
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')
}
}
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('zh-CN', {
year: 'numeric',
month: 'short',
day: 'numeric',
hour: '2-digit',
minute: '2-digit',
}).format(d)
}
onMounted(loadSubscribers)
</script>
+212
View File
@@ -0,0 +1,212 @@
<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'
import { useUserStore } from '~/stores/user'
definePageMeta({ middleware: 'admin', layout: 'admin' })
useSeoMeta({ title: '用户管理' })
interface AdminUser {
id: number
username: string
email: string | null
phone: string | null
role: 'user' | 'admin'
createdAt: string
}
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 = ''
try {
const data = await $fetch<{ users: AdminUser[] }>('/api/admin/users')
users.value = data.users
} catch (err) {
console.error('load users error:', err)
loadError.value = '加载失败,请重试'
} finally {
loading.value = false
}
}
// 切换角色(user ↔ admin),后端拒绝修改自己的角色
const toggleRole = async (u: AdminUser) => {
const next: AdminUser['role'] = u.role === 'admin' ? 'user' : 'admin'
try {
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')
}
}
const removeUser = async (u: AdminUser) => {
if (!window.confirm(`确定删除用户「${u.username}」吗?此操作不可恢复。`)) return
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')
}
}
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('zh-CN', {
year: 'numeric',
month: 'short',
day: 'numeric',
hour: '2-digit',
minute: '2-digit',
}).format(d)
}
onMounted(loadUsers)
</script>
+709
View File
@@ -0,0 +1,709 @@
<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'
definePageMeta({ middleware: 'admin', layout: 'admin' })
useHead({ title: '作品管理' })
interface Work {
id?: number
slug: string
category: 'webDesign' | 'branding' | 'development'
titleZh: string
titleEn: string
descriptionZh: string
descriptionEn: string
overviewZh: string
overviewEn: string
challengeZh: string
challengeEn: string
solutionZh: string
solutionEn: string
clientZh: string
clientEn: string
durationZh: string
durationEn: string
year: string
tags: string[]
image: string | null
gallery: string[]
url: string | null
published: number
createdAt: string
updatedAt: string
}
const CATEGORIES = [
{ value: 'webDesign', label: '网页设计' },
{ value: 'branding', label: '品牌设计' },
{ value: 'development', label: '程序开发' },
]
const catLabel = (c: string) => CATEGORIES.find((x) => x.value === c)?.label ?? c
/* ---------- 列表 ---------- */
const works = ref<Work[]>([])
const loading = ref(true)
const error = ref('')
const loadWorks = async () => {
loading.value = true
error.value = ''
try {
const res = await $fetch<{ works: Work[] }>('/api/admin/works')
works.value = res.works
} catch (err: any) {
error.value = err?.data?.message || '加载失败'
} finally {
loading.value = false
}
}
onMounted(loadWorks)
/* ---------- 提示 ---------- */
const message = ref('')
const messageType = ref<'success' | 'error'>('success')
let toastTimer: ReturnType<typeof setTimeout> | undefined
const toast = (text: string, type: 'success' | 'error' = 'success') => {
message.value = text
messageType.value = type
if (toastTimer) clearTimeout(toastTimer)
toastTimer = setTimeout(() => (message.value = ''), 3000)
}
/* ---------- 表单 ---------- */
const view = ref<'list' | 'form'>('list')
const editingId = ref<number | null>(null)
const saving = ref(false)
const formError = ref('')
const emptyForm = () => ({
slug: '',
category: 'webDesign' as Work['category'],
titleZh: '',
titleEn: '',
descriptionZh: '',
descriptionEn: '',
overviewZh: '',
overviewEn: '',
challengeZh: '',
challengeEn: '',
solutionZh: '',
solutionEn: '',
clientZh: '',
clientEn: '',
durationZh: '',
durationEn: '',
year: String(new Date().getFullYear()),
image: '',
gallery: [''] as string[],
url: '',
published: true,
})
const form = reactive(emptyForm())
const tagsText = ref('')
const openCreate = () => {
Object.assign(form, emptyForm())
tagsText.value = ''
editingId.value = null
formError.value = ''
view.value = 'form'
window.scrollTo({ top: 0, behavior: 'smooth' })
}
const openEdit = (w: Work) => {
if (w.id == null) {
toast('该条目缺少 id 字段,暂时无法编辑(后端待补)', 'error')
return
}
editingId.value = w.id
Object.assign(form, {
slug: w.slug,
category: w.category,
titleZh: w.titleZh,
titleEn: w.titleEn,
descriptionZh: w.descriptionZh,
descriptionEn: w.descriptionEn,
overviewZh: w.overviewZh,
overviewEn: w.overviewEn,
challengeZh: w.challengeZh,
challengeEn: w.challengeEn,
solutionZh: w.solutionZh,
solutionEn: w.solutionEn,
clientZh: w.clientZh,
clientEn: w.clientEn,
durationZh: w.durationZh,
durationEn: w.durationEn,
year: w.year,
image: w.image ?? '',
gallery: w.gallery.length ? [...w.gallery] : [''],
url: w.url ?? '',
published: !!w.published,
})
tagsText.value = w.tags.join(', ')
formError.value = ''
view.value = 'form'
window.scrollTo({ top: 0, behavior: 'smooth' })
}
const backToList = () => {
view.value = 'list'
window.scrollTo({ top: 0, behavior: 'smooth' })
}
const save = async () => {
formError.value = ''
if (!/^[a-z0-9-]{2,64}$/.test(form.slug)) {
formError.value = 'slug 需为 2-64 位小写字母/数字/中划线'
return
}
if (!form.titleZh.trim() || !form.titleEn.trim()) {
formError.value = '中英文标题均为必填'
return
}
saving.value = true
try {
const payload = {
slug: form.slug,
category: form.category,
titleZh: form.titleZh,
titleEn: form.titleEn,
descriptionZh: form.descriptionZh,
descriptionEn: form.descriptionEn,
overviewZh: form.overviewZh,
overviewEn: form.overviewEn,
challengeZh: form.challengeZh,
challengeEn: form.challengeEn,
solutionZh: form.solutionZh,
solutionEn: form.solutionEn,
clientZh: form.clientZh,
clientEn: form.clientEn,
durationZh: form.durationZh,
durationEn: form.durationEn,
year: form.year,
tags: tagsText.value.split(',').map((t) => t.trim()).filter(Boolean),
image: form.image || null,
gallery: form.gallery.filter((u) => u.trim()),
url: form.url.trim() || null,
published: form.published,
}
if (editingId.value != null) {
await $fetch(`/api/admin/works/${editingId.value}`, { method: 'PATCH', body: payload })
toast('作品已更新')
} else {
await $fetch('/api/admin/works', { method: 'POST', body: payload })
toast('作品已创建')
}
await loadWorks()
view.value = 'list'
} catch (err: any) {
formError.value = err?.data?.message || '保存失败'
} finally {
saving.value = false
}
}
/* ---------- 删除 ---------- */
const confirmDelete = ref<Work | null>(null)
const deleting = ref(false)
const askDelete = (w: Work) => {
if (w.id == null) {
toast('该条目缺少 id 字段,暂时无法删除(后端待补)', 'error')
return
}
confirmDelete.value = w
}
const doDelete = async () => {
const w = confirmDelete.value
if (!w || w.id == null) return
deleting.value = true
try {
await $fetch(`/api/admin/works/${w.id}`, { method: 'DELETE' })
toast(`已删除「${w.titleZh}」`)
confirmDelete.value = null
await loadWorks()
} catch (err: any) {
toast(err?.data?.message || '删除失败', 'error')
} finally {
deleting.value = false
}
}
/* ---------- 图集(gallery)上传 ---------- */
const galleryFileInput = ref<HTMLInputElement | null>(null)
const uploadingIndex = ref<number | null>(null)
const galleryUploading = ref(false)
const galleryError = ref('')
const pickGalleryFile = (i: number) => {
uploadingIndex.value = i
galleryFileInput.value?.click()
}
const onGalleryFile = async (e: Event) => {
const input = e.target as HTMLInputElement
const file = input.files?.[0]
input.value = ''
if (!file || uploadingIndex.value == null) return
galleryUploading.value = true
galleryError.value = ''
try {
const fd = new FormData()
fd.append('file', file)
const res = await $fetch<{ ok: boolean; url: string }>('/api/admin/upload', {
method: 'POST',
body: fd,
})
form.gallery[uploadingIndex.value] = res.url
} catch (err: any) {
galleryError.value = err?.data?.message || '上传失败'
} finally {
galleryUploading.value = false
}
}
const addGalleryRow = () => form.gallery.push('')
const removeGalleryRow = (i: number) => form.gallery.splice(i, 1)
</script>
<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"
>
<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"
>
<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>
<!-- ==================== 列表视图 ==================== -->
<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>
<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"
>
重新加载
</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>
</div>
<div v-else class="rounded-2xl bg-white 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-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>
</thead>
<tbody class="divide-y divide-gray-50">
<tr
v-for="w in works"
:key="w.slug"
class="hover:bg-gray-50/60 transition-colors"
>
<td class="px-5 py-4">
<div class="flex items-center gap-3">
<img
v-if="w.image"
:src="w.image"
:alt="w.titleZh"
class="w-10 h-10 rounded-lg object-cover border border-gray-100 flex-shrink-0"
/>
<div v-else class="w-10 h-10 rounded-lg bg-gray-100 flex items-center justify-center flex-shrink-0">
<Icon name="ph:image" class="w-4 h-4 text-gray-400" />
</div>
<div class="min-w-0">
<p class="font-semibold text-black truncate">{{ w.titleZh }}</p>
<p class="text-xs text-gray-400 mt-0.5 font-mono truncate">{{ w.slug }}</p>
</div>
</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>
</td>
<td class="px-5 py-4 text-gray-600 whitespace-nowrap">{{ w.year || '-' }}</td>
<td class="px-5 py-4">
<div class="flex flex-wrap gap-1.5 max-w-[220px]">
<span
v-for="tag in w.tags.slice(0, 3)"
:key="tag"
class="px-2 py-0.5 rounded-full bg-gray-50 text-gray-500 text-xs"
>
{{ tag }}
</span>
<span v-if="w.tags.length > 3" class="text-xs text-gray-400">+{{ w.tags.length - 3 }}</span>
</div>
</td>
<td class="px-5 py-4">
<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.published ? 'bg-green-500' : 'bg-amber-500'"
></span>
{{ w.published ? '已发布' : '草稿' }}
</span>
</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"
>
<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"
>
<Icon name="ph:trash" class="w-3.5 h-3.5" /> 删除
</button>
</div>
</td>
</tr>
</tbody>
</table>
</div>
</div>
</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>
<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
v-model="form.slug"
type="text"
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"
/>
<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
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"
/>
</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>
<span class="text-sm" :class="form.published ? 'text-green-700 font-semibold' : 'text-gray-500'">
{{ form.published ? '已发布(前台可见)' : '草稿(前台隐藏)' }}
</span>
</button>
</div>
</div>
</section>
<!-- 标题与简介 -->
<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>
<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>
</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>
</div>
</div>
</div>
</section>
<!-- 项目详情(中英) -->
<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>
<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>
</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>
</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" />
</div>
</div>
</div>
</section>
<!-- 封面图 -->
<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>
<AdminImageUpload v-model="form.image" label="封面图" />
</section>
<!-- 作品图集 -->
<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"
>
<Icon name="ph:plus" class="w-3.5 h-3.5" /> 添加图片
</button>
</div>
<div class="space-y-3">
<div
v-for="(url, i) in form.gallery"
:key="i"
class="flex items-center gap-3 border border-gray-200 rounded-xl bg-white p-3"
>
<div class="flex-1 min-w-0">
<input
v-model="form.gallery[i]"
type="text"
placeholder="图片 URL(本地 /uploads/... 或 https://...)"
class="w-full px-3 py-2 rounded-lg border border-gray-200 bg-gray-50 text-sm outline-none transition-all focus:border-black focus:bg-white"
/>
<div v-if="url" class="mt-2">
<img :src="url" alt="图集预览" class="h-24 w-auto max-w-full rounded-lg border border-gray-100 object-cover" />
</div>
</div>
<button
type="button"
:disabled="galleryUploading && uploadingIndex === i"
@click="pickGalleryFile(i)"
class="flex items-center gap-1.5 px-3 py-2 rounded-lg bg-black text-white text-xs font-semibold hover:bg-gray-800 transition-colors disabled:opacity-60 flex-shrink-0"
>
<Icon
:name="galleryUploading && uploadingIndex === i ? 'ph:circle-notch' : 'ph:upload-simple'"
:class="galleryUploading && uploadingIndex === i ? 'w-3.5 h-3.5 animate-spin' : 'w-3.5 h-3.5'"
/>
{{ galleryUploading && uploadingIndex === i ? '上传中…' : '上传' }}
</button>
<button
type="button"
@click="removeGalleryRow(i)"
class="w-8 h-8 rounded-lg hover:bg-red-50 text-gray-400 hover:text-red-600 flex items-center justify-center transition-colors flex-shrink-0"
aria-label="删除该图"
>
<Icon name="ph:trash" class="w-4 h-4" />
</button>
</div>
<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>
<!-- 提交 -->
<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" />
{{ saving ? '保存中…' : editingId != null ? '保存修改' : '创建作品' }}
</button>
</div>
</div>
</template>
<!-- 删除确认 -->
<AdminConfirmDialog
:open="!!confirmDelete"
:loading="deleting"
title="删除作品"
:message="`确定要删除「${confirmDelete?.titleZh}」吗?该作品下的所有收藏将一并删除,此操作不可撤销。`"
confirm-text="删除"
@confirm="doDelete"
@cancel="confirmDelete = null"
/>
</div>
</template>
+88 -40
View File
@@ -14,7 +14,7 @@
<!-- 文章 Hero -->
<section class="relative h-[50vh] md:h-[60vh] overflow-hidden">
<img
:src="article.image"
:src="article.image || ''"
:alt="title"
class="w-full h-full object-cover"
/>
@@ -23,7 +23,7 @@
<div class="max-w-[800px] mx-auto">
<span
class="inline-block px-3 py-1.5 text-xs md:text-sm font-semibold rounded-full mb-4"
:class="article.badge"
:class="categoryBadge[article.category]"
>
{{ t(`news.categories.${article.category}`) }}
</span>
@@ -48,41 +48,38 @@
</div>
</section>
<!-- 文章内容 -->
<!-- 文章内容(内容块:paragraph / heading / quote / image) -->
<section class="max-w-[800px] mx-auto px-6 md:px-10 py-16 md:py-24">
<article class="prose prose-lg max-w-none">
<p class="text-gray-700 text-lg leading-relaxed mb-8">
{{ t(`news.detail.items.${slug}.content`) }}
</p>
<template v-for="(block, index) in blocks" :key="index">
<p
v-if="block.type === 'paragraph'"
class="text-gray-700 text-lg leading-relaxed mb-8"
>
{{ block.text }}
</p>
<h2 class="text-2xl md:text-3xl font-bold text-black mb-6 mt-12">
{{ t(`news.detail.items.${slug}.section1Title`) }}
</h2>
<p class="text-gray-700 text-lg leading-relaxed mb-8">
{{ t(`news.detail.items.${slug}.section1Content`) }}
</p>
<h2
v-else-if="block.type === 'heading'"
class="text-2xl md:text-3xl font-bold text-black mb-6 mt-12"
>
{{ block.text }}
</h2>
<blockquote class="border-l-4 border-black pl-6 my-10 italic text-gray-600 text-lg">
"{{ t(`news.detail.items.${slug}.quote`) }}"
</blockquote>
<blockquote
v-else-if="block.type === 'quote'"
class="border-l-4 border-black pl-6 my-10 italic text-gray-600 text-lg"
>
"{{ block.text }}"
</blockquote>
<h2 class="text-2xl md:text-3xl font-bold text-black mb-6 mt-12">
{{ t(`news.detail.items.${slug}.section2Title`) }}
</h2>
<p class="text-gray-700 text-lg leading-relaxed mb-8">
{{ t(`news.detail.items.${slug}.section2Content`) }}
</p>
<div class="my-10 rounded-2xl overflow-hidden">
<img :src="article.image" :alt="title" class="w-full h-auto" />
</div>
<h2 class="text-2xl md:text-3xl font-bold text-black mb-6 mt-12">
{{ t(`news.detail.items.${slug}.section3Title`) }}
</h2>
<p class="text-gray-700 text-lg leading-relaxed mb-8">
{{ t(`news.detail.items.${slug}.section3Content`) }}
</p>
<img
v-else-if="block.type === 'image'"
:src="block.text"
:alt="title"
class="my-10 rounded-2xl w-full h-auto"
/>
</template>
</article>
<!-- 分享按钮(真实动作) -->
@@ -135,12 +132,12 @@
class="group block rounded-2xl overflow-hidden bg-white shadow-lg hover:shadow-xl transition-all duration-300 hover:-translate-y-1"
>
<div class="relative aspect-[16/10] overflow-hidden">
<img :src="related.image" :alt="t(`news.items.${related.slug}.title`)" class="w-full h-full object-cover transition-transform duration-500 group-hover:scale-105" />
<img :src="related.image || ''" :alt="locText(related.titleZh, related.titleEn)" class="w-full h-full object-cover transition-transform duration-500 group-hover:scale-105" />
</div>
<div class="p-5">
<span class="text-xs text-gray-500">{{ formatNewsDate(related.date, locale) }}</span>
<h3 class="text-lg font-bold text-black group-hover:text-gray-600 transition-colors mt-1 line-clamp-2">
{{ t(`news.items.${related.slug}.title`) }}
{{ locText(related.titleZh, related.titleEn) }}
</h3>
</div>
</NuxtLink>
@@ -155,25 +152,76 @@ import { computed, ref } from 'vue'
import { useRoute } from 'vue-router'
import { useI18n } from 'vue-i18n'
import { useSeoMeta, createError } from '#imports'
import { newsBySlug, newsItems, formatNewsDate } from '~/data/news'
const { t, locale } = useI18n()
const route = useRoute()
const slug = route.params.slug as string
const article = newsBySlug[slug]
interface Block {
type: 'paragraph' | 'heading' | 'quote' | 'image'
text: string
}
if (!article) {
interface ArticleItem {
slug: string
category: 'insights' | 'projects' | 'announcements'
titleZh: string
titleEn: string
excerptZh: string
excerptEn: string
contentZh: Block[]
contentEn: Block[]
image: string | null
date: string | null
readTime: number
author: string
}
const [{ data, error }, { data: listData }] = await Promise.all([
useFetch<{ article: ArticleItem }>(`/api/news/${slug}`),
useFetch<{ articles: ArticleItem[] }>('/api/news'),
])
// 未发布 / 不存在 → 404
if (error.value || !data.value?.article) {
throw createError({ statusCode: 404, statusMessage: 'Article not found' })
}
const title = computed(() => t(`news.items.${slug}.title`))
const article = computed<ArticleItem>(() => data.value!.article)
const relatedArticles = newsItems.filter((a) => a.slug !== slug).slice(0, 3)
const locText = (zh: string, en: string) => (locale.value === 'zh' ? zh : en)
function formatNewsDate(date: string | null, loc: string): string {
if (!date) return ''
const d = new Date(`${date}T00:00:00`)
if (Number.isNaN(d.getTime())) return date
return new Intl.DateTimeFormat(loc === 'zh' ? 'zh-CN' : 'en-US', {
year: 'numeric',
month: 'long',
day: 'numeric',
}).format(d)
}
const categoryBadge: Record<string, string> = {
insights: 'bg-purple-100 text-purple-700',
projects: 'bg-blue-100 text-blue-700',
announcements: 'bg-green-100 text-green-700',
}
const title = computed(() => locText(article.value.titleZh, article.value.titleEn))
// 正文内容块(按当前语言选择 contentZh / contentEn)
const blocks = computed(() =>
locale.value === 'zh' ? article.value.contentZh : article.value.contentEn,
)
const relatedArticles = computed(() =>
(listData.value?.articles ?? []).filter((a) => a.slug !== slug).slice(0, 3),
)
useSeoMeta({
title: () => `${title.value} - ${t('news.title')}`,
description: () => t(`news.items.${slug}.excerpt`),
description: () => locText(article.value.excerptZh, article.value.excerptEn),
})
// ---- 分享(真实动作) ----
+47 -10
View File
@@ -58,15 +58,15 @@
>
<div class="relative aspect-[16/10] overflow-hidden bg-gray-100">
<img
:src="article.image"
:alt="t(`news.items.${article.slug}.title`)"
:src="article.image || ''"
:alt="locText(article.titleZh, article.titleEn)"
:loading="'lazy'"
class="w-full h-full object-cover transition-transform duration-700 group-hover:scale-110"
/>
<div class="absolute top-4 left-4">
<span
class="px-3 py-1.5 text-xs md:text-sm font-semibold rounded-full shadow-sm"
:class="article.badge"
:class="categoryBadge[article.category]"
>
{{ t(`news.categories.${article.category}`) }}
</span>
@@ -86,11 +86,11 @@
</div>
<h3 class="text-lg md:text-xl font-bold text-black mb-3 group-hover:text-gray-700 transition-colors duration-300 line-clamp-2">
{{ t(`news.items.${article.slug}.title`) }}
{{ locText(article.titleZh, article.titleEn) }}
</h3>
<p class="text-sm md:text-base text-gray-600 mb-4 flex-grow line-clamp-3">
{{ t(`news.items.${article.slug}.excerpt`) }}
{{ locText(article.excerptZh, article.excerptEn) }}
</p>
<div class="flex items-center justify-between pt-3 border-t border-gray-100">
@@ -127,11 +127,48 @@ import { useI18n } from 'vue-i18n'
import { useSeoMeta } from '#imports'
import gsap from 'gsap'
import { useAppStore } from '~/stores/app'
import { newsItems, formatNewsDate, getNewsCategories } from '~/data/news'
const { t, locale } = useI18n()
const appStore = useAppStore()
interface ArticleItem {
slug: string
category: 'insights' | 'projects' | 'announcements'
titleZh: string
titleEn: string
excerptZh: string
excerptEn: string
image: string | null
date: string | null
readTime: number
author: string
}
// 内容 API(仅已发布,date 降序)
const { data } = await useFetch<{ articles: ArticleItem[] }>('/api/news')
const articles = computed(() => data.value?.articles ?? [])
// 双语选择:切换语言即时生效(内容双字段已在 API 返回,无需重新请求)
const locText = (zh: string, en: string) => (locale.value === 'zh' ? zh : en)
function formatNewsDate(date: string | null, loc: string): string {
if (!date) return ''
const d = new Date(`${date}T00:00:00`)
if (Number.isNaN(d.getTime())) return date
return new Intl.DateTimeFormat(loc === 'zh' ? 'zh-CN' : 'en-US', {
year: 'numeric',
month: 'long',
day: 'numeric',
}).format(d)
}
// 分类徽章样式(insights=紫、projects=蓝、announcements=绿)
const categoryBadge: Record<string, string> = {
insights: 'bg-purple-100 text-purple-700',
projects: 'bg-blue-100 text-blue-700',
announcements: 'bg-green-100 text-green-700',
}
const headerWrapRef = ref<HTMLElement | null>(null)
const titleRef = ref<HTMLElement | null>(null)
const descRef = ref<HTMLElement | null>(null)
@@ -144,16 +181,16 @@ const visibleCount = ref(0)
const PAGE_SIZE = 6
const categories = ['all', ...getNewsCategories()]
const categories = ['all', 'insights', 'projects', 'announcements']
// 分类 + 搜索过滤(标题/摘要按当前语言文案匹配)
const filteredNews = computed(() => {
const kw = keyword.value.trim().toLowerCase()
return newsItems.filter((item) => {
return articles.value.filter((item) => {
if (activeCategory.value !== 'all' && item.category !== activeCategory.value) return false
if (!kw) return true
const title = t(`news.items.${item.slug}.title`).toLowerCase()
const excerpt = t(`news.items.${item.slug}.excerpt`).toLowerCase()
const title = locText(item.titleZh, item.titleEn).toLowerCase()
const excerpt = locText(item.excerptZh, item.excerptEn).toLowerCase()
return title.includes(kw) || excerpt.includes(kw)
})
})
+52 -18
View File
@@ -14,7 +14,7 @@
<!-- Hero 大图 -->
<section class="relative h-[60vh] md:h-[70vh] overflow-hidden">
<img
:src="project.image"
:src="project.image || ''"
:alt="title"
class="w-full h-full object-cover"
/>
@@ -34,7 +34,7 @@
{{ title }}
</h1>
<p class="text-lg md:text-xl text-white/80 max-w-2xl">
{{ t(`work.items.${slug}.description`) }}
{{ description }}
</p>
</div>
</div>
@@ -48,26 +48,26 @@
<div>
<h2 class="text-2xl md:text-3xl font-bold text-black mb-6">{{ t('work.detail.overview') }}</h2>
<p class="text-gray-700 text-base md:text-lg leading-relaxed">
{{ t(`work.detail.items.${slug}.overview`) }}
{{ locText(project.overviewZh, project.overviewEn) }}
</p>
</div>
<div>
<h2 class="text-2xl md:text-3xl font-bold text-black mb-6">{{ t('work.detail.challenge') }}</h2>
<p class="text-gray-700 text-base md:text-lg leading-relaxed">
{{ t(`work.detail.items.${slug}.challenge`) }}
{{ locText(project.challengeZh, project.challengeEn) }}
</p>
</div>
<div>
<h2 class="text-2xl md:text-3xl font-bold text-black mb-6">{{ t('work.detail.solution') }}</h2>
<p class="text-gray-700 text-base md:text-lg leading-relaxed">
{{ t(`work.detail.items.${slug}.solution`) }}
{{ locText(project.solutionZh, project.solutionEn) }}
</p>
</div>
<!-- 项目截图 -->
<div class="space-y-6">
<div v-if="project.gallery.length" class="space-y-6">
<h2 class="text-2xl md:text-3xl font-bold text-black">{{ t('work.detail.gallery') }}</h2>
<div class="grid grid-cols-1 md:grid-cols-2 gap-6">
<div
@@ -89,7 +89,7 @@
<div class="space-y-5">
<div>
<p class="text-sm text-gray-500 mb-1">{{ t('work.detail.client') }}</p>
<p class="text-base font-semibold text-black">{{ t(`work.detail.items.${slug}.client`) }}</p>
<p class="text-base font-semibold text-black">{{ locText(project.clientZh, project.clientEn) }}</p>
</div>
<div>
<p class="text-sm text-gray-500 mb-1">{{ t('work.detail.year') }}</p>
@@ -97,7 +97,7 @@
</div>
<div>
<p class="text-sm text-gray-500 mb-1">{{ t('work.detail.duration') }}</p>
<p class="text-base font-semibold text-black">{{ t(`work.detail.items.${slug}.duration`) }}</p>
<p class="text-base font-semibold text-black">{{ locText(project.durationZh, project.durationEn) }}</p>
</div>
<div>
<p class="text-sm text-gray-500 mb-1">{{ t('work.detail.services') }}</p>
@@ -146,11 +146,11 @@
class="group block rounded-2xl overflow-hidden bg-white shadow-lg hover:shadow-xl transition-all duration-300 hover:-translate-y-1"
>
<div class="relative aspect-[4/3] overflow-hidden">
<img :src="related.image" :alt="t(`work.items.${related.slug}.title`)" class="w-full h-full object-cover transition-transform duration-500 group-hover:scale-105" />
<img :src="related.image || ''" :alt="locText(related.titleZh, related.titleEn)" class="w-full h-full object-cover transition-transform duration-500 group-hover:scale-105" />
</div>
<div class="p-5">
<h3 class="text-lg font-bold text-black group-hover:text-gray-600 transition-colors">{{ t(`work.items.${related.slug}.title`) }}</h3>
<p class="text-sm text-gray-500 mt-1">{{ related.tags[0] }}</p>
<h3 class="text-lg font-bold text-black group-hover:text-gray-600 transition-colors">{{ locText(related.titleZh, related.titleEn) }}</h3>
<p class="text-sm text-gray-500 mt-1">{{ related.tags?.[0] }}</p>
</div>
</NuxtLink>
</div>
@@ -164,24 +164,58 @@ import { computed } from 'vue'
import { useRoute } from 'vue-router'
import { useI18n } from 'vue-i18n'
import { useSeoMeta, createError } from '#imports'
import { workBySlug, workItems } from '~/data/work'
const { t } = useI18n()
const { t, locale } = useI18n()
const route = useRoute()
const slug = route.params.slug as string
const project = workBySlug[slug]
interface WorkItem {
slug: string
category: 'webDesign' | 'branding' | 'development'
titleZh: string
titleEn: string
descriptionZh: string
descriptionEn: string
overviewZh: string
overviewEn: string
challengeZh: string
challengeEn: string
solutionZh: string
solutionEn: string
clientZh: string
clientEn: string
durationZh: string
durationEn: string
year: string
tags: string[]
image: string | null
gallery: string[]
url: string | null
}
if (!project) {
const [{ data, error }, { data: listData }] = await Promise.all([
useFetch<{ work: WorkItem }>(`/api/work/${slug}`),
useFetch<{ works: WorkItem[] }>('/api/work'),
])
// 未发布 / 不存在 → 404
if (error.value || !data.value?.work) {
throw createError({ statusCode: 404, statusMessage: 'Project not found' })
}
const title = computed(() => t(`work.items.${slug}.title`))
const project = computed<WorkItem>(() => data.value!.work)
const relatedProjects = workItems.filter((p) => p.slug !== slug).slice(0, 3)
const locText = (zh: string, en: string) => (locale.value === 'zh' ? zh : en)
const title = computed(() => locText(project.value.titleZh, project.value.titleEn))
const description = computed(() => locText(project.value.descriptionZh, project.value.descriptionEn))
const relatedProjects = computed(() =>
(listData.value?.works ?? []).filter((p) => p.slug !== slug).slice(0, 3),
)
useSeoMeta({
title: () => `${title.value} - ${t('work.title')}`,
description: () => t(`work.items.${slug}.description`),
description: () => description.value,
})
</script>
+28 -10
View File
@@ -58,8 +58,8 @@
>
<div class="relative aspect-[4/3] overflow-hidden bg-gray-100">
<img
:src="project.image"
:alt="t(`work.items.${project.slug}.title`)"
:src="project.image || ''"
:alt="locText(project.titleZh, project.titleEn)"
:loading="'lazy'"
class="w-full h-full object-cover transition-transform duration-700 group-hover:scale-110"
/>
@@ -69,13 +69,13 @@
<div class="p-6 md:p-8 bg-white">
<div class="flex items-start justify-between mb-3">
<h3 class="text-xl md:text-2xl font-bold text-black group-hover:text-gray-700 transition-colors duration-300">
{{ t(`work.items.${project.slug}.title`) }}
{{ locText(project.titleZh, project.titleEn) }}
</h3>
<div class="w-9 h-9 md:w-10 md:h-10 rounded-full flex items-center justify-center bg-gray-50 text-gray-400 group-hover:bg-black group-hover:text-white transition-all duration-300 flex-shrink-0 ml-3">
<Icon name="ph:arrow-up-right" class="w-4 h-4 md:w-5 md:h-5" />
</div>
</div>
<p class="text-sm md:text-base text-gray-600 mb-4">{{ t(`work.items.${project.slug}.description`) }}</p>
<p class="text-sm md:text-base text-gray-600 mb-4">{{ locText(project.descriptionZh, project.descriptionEn) }}</p>
<div class="flex flex-wrap gap-2">
<span
v-for="tag in project.tags"
@@ -111,11 +111,29 @@ import { useI18n } from 'vue-i18n'
import { useSeoMeta } from '#imports'
import gsap from 'gsap'
import { useAppStore } from '~/stores/app'
import { workItems, getWorkCategories } from '~/data/work'
const { t } = useI18n()
const { t, locale } = useI18n()
const appStore = useAppStore()
interface WorkItem {
slug: string
category: 'webDesign' | 'branding' | 'development'
titleZh: string
titleEn: string
descriptionZh: string
descriptionEn: string
year: string
tags: string[]
image: string | null
}
// 内容 API(仅已发布)
const { data } = await useFetch<{ works: WorkItem[] }>('/api/work')
const works = computed(() => data.value?.works ?? [])
// 双语选择:切换语言即时生效
const locText = (zh: string, en: string) => (locale.value === 'zh' ? zh : en)
const headerWrapRef = ref<HTMLElement | null>(null)
const titleRef = ref<HTMLElement | null>(null)
const descRef = ref<HTMLElement | null>(null)
@@ -128,16 +146,16 @@ const visibleCount = ref(0)
const PAGE_SIZE = 4
const categories = ['all', ...getWorkCategories()]
const categories = ['all', 'webDesign', 'branding', 'development']
// 分类 + 搜索过滤(标题/描述按当前语言文案匹配)
const filteredWork = computed(() => {
const kw = keyword.value.trim().toLowerCase()
return workItems.filter((item) => {
return works.value.filter((item) => {
if (activeCategory.value !== 'all' && item.category !== activeCategory.value) return false
if (!kw) return true
const title = t(`work.items.${item.slug}.title`).toLowerCase()
const desc = t(`work.items.${item.slug}.description`).toLowerCase()
const title = locText(item.titleZh, item.titleEn).toLowerCase()
const desc = locText(item.descriptionZh, item.descriptionEn).toLowerCase()
return title.includes(kw) || desc.includes(kw)
})
})
+10
View File
@@ -0,0 +1,10 @@
import { defineNuxtPlugin } from '#app'
/**
* 客户端启动时从服务端会话恢复登录状态(在路由守卫前完成,
* 保证 admin 中间件与 /account 页能立即拿到真实用户)。
*/
export default defineNuxtPlugin(async () => {
const userStore = useUserStore()
await userStore.restoreUser()
})
+9
View File
@@ -17,6 +17,7 @@
# SMTP_HOST/PORT/USER/PASS/FROM 邮件
# CONTACT_TO 联系表单收件邮箱
# ADMIN_EMAILS 管理员邮箱(逗号分隔)
# ADMIN_INITIAL_PASSWORD 预置管理员初始密码(缺省自动生成并打印)
# SITE_URL 站点公开地址(默认 https://personal.virtheart.com)
# =========================================================
set -euo pipefail
@@ -72,6 +73,13 @@ if [ -z "${SESSION_SECRET}" ]; then
fi
# 注意:Nuxt runtimeConfig 的环境变量一律使用 NUXT_ 前缀
# 预置管理员密码(首次部署生成,用于 DB 初始化时创建 admin 账号)
ADMIN_INITIAL_PASSWORD="${ADMIN_INITIAL_PASSWORD:-}"
if [ -z "${ADMIN_INITIAL_PASSWORD}" ]; then
ADMIN_INITIAL_PASSWORD="$(openssl rand -base64 18 2>/dev/null | tr -d '/+=' | cut -c1-16)"
echo " (已自动生成预置管理员密码,请保存: ${ADMIN_INITIAL_PASSWORD})"
fi
kubectl create secret generic app-secrets -n "${NAMESPACE}" \
--from-literal="NUXT_SESSION_SECRET=${SESSION_SECRET}" \
--from-literal="NUXT_SMTP_HOST=${SMTP_HOST:-}" \
@@ -81,6 +89,7 @@ kubectl create secret generic app-secrets -n "${NAMESPACE}" \
--from-literal="NUXT_SMTP_FROM=${SMTP_FROM:-}" \
--from-literal="NUXT_CONTACT_TO=${CONTACT_TO:-}" \
--from-literal="NUXT_ADMIN_EMAILS=${ADMIN_EMAILS:-}" \
--from-literal="NUXT_ADMIN_INITIAL_PASSWORD=${ADMIN_INITIAL_PASSWORD}" \
--dry-run=client -o yaml | kubectl apply -f - >/dev/null
kubectl create configmap app-config -n "${NAMESPACE}" \
+4 -161
View File
@@ -277,32 +277,6 @@
},
"cta": "View Project",
"backToList": "Back to Work",
"items": {
"forma-digital": {
"title": "Forma Digital",
"description": "A modern e-commerce platform with seamless user experience and dynamic product showcases."
},
"one-step": {
"title": "One Step",
"description": "Brand identity and marketing campaign for a fitness app focused on sustainable habits."
},
"nero-vision": {
"title": "Nero Vision",
"description": "Full-stack web application for creative professionals to manage their portfolios."
},
"bold-moves": {
"title": "Bold Moves",
"description": "Interactive website showcasing innovative architectural designs with 3D visualizations."
},
"echo-labs": {
"title": "Echo Labs",
"description": "Corporate branding and visual identity for a tech startup in the AI space."
},
"flux-api": {
"title": "Flux API",
"description": "Scalable REST API with comprehensive documentation and developer tools."
}
},
"detail": {
"overview": "Overview",
"challenge": "Challenge",
@@ -314,51 +288,7 @@
"duration": "Duration",
"services": "Services",
"visitProject": "Visit Project",
"relatedProjects": "Related Projects",
"items": {
"forma-digital": {
"overview": "Forma Digital is a modern e-commerce platform designed to provide a seamless shopping experience. We redesigned the entire user interface with a minimalist design approach, focusing on product showcase and conversion optimization.",
"challenge": "The client needed a platform that could both showcase premium products and deliver a smooth shopping experience. The existing website was slow, had poor mobile experience, and low conversion rates.",
"solution": "We built the platform with React + Next.js, implementing server-side rendering and static generation for blazing fast load times. The product pages feature immersive large-format imagery with smooth animation transitions.",
"client": "Forma Digital Inc.",
"duration": "3 months"
},
"one-step": {
"overview": "One Step is a fitness app focused on building healthy habits. We created a complete brand visual identity system including logo design, UI interface, and marketing materials.",
"challenge": "In the competitive fitness app market, how to stand out through brand design and establish unique brand recognition.",
"solution": "With the core concept of 'one step at a time', we designed a clean and powerful brand identity. Using gradient colors and rounded graphic language to convey health, positivity, and progress.",
"client": "One Step Fitness",
"duration": "2 months"
},
"nero-vision": {
"overview": "Nero Vision is a portfolio management platform for creative professionals, helping designers and artists showcase and manage their work.",
"challenge": "Creative professionals need a platform that can perfectly showcase work while being easy to manage. Existing solutions are either too complex or have poor display quality.",
"solution": "We developed a full-stack application with Vue.js + Node.js, designing an intuitive drag-and-drop portfolio management interface with beautiful display templates.",
"client": "Nero Studio",
"duration": "4 months"
},
"bold-moves": {
"overview": "Bold Moves is an interactive website showcasing innovative architectural designs through 3D visualization technology, letting users experience architecture immersively.",
"challenge": "How to present complex architectural designs in an intuitive and engaging way to general users while maintaining professionalism.",
"solution": "We used Three.js for high-quality 3D rendering with smooth interactive design, allowing users to appreciate architectural details from any angle, with lighting effects and material displays.",
"client": "Bold Moves Architecture",
"duration": "5 months"
},
"echo-labs": {
"overview": "Echo Labs is an AI tech startup. We created a complete brand visual identity system and corporate website for them.",
"challenge": "AI brands need to convey both technology and humanity, avoiding being too cold or technical.",
"solution": "With the concept of 'echo', we designed a dynamic brand identity. Using dark themes with gradient colors for a tech feel, while rounded graphic language adds approachability.",
"client": "Echo Labs AI",
"duration": "3 months"
},
"flux-api": {
"overview": "Flux API is a scalable REST API service platform with comprehensive documentation and developer tools to help developers integrate quickly.",
"challenge": "API documentation and developer experience are core competitive advantages. How to make complex APIs easy to understand and use.",
"solution": "We designed interactive API documentation with online testing and code generation. Multi-language SDKs and detailed tutorials significantly reduce the learning curve for developers.",
"client": "Flux Technologies",
"duration": "6 months"
}
}
"relatedProjects": "Related Projects"
}
},
"studio": {
@@ -419,97 +349,9 @@
"announcements": "Announcements"
},
"minutes": "min",
"items": {
"design-trends-2026": {
"title": "Design Trends Shaping 2026",
"excerpt": "Explore the emerging design trends defining digital experiences this year, from minimalism to bold typography."
},
"forma-digital-launch": {
"title": "Forma Digital Platform Launch",
"excerpt": "We are excited to announce the successful launch of Forma Digital, a revolutionary e-commerce experience."
},
"studio-expansion": {
"title": "Studio Expansion Announcement",
"excerpt": "ArcticNewOne is growing! We are expanding our team and capabilities to serve you better."
},
"ux-research-methods": {
"title": "Modern UX Research Methods",
"excerpt": "Dive into the latest user experience research methodologies, from remote testing to behavioral analytics."
},
"bold-moves-case-study": {
"title": "Bold Moves: A Case Study",
"excerpt": "Behind the scenes of our award-winning architectural visualization project featuring cutting-edge 3D technology."
},
"new-tools-integration": {
"title": "New Tools Added to Our Platform",
"excerpt": "Check out the latest additions to our toolbox across design, development and collaboration."
}
},
"detail": {
"shareArticle": "Share Article",
"relatedArticles": "Related Articles",
"items": {
"design-trends-2026": {
"content": "In 2026, the design industry is undergoing a profound transformation. From the return of minimalism to the rise of bold typography, from the普及 of 3D elements to the maturity of AI-assisted design, these trends are redefining the boundaries of digital experiences.",
"section1Title": "The Return of Minimalism",
"section1Content": "In an age of information overload, users increasingly渴望 clean, clear interfaces. 2026's minimalism isn't just 'less is more' — it's about delivering more value in limited space through careful information architecture and visual hierarchy.",
"quote": "Good design isn't about adding more, it's about removing the unnecessary. In 2026, this matters more than ever.",
"section2Title": "Bold Typography & Dynamic Text",
"section2Content": "Typography is moving from supporting actor to leading role. Large, high-contrast font designs are becoming important brand expression tools. Dynamic text effects are making typography a living, interactive element rather than static decoration.",
"section3Title": "Maturity of AI-Assisted Design",
"section3Content": "AI tools are shifting from 'replacing designers' to 'empowering designers.' Smart layout suggestions, automated color schemes, and real-time design feedback let designers focus on creativity and strategy rather than repetitive execution."
},
"forma-digital-launch": {
"content": "After three months of careful crafting, we're excited to announce the official launch of the Forma Digital e-commerce platform! This project is one of our team's most challenging works to date.",
"section1Title": "Project Background",
"section1Content": "Forma Digital is an e-commerce brand focusing on premium home goods. They needed a platform that could perfectly showcase product quality while delivering a smooth shopping experience.",
"quote": "The ArcticNewOne team not only understood our needs but exceeded our expectations. After the new platform launched, our conversion rate increased by 45%.",
"section2Title": "Technical Highlights",
"section2Content": "We used React + Next.js for server-side rendering and static generation. Through lazy loading, code splitting, and CDN acceleration, we reduced first load time from 4.5s to 1.2s.",
"section3Title": "Results",
"section3Content": "After launch, user停留 time increased by 60%, bounce rate decreased by 35%, and conversion rate improved by 45%."
},
"studio-expansion": {
"content": "With continued business growth and increasing client demand, we're excited to announce the official expansion of ArcticNewOne Studio!",
"section1Title": "Team Growth",
"section1Content": "We're adding 5 senior designers and 3 senior developers covering frontend, backend, UI/UX, and more. All new members have extensive industry experience.",
"quote": "Talent is our most valuable asset. By expanding our team, we can take on more projects while maintaining consistent high-quality delivery.",
"section2Title": "Service Upgrade",
"section2Content": "In addition to existing services, we're adding data visualization, AI application development, AR/VR experience design, and other cutting-edge services.",
"section3Title": "Looking Ahead",
"section3Content": "We plan to complete 50+ projects and serve 30+ new clients in the coming year while continuing to explore new possibilities."
},
"ux-research-methods": {
"content": "UX research is the foundation of design decisions. In 2026, as technology evolves and user behaviors change, UX research methods continue to advance.",
"section1Title": "Remote User Testing",
"section1Content": "Remote user testing has become mainstream. Through professional platforms, we can recruit test users globally and gather broader feedback in less time.",
"quote": "Remote testing not only reduces costs but more importantly lets us access more authentic user scenarios.",
"section2Title": "Behavioral Data Analysis",
"section2Content": "Through heatmaps, scroll depth, click streams, and other behavioral data, we can objectively understand how users interact with products.",
"section3Title": "AI-Assisted Analysis",
"section3Content": "AI tools help us analyze user feedback more efficiently. Sentiment analysis, topic clustering, and trend prediction help extract valuable insights from massive data."
},
"bold-moves-case-study": {
"content": "Bold Moves is an interactive website showcasing innovative architectural designs. This article provides an in-depth look at the design思路, technical implementation, and final results.",
"section1Title": "Design Philosophy",
"section1Content": "Bold Moves wanted to showcase architectural beauty digitally. We decided to use 3D visualization to let users appreciate architectural details from any angle.",
"quote": "We didn't just want a showcase website — we wanted a digital space where users could 'walk into' the architecture.",
"section2Title": "Technical Challenges",
"section2Content": "High-quality 3D rendering requires significant computing power, but web performance is limited. We achieved smooth interactions through model optimization, LOD techniques, and WebGL rendering.",
"section3Title": "Final Results",
"section3Content": "The project received widespread acclaim and won multiple design awards. Average user停留 time exceeded 5 minutes, well above industry average."
},
"new-tools-integration": {
"content": "To better serve our clients, we continuously expand and improve our toolbox. Recently, we've added several practical tools covering design, development, collaboration, and more.",
"section1Title": "Design Tool Upgrades",
"section1Content": "We've引入 the latest design collaboration platform supporting real-time multi-person editing, version management, and design system integration.",
"quote": "Good tools significantly boost team efficiency. The right toolchain is key to delivering quality work.",
"section2Title": "Development Tool Enhancements",
"section2Content": "Added automated testing frameworks, performance monitoring tools, and code quality checks to help identify and resolve issues during development.",
"section3Title": "Collaboration Tool Optimization",
"section3Content": "We upgraded our project management platform with new Kanban views, time tracking, and resource allocation features for better project oversight."
}
}
"relatedArticles": "Related Articles"
}
},
"auth": {
@@ -584,7 +426,8 @@
"date": "Date",
"delivered": "Delivered to inbox",
"notDelivered": "Not delivered (SMTP not configured)"
}
},
"adminEntry": "Admin Panel"
},
"comments": {
"title": "Comments",
+4 -161
View File
@@ -277,32 +277,6 @@
},
"cta": "查看项目",
"backToList": "返回作品列表",
"items": {
"forma-digital": {
"title": "Forma Digital",
"description": "现代化的电商平台,无缝用户体验与动态产品展示。"
},
"one-step": {
"title": "One Step",
"description": "为健身应用打造的品牌形象与营销战役,聚焦可持续习惯养成。"
},
"nero-vision": {
"title": "Nero Vision",
"description": "面向创意专业人士的全栈作品集管理应用。"
},
"bold-moves": {
"title": "Bold Moves",
"description": "以 3D 可视化展示创新建筑设计的交互式网站。"
},
"echo-labs": {
"title": "Echo Labs",
"description": "AI 科技创业公司的企业品牌与视觉识别。"
},
"flux-api": {
"title": "Flux API",
"description": "具备完善文档与开发者工具的可扩展 REST API 服务。"
}
},
"detail": {
"overview": "项目概述",
"challenge": "项目挑战",
@@ -314,51 +288,7 @@
"duration": "周期",
"services": "服务内容",
"visitProject": "访问项目",
"relatedProjects": "相关项目",
"items": {
"forma-digital": {
"overview": "Forma Digital 是一个现代化的电商平台,致力于为用户提供无缝的购物体验。我们重新设计了整个用户界面,采用极简主义设计风格,突出产品展示,提升转化率。",
"challenge": "客户需要一个既能展示高端产品,又能提供流畅购物体验的平台。原有的网站加载缓慢,用户体验差,转化率低下。",
"solution": "我们采用了 React + Next.js 技术栈,实现了服务端渲染和静态生成,大幅提升加载速度。同时重新设计了产品展示页面,采用沉浸式大图展示,配合流畅的动画过渡。",
"client": "Forma Digital Inc.",
"duration": "3 个月"
},
"one-step": {
"overview": "One Step 是一款专注于健康习惯养成的健身应用。我们为其打造了完整的品牌视觉识别系统,包括 Logo 设计、UI 界面和营销物料。",
"challenge": "在竞争激烈的健身应用市场中,如何通过品牌设计脱颖而出,建立独特的品牌认知。",
"solution": "我们以「一步一个脚印」为核心理念,设计了简洁有力的品牌标识。采用渐变色彩和圆润的图形语言,传达健康、积极、向上的品牌调性。",
"client": "One Step Fitness",
"duration": "2 个月"
},
"nero-vision": {
"overview": "Nero Vision 是一个面向创意专业人士的作品集管理平台,帮助设计师和艺术家展示和管理他们的创作。",
"challenge": "创意人士需要一个既能完美展示作品,又能方便管理的平台。现有解决方案要么太复杂,要么展示效果不佳。",
"solution": "我们采用 Vue.js + Node.js 全栈开发,设计了直观的拖拽式作品管理界面,配合精美的展示模板,让创意人士轻松打造个人品牌。",
"client": "Nero Studio",
"duration": "4 个月"
},
"bold-moves": {
"overview": "Bold Moves 是一个展示创新建筑设计的交互式网站,通过 3D 可视化技术,让用户身临其境地体验建筑之美。",
"challenge": "如何将复杂的建筑设计以直观、吸引人的方式展示给普通用户,同时保持专业性。",
"solution": "我们使用 Three.js 实现了高质量的 3D 渲染,配合流畅的交互设计,用户可以从任意角度欣赏建筑细节。同时加入了光影效果和材质展示,提升视觉冲击力。",
"client": "Bold Moves Architecture",
"duration": "5 个月"
},
"echo-labs": {
"overview": "Echo Labs 是一家 AI 领域的科技创业公司,我们为其打造了完整的品牌视觉识别系统和企业官网。",
"challenge": "AI 领域的品牌需要既体现科技感,又要有人文温度,避免过于冷冰冰的技术感。",
"solution": "我们以「回声」为概念,设计了富有动感的品牌标识。采用深色主题配合渐变色彩,营造科技感的同时,通过圆润的图形语言增添亲和力。",
"client": "Echo Labs AI",
"duration": "3 个月"
},
"flux-api": {
"overview": "Flux API 是一个可扩展的 REST API 服务平台,提供全面的文档和开发者工具,帮助开发者快速集成。",
"challenge": "API 文档和开发者体验是技术产品的核心竞争力,如何让复杂的 API 变得易于理解和使用。",
"solution": "我们设计了交互式 API 文档,支持在线测试和代码生成。同时提供了多语言 SDK 和详细的教程,大幅降低开发者的学习成本。",
"client": "Flux Technologies",
"duration": "6 个月"
}
}
"relatedProjects": "相关项目"
}
},
"studio": {
@@ -419,97 +349,9 @@
"announcements": "公告通知"
},
"minutes": "分钟",
"items": {
"design-trends-2026": {
"title": "2026 年设计趋势展望",
"excerpt": "从极简主义的回归到大胆排版的兴起,从 3D 元素普及到 AI 辅助设计成熟,探索塑造今年数字体验的前沿趋势。"
},
"forma-digital-launch": {
"title": "Forma Digital 电商平台正式上线",
"excerpt": "我们很高兴地宣布 Forma Digital 电商平台正式上线,上线后转化率提升 45%。"
},
"studio-expansion": {
"title": "工作室扩张公告",
"excerpt": "ArcticNewOne 正在成长!我们正在扩展团队与服务能力,以更好地服务客户。"
},
"ux-research-methods": {
"title": "现代 UX 研究方法",
"excerpt": "深入解析影响我们设计决策的最新用户体验研究方法,从远程测试到行为数据分析。"
},
"bold-moves-case-study": {
"title": "Bold Moves:项目复盘",
"excerpt": "走进我们屡获殊荣的建筑可视化项目幕后,见证前沿 3D 技术如何重塑用户体验。"
},
"new-tools-integration": {
"title": "工具箱新增多款实用工具",
"excerpt": "看看我们工具箱的最新成员,覆盖设计、开发、协作,助你精简工作流、提升生产力。"
}
},
"detail": {
"shareArticle": "分享文章",
"relatedArticles": "相关文章",
"items": {
"design-trends-2026": {
"content": "2026 年,设计行业正在经历一场深刻的变革。从极简主义的回归到大胆排版的兴起,从 3D 元素的普及到 AI 辅助设计的成熟,这些趋势正在重新定义数字体验的边界。作为设计从业者,我们需要紧跟这些变化,才能为客户创造更具竞争力的作品。",
"section1Title": "极简主义的回归",
"section1Content": "在信息过载的时代,用户越来越渴望简洁、清晰的界面。2026 年的极简主义不再是简单的「少即是多」,而是通过精心的信息架构和视觉层次,在有限的空间内传达更多价值。留白不再是空白,而是一种有意为之的设计语言。",
"quote": "好的设计不是添加更多,而是去除不必要的。在 2026 年,这一点比以往任何时候都更加重要。",
"section2Title": "大胆排版与动态文字",
"section2Content": "排版正在从配角变成主角。大尺寸、高对比度的字体设计正在成为品牌表达的重要手段。动态文字效果的普及,让排版不再是静态的装饰,而是能够与用户互动的活元素。",
"section3Title": "AI 辅助设计的成熟",
"section3Content": "AI 工具正在从「替代设计师」转向「增强设计师」。智能布局建议、自动化配色方案、实时设计反馈等功能,让设计师能够专注于创意和策略,而非重复性的执行工作。"
},
"forma-digital-launch": {
"content": "经过三个月的精心打造,我们很高兴地宣布 Forma Digital 电商平台正式上线!这个项目是我们团队迄今为止最具挑战性的作品之一,也是我们技术实力和设计能力的集中体现。",
"section1Title": "项目背景",
"section1Content": "Forma Digital 是一家专注于高端家居用品的电商品牌。他们需要一个能够完美展示产品质感、提供流畅购物体验的平台。原有的网站存在加载缓慢、移动端体验差、转化率低等问题。",
"quote": "北极新一团队不仅理解我们的需求,更超越了我们的期望。新平台上线后,我们的转化率提升了 45%。",
"section2Title": "技术亮点",
"section2Content": "我们采用了 React + Next.js 技术栈,实现了服务端渲染和静态生成。通过图片懒加载、代码分割、CDN 加速等技术手段,将首屏加载时间从 4.5 秒降低到 1.2 秒。",
"section3Title": "成果展示",
"section3Content": "新平台上线后,用户停留时间增加了 60%,跳出率降低了 35%,转化率提升了 45%。客户对新平台的设计和性能都非常满意。"
},
"studio-expansion": {
"content": "随着业务的持续增长和客户需求的不断增加,我们很高兴地宣布 ArcticNewOne 工作室正式扩展!我们将增加新的团队成员,拓展服务能力,为客户提供更优质的数字化解决方案。",
"section1Title": "团队扩展",
"section1Content": "我们将新增 5 名资深设计师和 3 名高级开发工程师,覆盖前端、后端、UI/UX 等多个领域。这些新成员都拥有丰富的行业经验,曾服务于多家知名企业。",
"quote": "人才是我们最宝贵的资产。通过扩展团队,我们能够承接更多项目,同时保持一贯的高品质交付。",
"section2Title": "服务升级",
"section2Content": "除了现有的网页设计、品牌设计、程序开发等服务,我们还将新增数据可视化、AI 应用开发、AR/VR 体验设计等前沿服务。",
"section3Title": "展望未来",
"section3Content": "我们计划在未来一年内完成 50+ 项目,服务 30+ 新客户。同时,我们将继续深耕技术创新,探索更多可能性,为客户创造更大价值。"
},
"ux-research-methods": {
"content": "用户体验研究是设计决策的基础。在 2026 年,随着技术的发展和用户行为的变化,UX 研究方法也在不断演进。本文将介绍几种最有效的现代 UX 研究方法。",
"section1Title": "远程用户测试",
"section1Content": "远程用户测试已经成为 UX 研究的主流方法。通过专业的远程测试平台,我们可以在短时间内招募到全球各地的测试用户,获取更广泛的反馈。",
"quote": "远程测试不仅降低了成本,更重要的是让我们能够接触到更真实的用户场景。",
"section2Title": "行为数据分析",
"section2Content": "通过热力图、滚动深度、点击流等行为数据,我们可以客观地了解用户如何与产品互动。这些数据弥补了传统访谈和问卷的不足,提供了更真实的用户行为洞察。",
"section3Title": "AI 辅助分析",
"section3Content": "AI 工具正在帮助我们更高效地分析用户反馈。情感分析、主题聚类、趋势预测等功能,让我们能够从海量数据中快速提取有价值的洞察。"
},
"bold-moves-case-study": {
"content": "Bold Moves 是一个展示创新建筑设计的交互式网站项目。本文将深入介绍这个项目的设计思路、技术实现和最终成果。",
"section1Title": "设计理念",
"section1Content": "Bold Moves 希望通过数字方式展示建筑设计的魅力。我们决定采用 3D 可视化技术,让用户能够从任意角度欣赏建筑细节,获得沉浸式的体验。",
"quote": "我们想要的不只是一个展示网站,而是一个能够让用户「走进」建筑的数字空间。",
"section2Title": "技术挑战",
"section2Content": "高质量的 3D 渲染需要强大的计算能力,而网页端的性能有限。我们通过模型优化、LOD 技术、WebGL 渲染等手段,在保证视觉质量的同时,实现了流畅的交互体验。",
"section3Title": "最终成果",
"section3Content": "项目上线后获得了广泛好评,赢得了多个设计奖项。用户平均停留时间超过 5 分钟,远高于行业平均水平。"
},
"new-tools-integration": {
"content": "为了更好地服务客户,我们不断扩充和完善我们的工具箱。最近,我们新增了多款实用工具,涵盖设计、开发、协作等多个领域。",
"section1Title": "设计工具升级",
"section1Content": "我们引入了最新的设计协作平台,支持实时多人编辑、版本管理、设计系统集成等功能。设计师和开发者可以在同一个平台上无缝协作。",
"quote": "工欲善其事,必先利其器。好的工具能够大幅提升团队效率。",
"section2Title": "开发工具增强",
"section2Content": "新增了自动化测试框架、性能监控工具、代码质量检查等开发工具。这些工具帮助我们在开发过程中及时发现和解决问题,保证代码质量。",
"section3Title": "协作工具优化",
"section3Content": "我们升级了项目管理平台,新增了看板视图、时间追踪、资源分配等功能。项目经理可以更直观地掌控项目进度,团队成员可以更高效地协作。"
}
}
"relatedArticles": "相关文章"
}
},
"auth": {
@@ -584,7 +426,8 @@
"date": "时间",
"delivered": "已送达邮箱",
"notDelivered": "未送达(SMTP 未配置)"
}
},
"adminEntry": "进入后台管理"
},
"comments": {
"title": "评论",
+1
View File
@@ -32,6 +32,7 @@ export default defineNuxtConfig({
smtpFrom: '',
contactTo: '',
adminEmails: '',
adminInitialPassword: '',
public: {
// 客户端可见(环境变量:NUXT_PUBLIC_SITE_URL),用于 sitemap/robots/og 等绝对链接
siteUrl: '',
+144
View File
@@ -0,0 +1,144 @@
/**
* 生成 server/utils/seed.ts(一次性工具)。
*
* 从当前 i18n 文案 + 内容元数据转录出 articles/works 双语种子数据,
* 供 DB 初始化时灌入,保证站点初始内容与改造前一致。
*
* 用法: node scripts/generate-seed.mjs
*/
import { readFileSync, writeFileSync } from 'node:fs'
const zh = JSON.parse(readFileSync('i18n/locales/zh.json', 'utf8'))
const en = JSON.parse(readFileSync('i18n/locales/en.json', 'utf8'))
// ---------- 动态元数据(与原 app/data/news.ts 一致) ----------
const articleMeta = [
{ slug: 'design-trends-2026', category: 'insights', date: '2026-05-28', readTime: 5, author: 'ArcticNewOne', image: 'https://picsum.photos/id/1/800/500' },
{ slug: 'forma-digital-launch', category: 'projects', date: '2026-05-15', readTime: 3, author: 'ArcticNewOne', image: 'https://picsum.photos/id/201/800/500' },
{ slug: 'studio-expansion', category: 'announcements', date: '2026-05-10', readTime: 2, author: 'ArcticNewOne', image: 'https://picsum.photos/id/164/800/500' },
{ slug: 'ux-research-methods', category: 'insights', date: '2026-04-28', readTime: 7, author: 'ArcticNewOne', image: 'https://picsum.photos/id/180/800/500' },
{ slug: 'bold-moves-case-study', category: 'projects', date: '2026-04-20', readTime: 6, author: 'ArcticNewOne', image: 'https://picsum.photos/id/119/800/500' },
{ slug: 'new-tools-integration', category: 'announcements', date: '2026-04-12', readTime: 4, author: 'ArcticNewOne', image: 'https://picsum.photos/id/326/800/500' },
]
// ---------- 作品元数据(与原 app/data/work.ts 一致) ----------
const workMeta = [
{ slug: 'forma-digital', category: 'webDesign', year: '2026', tags: ['Web Design', 'E-commerce', 'React'], image: 'https://picsum.photos/id/201/1200/800', gallery: ['https://picsum.photos/id/201/800/600', 'https://picsum.photos/id/202/800/600', 'https://picsum.photos/id/203/800/600', 'https://picsum.photos/id/204/800/600'], url: null },
{ slug: 'one-step', category: 'branding', year: '2024', tags: ['Branding', 'Marketing', 'UI/UX'], image: 'https://picsum.photos/id/180/1200/800', gallery: ['https://picsum.photos/id/180/800/600', 'https://picsum.photos/id/181/800/600', 'https://picsum.photos/id/182/800/600', 'https://picsum.photos/id/183/800/600'], url: null },
{ slug: 'nero-vision', category: 'development', year: '2025', tags: ['Development', 'Vue.js', 'Node.js'], image: 'https://picsum.photos/id/119/1200/800', gallery: ['https://picsum.photos/id/119/800/600', 'https://picsum.photos/id/120/800/600', 'https://picsum.photos/id/121/800/600', 'https://picsum.photos/id/122/800/600'], url: null },
{ slug: 'bold-moves', category: 'webDesign', year: '2024', tags: ['Web Design', '3D', 'Three.js'], image: 'https://picsum.photos/id/164/1200/800', gallery: ['https://picsum.photos/id/164/800/600', 'https://picsum.photos/id/165/800/600', 'https://picsum.photos/id/166/800/600', 'https://picsum.photos/id/167/800/600'], url: null },
{ slug: 'echo-labs', category: 'branding', year: '2025', tags: ['Branding', 'Visual Identity', 'Corporate'], image: 'https://picsum.photos/id/101/1200/800', gallery: ['https://picsum.photos/id/101/800/600', 'https://picsum.photos/id/102/800/600', 'https://picsum.photos/id/103/800/600', 'https://picsum.photos/id/104/800/600'], url: null },
{ slug: 'flux-api', category: 'development', year: '2025', tags: ['Development', 'API', 'Python'], image: 'https://picsum.photos/id/326/1200/800', gallery: ['https://picsum.photos/id/326/800/600', 'https://picsum.photos/id/327/800/600', 'https://picsum.photos/id/328/800/600', 'https://picsum.photos/id/329/800/600'], url: null },
]
// ---------- 文章正文块(从 i18n 转录) ----------
function articleBlocks(locale, slug) {
const d = locale.detail.items[slug]
return [
{ type: 'paragraph', text: d.content },
{ type: 'heading', text: d.section1Title },
{ type: 'paragraph', text: d.section1Content },
{ type: 'quote', text: d.quote },
{ type: 'heading', text: d.section2Title },
{ type: 'paragraph', text: d.section2Content },
{ type: 'heading', text: d.section3Title },
{ type: 'paragraph', text: d.section3Content },
]
}
const articles = articleMeta.map((m) => ({
slug: m.slug,
category: m.category,
titleZh: zh.news.items[m.slug].title,
titleEn: en.news.items[m.slug].title,
excerptZh: zh.news.items[m.slug].excerpt,
excerptEn: en.news.items[m.slug].excerpt,
contentZh: articleBlocks(zh.news, m.slug),
contentEn: articleBlocks(en.news, m.slug),
image: m.image,
date: m.date,
readTime: m.readTime,
author: m.author,
published: 1,
}))
const works = workMeta.map((m) => ({
slug: m.slug,
category: m.category,
titleZh: zh.work.items[m.slug].title,
titleEn: en.work.items[m.slug].title,
descriptionZh: zh.work.items[m.slug].description,
descriptionEn: en.work.items[m.slug].description,
overviewZh: zh.work.detail.items[m.slug].overview,
overviewEn: en.work.detail.items[m.slug].overview,
challengeZh: zh.work.detail.items[m.slug].challenge,
challengeEn: en.work.detail.items[m.slug].challenge,
solutionZh: zh.work.detail.items[m.slug].solution,
solutionEn: en.work.detail.items[m.slug].solution,
clientZh: zh.work.detail.items[m.slug].client,
clientEn: en.work.detail.items[m.slug].client,
durationZh: zh.work.detail.items[m.slug].duration,
durationEn: en.work.detail.items[m.slug].duration,
year: m.year,
tags: m.tags,
image: m.image,
gallery: m.gallery,
url: m.url,
published: 1,
}))
const out = `/**
* 种子数据(由 scripts/generate-seed.mjs 生成,勿手改)。
* 站点初始内容:6 篇动态 + 6 个作品(中英双语)。
* DB 初始化(migrate)时若对应表为空则自动灌入。
*/
import type { ArticleBlock } from './db'
export interface ArticleSeed {
slug: string
category: 'insights' | 'projects' | 'announcements'
titleZh: string
titleEn: string
excerptZh: string
excerptEn: string
contentZh: ArticleBlock[]
contentEn: ArticleBlock[]
image: string
date: string
readTime: number
author: string
published: number
}
export interface WorkSeed {
slug: string
category: 'webDesign' | 'branding' | 'development'
titleZh: string
titleEn: string
descriptionZh: string
descriptionEn: string
overviewZh: string
overviewEn: string
challengeZh: string
challengeEn: string
solutionZh: string
solutionEn: string
clientZh: string
clientEn: string
durationZh: string
durationEn: string
year: string
tags: string[]
image: string
gallery: string[]
url: string | null
published: number
}
export const articlesSeed: ArticleSeed[] = ${JSON.stringify(articles, null, 2)}
export const worksSeed: WorkSeed[] = ${JSON.stringify(works, null, 2)}
`
writeFileSync('server/utils/seed.ts', out)
console.log(`seed.ts generated: ${articles.length} articles, ${works.length} works`)
-30
View File
@@ -1,30 +0,0 @@
import { requireAdmin } from '../../utils/auth'
import { getDb } from '../../utils/db'
/**
* 管理员收件箱:联系留言 + 邮箱订阅(仅 admin 可见)
*/
export default defineEventHandler((event) => {
requireAdmin(event)
const db = getDb()
const contacts = db
.prepare(
'SELECT id, name, email, subject, message, delivered, created_at AS createdAt FROM contacts ORDER BY created_at DESC',
)
.all() as Array<{
id: number
name: string
email: string
subject: string
message: string
delivered: number
createdAt: string
}>
const subscribers = db
.prepare('SELECT id, email, created_at AS createdAt FROM subscribers ORDER BY created_at DESC')
.all() as Array<{ id: number; email: string; createdAt: string }>
return { contacts, subscribers }
})
+10
View File
@@ -0,0 +1,10 @@
import { requireAdmin } from '../../utils/auth'
import { listArticles } from '../../utils/content'
/**
* 后台动态列表(含未发布)
*/
export default defineEventHandler((event) => {
requireAdmin(event)
return { articles: listArticles({ publishedOnly: false }) }
})
+52
View File
@@ -0,0 +1,52 @@
import { readBody, createError } from 'h3'
import { requireAdmin } from '../../utils/auth'
import { getDb } from '../../utils/db'
import { getArticleBySlug } from '../../utils/content'
import { normalizeSlug, isValidSlug, isValidArticleCategory, normalizeBlocks } from '../../utils/validateContent'
/**
* 后台新增动态
*/
export default defineEventHandler(async (event) => {
requireAdmin(event)
const body = await readBody(event)
const db = getDb()
const slug = normalizeSlug(body?.slug)
if (!isValidSlug(slug)) {
throw createError({ statusCode: 400, message: 'slug 需为 2-64 位小写字母/数字/中划线', data: { code: 'VALIDATION_ERROR' } })
}
if (!isValidArticleCategory(body?.category)) {
throw createError({ statusCode: 400, message: '分类不合法', data: { code: 'VALIDATION_ERROR' } })
}
const titleZh = String(body?.titleZh ?? '').trim()
const titleEn = String(body?.titleEn ?? '').trim()
if (!titleZh || !titleEn) {
throw createError({ statusCode: 400, message: '中英文标题不能为空', data: { code: 'VALIDATION_ERROR' } })
}
if (getArticleBySlug(slug, { publishedOnly: false })) {
throw createError({ statusCode: 400, message: 'slug 已存在', data: { code: 'SLUG_TAKEN' } })
}
db.prepare(
`INSERT INTO articles
(slug, category, title_zh, title_en, excerpt_zh, excerpt_en, content_zh, content_en, image, date, read_time, author, published, updated_at)
VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, datetime('now'))`,
).run(
slug,
body.category,
titleZh,
titleEn,
String(body?.excerptZh ?? ''),
String(body?.excerptEn ?? ''),
JSON.stringify(normalizeBlocks(body?.contentZh)),
JSON.stringify(normalizeBlocks(body?.contentEn)),
body?.image ? String(body.image).trim() : null,
body?.date ? String(body.date).trim() : null,
Number(body?.readTime) || 5,
String(body?.author ?? 'ArcticNewOne').trim() || 'ArcticNewOne',
body?.published ? 1 : 0,
)
return { ok: true, article: getArticleBySlug(slug, { publishedOnly: false }) }
})
+25
View File
@@ -0,0 +1,25 @@
import { createError, getRouterParam } from 'h3'
import { requireAdmin } from '../../../utils/auth'
import { getDb } from '../../../utils/db'
/**
* 后台删除动态(连带删除其评论)
*/
export default defineEventHandler((event) => {
requireAdmin(event)
const id = Number(getRouterParam(event, 'id'))
const db = getDb()
const row = db.prepare('SELECT slug FROM articles WHERE id = ?').get(id) as { slug: string } | undefined
if (!row) {
throw createError({ statusCode: 404, message: '动态不存在', data: { code: 'NOT_FOUND' } })
}
const tx = db.transaction(() => {
db.prepare('DELETE FROM comments WHERE news_slug = ?').run(row.slug)
db.prepare('DELETE FROM articles WHERE id = ?').run(id)
})
tx()
return { ok: true }
})
+82
View File
@@ -0,0 +1,82 @@
import { readBody, createError, getRouterParam } from 'h3'
import { requireAdmin } from '../../../utils/auth'
import { getDb } from '../../../utils/db'
import { getArticleBySlug } from '../../../utils/content'
import { normalizeSlug, isValidSlug, isValidArticleCategory, normalizeBlocks } from '../../../utils/validateContent'
/**
* 后台更新动态(部分字段)
*/
export default defineEventHandler(async (event) => {
requireAdmin(event)
const id = Number(getRouterParam(event, 'id'))
const body = await readBody(event)
const db = getDb()
const existing = db.prepare('SELECT slug FROM articles WHERE id = ?').get(id) as { slug: string } | undefined
if (!existing) {
throw createError({ statusCode: 404, message: '动态不存在', data: { code: 'NOT_FOUND' } })
}
const sets: string[] = []
const params: unknown[] = []
if (body?.slug !== undefined) {
const slug = normalizeSlug(body.slug)
if (!isValidSlug(slug)) {
throw createError({ statusCode: 400, message: 'slug 需为 2-64 位小写字母/数字/中划线', data: { code: 'VALIDATION_ERROR' } })
}
const taken = db.prepare('SELECT id FROM articles WHERE slug = ? AND id != ?').get(slug, id)
if (taken) {
throw createError({ statusCode: 400, message: 'slug 已存在', data: { code: 'SLUG_TAKEN' } })
}
sets.push('slug = ?'); params.push(slug)
}
if (body?.category !== undefined) {
if (!isValidArticleCategory(body.category)) {
throw createError({ statusCode: 400, message: '分类不合法', data: { code: 'VALIDATION_ERROR' } })
}
sets.push('category = ?'); params.push(body.category)
}
for (const field of ['titleZh', 'titleEn', 'excerptZh', 'excerptEn', 'image', 'date', 'author'] as const) {
if (body?.[field] !== undefined) {
if (field === 'titleZh' || field === 'titleEn') {
if (!String(body[field]).trim()) {
throw createError({ statusCode: 400, message: '中英文标题不能为空', data: { code: 'VALIDATION_ERROR' } })
}
}
sets.push(fieldToCol(field) + ' = ?'); params.push(String(body[field]).trim())
}
}
if (body?.readTime !== undefined) {
sets.push('read_time = ?'); params.push(Number(body.readTime) || 5)
}
if (body?.published !== undefined) {
sets.push('published = ?'); params.push(body.published ? 1 : 0)
}
if (body?.contentZh !== undefined) {
sets.push('content_zh = ?'); params.push(JSON.stringify(normalizeBlocks(body.contentZh)))
}
if (body?.contentEn !== undefined) {
sets.push('content_en = ?'); params.push(JSON.stringify(normalizeBlocks(body.contentEn)))
}
if (sets.length === 0) {
throw createError({ statusCode: 400, message: '没有可更新的字段', data: { code: 'VALIDATION_ERROR' } })
}
sets.push("updated_at = datetime('now')")
db.prepare(`UPDATE articles SET ${sets.join(', ')} WHERE id = ?`).run(...params, id)
const row = db.prepare('SELECT slug FROM articles WHERE id = ?').get(id) as { slug: string }
return { ok: true, article: getArticleBySlug(row.slug, { publishedOnly: false }) }
})
function fieldToCol(field: string): string {
const map: Record<string, string> = {
titleZh: 'title_zh', titleEn: 'title_en',
excerptZh: 'excerpt_zh', excerptEn: 'excerpt_en',
image: 'image', date: 'date', author: 'author',
}
return map[field]
}
+18
View File
@@ -0,0 +1,18 @@
import { requireAdmin } from '../../utils/auth'
import { getDb } from '../../utils/db'
/**
* 后台全站评论列表(含文章 slug 与作者)
*/
export default defineEventHandler((event) => {
requireAdmin(event)
const comments = getDb()
.prepare(
`SELECT c.id, c.news_slug AS newsSlug, c.content, c.created_at AS createdAt, u.username
FROM comments c
JOIN users u ON u.id = c.user_id
ORDER BY c.created_at DESC`,
)
.all()
return { comments }
})
+18
View File
@@ -0,0 +1,18 @@
import { createError, getRouterParam } from 'h3'
import { requireAdmin } from '../../../utils/auth'
import { getDb } from '../../../utils/db'
/**
* 后台删除评论
*/
export default defineEventHandler((event) => {
requireAdmin(event)
const id = Number(getRouterParam(event, 'id'))
const db = getDb()
const target = db.prepare('SELECT id FROM comments WHERE id = ?').get(id)
if (!target) {
throw createError({ statusCode: 404, message: '评论不存在', data: { code: 'NOT_FOUND' } })
}
db.prepare('DELETE FROM comments WHERE id = ?').run(id)
return { ok: true }
})
+13
View File
@@ -0,0 +1,13 @@
import { requireAdmin } from '../../utils/auth'
import { getDb } from '../../utils/db'
/**
* 后台联系消息列表
*/
export default defineEventHandler((event) => {
requireAdmin(event)
const contacts = getDb()
.prepare('SELECT id, name, email, subject, message, delivered, created_at AS createdAt FROM contacts ORDER BY created_at DESC')
.all()
return { contacts }
})
+18
View File
@@ -0,0 +1,18 @@
import { createError, getRouterParam } from 'h3'
import { requireAdmin } from '../../../utils/auth'
import { getDb } from '../../../utils/db'
/**
* 后台删除联系消息
*/
export default defineEventHandler((event) => {
requireAdmin(event)
const id = Number(getRouterParam(event, 'id'))
const db = getDb()
const target = db.prepare('SELECT id FROM contacts WHERE id = ?').get(id)
if (!target) {
throw createError({ statusCode: 404, message: '消息不存在', data: { code: 'NOT_FOUND' } })
}
db.prepare('DELETE FROM contacts WHERE id = ?').run(id)
return { ok: true }
})
+20
View File
@@ -0,0 +1,20 @@
import { requireAdmin } from '../../utils/auth'
import { getDb } from '../../utils/db'
import { getContentStats } from '../../utils/content'
/**
* 后台 Dashboard 统计
*/
export default defineEventHandler((event) => {
requireAdmin(event)
const db = getDb()
const one = (sql: string) => (db.prepare(sql).get() as { c: number }).c
return {
...getContentStats(),
users: one('SELECT COUNT(*) AS c FROM users'),
comments: one('SELECT COUNT(*) AS c FROM comments'),
contacts: one('SELECT COUNT(*) AS c FROM contacts'),
subscribers: one('SELECT COUNT(*) AS c FROM subscribers'),
favorites: one('SELECT COUNT(*) AS c FROM favorites'),
}
})
+13
View File
@@ -0,0 +1,13 @@
import { requireAdmin } from '../../utils/auth'
import { getDb } from '../../utils/db'
/**
* 后台订阅列表
*/
export default defineEventHandler((event) => {
requireAdmin(event)
const subscribers = getDb()
.prepare('SELECT id, email, created_at AS createdAt FROM subscribers ORDER BY created_at DESC')
.all()
return { subscribers }
})
@@ -0,0 +1,18 @@
import { createError, getRouterParam } from 'h3'
import { requireAdmin } from '../../../utils/auth'
import { getDb } from '../../../utils/db'
/**
* 后台删除订阅
*/
export default defineEventHandler((event) => {
requireAdmin(event)
const id = Number(getRouterParam(event, 'id'))
const db = getDb()
const target = db.prepare('SELECT id FROM subscribers WHERE id = ?').get(id)
if (!target) {
throw createError({ statusCode: 404, message: '订阅不存在', data: { code: 'NOT_FOUND' } })
}
db.prepare('DELETE FROM subscribers WHERE id = ?').run(id)
return { ok: true }
})
@@ -0,0 +1,23 @@
import { requireAdmin } from '../../../utils/auth'
import { getDb } from '../../../utils/db'
/**
* 导出订阅 CSV(UTF-8 BOM,兼容 Excel)
*/
export default defineEventHandler((event) => {
requireAdmin(event)
const rows = getDb()
.prepare('SELECT email, created_at AS createdAt FROM subscribers ORDER BY created_at DESC')
.all() as Array<{ email: string; createdAt: string }>
const escape = (v: string) => `"${String(v).replace(/"/g, '""')}"`
const lines = ['email,created_at', ...rows.map((r) => `${escape(r.email)},${escape(r.createdAt)}`)]
const csv = '' + lines.join('\n')
return new Response(csv, {
headers: {
'Content-Type': 'text/csv; charset=utf-8',
'Content-Disposition': `attachment; filename="subscribers-${new Date().toISOString().slice(0, 10)}.csv"`,
},
})
})
+46
View File
@@ -0,0 +1,46 @@
import { readMultipartFormData, createError } from 'h3'
import { writeFileSync, mkdirSync } from 'node:fs'
import { dirname, join } from 'node:path'
import { randomBytes } from 'node:crypto'
import { requireAdmin } from '../../utils/auth'
import { getConfig } from '../../utils/config'
const MAX_SIZE = 8 * 1024 * 1024 // 8MB
const EXT_BY_TYPE: Record<string, string> = {
'image/png': 'png',
'image/jpeg': 'jpg',
'image/gif': 'gif',
'image/webp': 'webp',
'image/svg+xml': 'svg',
'image/avif': 'avif',
}
/**
* 后台图片上传 -> 保存到 PVC 的 uploads 目录(/data/uploads),
* 通过 /uploads/<name> 对外提供。
*/
export default defineEventHandler(async (event) => {
requireAdmin(event)
const parts = await readMultipartFormData(event)
const file = parts?.find((p) => p.name === 'file' && p.data?.length)
if (!file || !file.data) {
throw createError({ statusCode: 400, message: '缺少文件', data: { code: 'VALIDATION_ERROR' } })
}
const type = file.type || 'application/octet-stream'
const ext = EXT_BY_TYPE[type]
if (!ext) {
throw createError({ statusCode: 400, message: '仅支持图片(png/jpg/gif/webp/svg/avif)', data: { code: 'VALIDATION_ERROR' } })
}
if (file.data.length > MAX_SIZE) {
throw createError({ statusCode: 400, message: '文件过大(上限 8MB)', data: { code: 'VALIDATION_ERROR' } })
}
const name = `${Date.now()}-${randomBytes(6).toString('hex')}.${ext}`
const dir = join(dirname(getConfig().dbPath), 'uploads')
mkdirSync(dir, { recursive: true })
writeFileSync(join(dir, name), file.data)
return { ok: true, url: `/uploads/${name}` }
})
+13
View File
@@ -0,0 +1,13 @@
import { requireAdmin } from '../../utils/auth'
import { getDb } from '../../utils/db'
/**
* 后台用户列表
*/
export default defineEventHandler((event) => {
requireAdmin(event)
const users = getDb()
.prepare('SELECT id, username, email, phone, role, created_at AS createdAt FROM users ORDER BY id DESC')
.all()
return { users }
})
+22
View File
@@ -0,0 +1,22 @@
import { createError, getRouterParam } from 'h3'
import { requireAdmin } from '../../../utils/auth'
import { getDb } from '../../../utils/db'
/**
* 后台删除用户(连带删除其会话/评论/收藏)
*/
export default defineEventHandler((event) => {
const me = requireAdmin(event)
const id = Number(getRouterParam(event, 'id'))
const db = getDb()
if (me.id === id) {
throw createError({ statusCode: 400, message: '不能删除自己的账号', data: { code: 'VALIDATION_ERROR' } })
}
const target = db.prepare('SELECT id FROM users WHERE id = ?').get(id)
if (!target) {
throw createError({ statusCode: 404, message: '用户不存在', data: { code: 'NOT_FOUND' } })
}
db.prepare('DELETE FROM users WHERE id = ?').run(id) // 外键级联:sessions/comments/favorites
return { ok: true }
})
+28
View File
@@ -0,0 +1,28 @@
import { readBody, createError, getRouterParam } from 'h3'
import { requireAdmin } from '../../../utils/auth'
import { getDb } from '../../../utils/db'
/**
* 后台更新用户(角色切换)
*/
export default defineEventHandler(async (event) => {
const me = requireAdmin(event)
const id = Number(getRouterParam(event, 'id'))
const body = await readBody(event)
const db = getDb()
if (me.id === id) {
throw createError({ statusCode: 400, message: '不能修改自己的角色', data: { code: 'VALIDATION_ERROR' } })
}
const target = db.prepare('SELECT id FROM users WHERE id = ?').get(id)
if (!target) {
throw createError({ statusCode: 404, message: '用户不存在', data: { code: 'NOT_FOUND' } })
}
if (body?.role !== undefined) {
if (!['user', 'admin'].includes(body.role)) {
throw createError({ statusCode: 400, message: '角色不合法', data: { code: 'VALIDATION_ERROR' } })
}
db.prepare('UPDATE users SET role = ? WHERE id = ?').run(body.role, id)
}
return { ok: true }
})
+10
View File
@@ -0,0 +1,10 @@
import { requireAdmin } from '../../utils/auth'
import { listWorks } from '../../utils/content'
/**
* 后台作品列表(含未发布)
*/
export default defineEventHandler((event) => {
requireAdmin(event)
return { works: listWorks({ publishedOnly: false }) }
})
+69
View File
@@ -0,0 +1,69 @@
import { readBody, createError } from 'h3'
import { requireAdmin } from '../../utils/auth'
import { getDb } from '../../utils/db'
import { getWorkBySlug } from '../../utils/content'
import {
normalizeSlug,
isValidSlug,
isValidWorkCategory,
normalizeTags,
normalizeGallery,
} from '../../utils/validateContent'
/**
* 后台新增作品
*/
export default defineEventHandler(async (event) => {
requireAdmin(event)
const body = await readBody(event)
const db = getDb()
const slug = normalizeSlug(body?.slug)
if (!isValidSlug(slug)) {
throw createError({ statusCode: 400, message: 'slug 需为 2-64 位小写字母/数字/中划线', data: { code: 'VALIDATION_ERROR' } })
}
if (!isValidWorkCategory(body?.category)) {
throw createError({ statusCode: 400, message: '分类不合法', data: { code: 'VALIDATION_ERROR' } })
}
const titleZh = String(body?.titleZh ?? '').trim()
const titleEn = String(body?.titleEn ?? '').trim()
if (!titleZh || !titleEn) {
throw createError({ statusCode: 400, message: '中英文标题不能为空', data: { code: 'VALIDATION_ERROR' } })
}
if (getWorkBySlug(slug, { publishedOnly: false })) {
throw createError({ statusCode: 400, message: 'slug 已存在', data: { code: 'SLUG_TAKEN' } })
}
db.prepare(
`INSERT INTO works
(slug, category, title_zh, title_en, description_zh, description_en,
overview_zh, overview_en, challenge_zh, challenge_en, solution_zh, solution_en,
client_zh, client_en, duration_zh, duration_en, year, tags, image, gallery, url, published, updated_at)
VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, datetime('now'))`,
).run(
slug,
body.category,
titleZh,
titleEn,
String(body?.descriptionZh ?? ''),
String(body?.descriptionEn ?? ''),
String(body?.overviewZh ?? ''),
String(body?.overviewEn ?? ''),
String(body?.challengeZh ?? ''),
String(body?.challengeEn ?? ''),
String(body?.solutionZh ?? ''),
String(body?.solutionEn ?? ''),
String(body?.clientZh ?? ''),
String(body?.clientEn ?? ''),
String(body?.durationZh ?? ''),
String(body?.durationEn ?? ''),
String(body?.year ?? ''),
JSON.stringify(normalizeTags(body?.tags)),
body?.image ? String(body.image).trim() : null,
JSON.stringify(normalizeGallery(body?.gallery)),
body?.url ? String(body.url).trim() : null,
body?.published ? 1 : 0,
)
return { ok: true, work: getWorkBySlug(slug, { publishedOnly: false }) }
})
+25
View File
@@ -0,0 +1,25 @@
import { createError, getRouterParam } from 'h3'
import { requireAdmin } from '../../../utils/auth'
import { getDb } from '../../../utils/db'
/**
* 后台删除作品(连带清理用户收藏)
*/
export default defineEventHandler((event) => {
requireAdmin(event)
const id = Number(getRouterParam(event, 'id'))
const db = getDb()
const row = db.prepare('SELECT slug FROM works WHERE id = ?').get(id) as { slug: string } | undefined
if (!row) {
throw createError({ statusCode: 404, message: '作品不存在', data: { code: 'NOT_FOUND' } })
}
const tx = db.transaction(() => {
db.prepare('DELETE FROM favorites WHERE work_slug = ?').run(row.slug)
db.prepare('DELETE FROM works WHERE id = ?').run(id)
})
tx()
return { ok: true }
})
+95
View File
@@ -0,0 +1,95 @@
import { readBody, createError, getRouterParam } from 'h3'
import { requireAdmin } from '../../../utils/auth'
import { getDb } from '../../../utils/db'
import { getWorkBySlug } from '../../../utils/content'
import {
normalizeSlug,
isValidSlug,
isValidWorkCategory,
normalizeTags,
normalizeGallery,
} from '../../../utils/validateContent'
/**
* 后台更新作品(部分字段)
*/
export default defineEventHandler(async (event) => {
requireAdmin(event)
const id = Number(getRouterParam(event, 'id'))
const body = await readBody(event)
const db = getDb()
const existing = db.prepare('SELECT slug FROM works WHERE id = ?').get(id) as { slug: string } | undefined
if (!existing) {
throw createError({ statusCode: 404, message: '作品不存在', data: { code: 'NOT_FOUND' } })
}
const sets: string[] = []
const params: unknown[] = []
if (body?.slug !== undefined) {
const slug = normalizeSlug(body.slug)
if (!isValidSlug(slug)) {
throw createError({ statusCode: 400, message: 'slug 需为 2-64 位小写字母/数字/中划线', data: { code: 'VALIDATION_ERROR' } })
}
const taken = db.prepare('SELECT id FROM works WHERE slug = ? AND id != ?').get(slug, id)
if (taken) {
throw createError({ statusCode: 400, message: 'slug 已存在', data: { code: 'SLUG_TAKEN' } })
}
sets.push('slug = ?'); params.push(slug)
}
if (body?.category !== undefined) {
if (!isValidWorkCategory(body.category)) {
throw createError({ statusCode: 400, message: '分类不合法', data: { code: 'VALIDATION_ERROR' } })
}
sets.push('category = ?'); params.push(body.category)
}
for (const field of [
'titleZh', 'titleEn', 'descriptionZh', 'descriptionEn',
'overviewZh', 'overviewEn', 'challengeZh', 'challengeEn',
'solutionZh', 'solutionEn', 'clientZh', 'clientEn',
'durationZh', 'durationEn', 'year', 'image', 'url',
] as const) {
if (body?.[field] !== undefined) {
if (field === 'titleZh' || field === 'titleEn') {
if (!String(body[field]).trim()) {
throw createError({ statusCode: 400, message: '中英文标题不能为空', data: { code: 'VALIDATION_ERROR' } })
}
}
sets.push(fieldToCol(field) + ' = ?'); params.push(String(body[field]).trim())
}
}
if (body?.tags !== undefined) {
sets.push('tags = ?'); params.push(JSON.stringify(normalizeTags(body.tags)))
}
if (body?.gallery !== undefined) {
sets.push('gallery = ?'); params.push(JSON.stringify(normalizeGallery(body.gallery)))
}
if (body?.published !== undefined) {
sets.push('published = ?'); params.push(body.published ? 1 : 0)
}
if (sets.length === 0) {
throw createError({ statusCode: 400, message: '没有可更新的字段', data: { code: 'VALIDATION_ERROR' } })
}
sets.push("updated_at = datetime('now')")
db.prepare(`UPDATE works SET ${sets.join(', ')} WHERE id = ?`).run(...params, id)
const row = db.prepare('SELECT slug FROM works WHERE id = ?').get(id) as { slug: string }
return { ok: true, work: getWorkBySlug(row.slug, { publishedOnly: false }) }
})
function fieldToCol(field: string): string {
const map: Record<string, string> = {
titleZh: 'title_zh', titleEn: 'title_en',
descriptionZh: 'description_zh', descriptionEn: 'description_en',
overviewZh: 'overview_zh', overviewEn: 'overview_en',
challengeZh: 'challenge_zh', challengeEn: 'challenge_en',
solutionZh: 'solution_zh', solutionEn: 'solution_en',
clientZh: 'client_zh', clientEn: 'client_en',
durationZh: 'duration_zh', durationEn: 'duration_en',
year: 'year', image: 'image', url: 'url',
}
return map[field]
}
+5 -2
View File
@@ -1,6 +1,7 @@
import { readBody, createError } from 'h3'
import { getDb } from '../../utils/db'
import { hashPassword, createSession, setSessionCookie, toPublicUser, type UserRow } from '../../utils/auth'
import { isAdminEmail } from '../../utils/config'
import { isValidUsername, isValidEmail, isValidPassword, isValidPhone } from '../../utils/validation'
/**
@@ -39,9 +40,11 @@ export default defineEventHandler(async (event) => {
}
const passwordHash = await hashPassword(password)
// 管理员邮箱白名单命中者自动授予 admin 角色(后续可后台切换)
const role = isAdminEmail(email) ? 'admin' : 'user'
const info = db
.prepare('INSERT INTO users (username, email, phone, password_hash) VALUES (?, ?, ?, ?)')
.run(username, email, phone || null, passwordHash)
.prepare('INSERT INTO users (username, email, phone, password_hash, role) VALUES (?, ?, ?, ?, ?)')
.run(username, email, phone || null, passwordHash, role)
const user = db
.prepare('SELECT id, username, email, phone, role, created_at FROM users WHERE id = ?')
+2 -2
View File
@@ -1,6 +1,6 @@
import { getQuery, createError } from 'h3'
import { getDb } from '../utils/db'
import { newsBySlug } from '../../app/data/news'
import { getArticleBySlug } from '../utils/content'
/**
* 指定新闻的评论列表(公开)
@@ -9,7 +9,7 @@ export default defineEventHandler((event) => {
const query = getQuery(event)
const newsSlug = String(query?.newsSlug ?? '')
if (!newsBySlug[newsSlug]) {
if (!getArticleBySlug(newsSlug, { publishedOnly: false })) {
throw createError({ statusCode: 404, message: '文章不存在', data: { code: 'NOT_FOUND' } })
}
+2 -2
View File
@@ -1,7 +1,7 @@
import { readBody, createError } from 'h3'
import { requireUser } from '../utils/auth'
import { getDb } from '../utils/db'
import { newsBySlug } from '../../app/data/news'
import { getArticleBySlug } from '../utils/content'
/**
* 发表评论(需登录)
@@ -12,7 +12,7 @@ export default defineEventHandler(async (event) => {
const newsSlug = String(body?.newsSlug ?? '')
const content = String(body?.content ?? '').trim()
if (!newsBySlug[newsSlug]) {
if (!getArticleBySlug(newsSlug, { publishedOnly: false })) {
throw createError({ statusCode: 400, message: '未知的文章', data: { code: 'VALIDATION_ERROR' } })
}
if (!content) {
+2 -2
View File
@@ -1,7 +1,7 @@
import { readBody, createError } from 'h3'
import { requireUser } from '../utils/auth'
import { getDb } from '../utils/db'
import { workBySlug } from '../../app/data/work'
import { getWorkBySlug } from '../utils/content'
/**
* 收藏作品(幂等)
@@ -11,7 +11,7 @@ export default defineEventHandler(async (event) => {
const body = await readBody(event)
const workSlug = String(body?.workSlug ?? '')
if (!workBySlug[workSlug]) {
if (!getWorkBySlug(workSlug, { publishedOnly: false })) {
throw createError({ statusCode: 400, message: '未知的作品', data: { code: 'VALIDATION_ERROR' } })
}
+8
View File
@@ -0,0 +1,8 @@
import { listArticles } from '../utils/content'
/**
* 动态列表(前台,仅已发布)
*/
export default defineEventHandler(() => {
return { articles: listArticles({ publishedOnly: true }) }
})
+14
View File
@@ -0,0 +1,14 @@
import { createError } from 'h3'
import { getArticleBySlug } from '../../utils/content'
/**
* 动态详情(前台,仅已发布)
*/
export default defineEventHandler((event) => {
const slug = getRouterParam(event, 'slug') ?? ''
const article = getArticleBySlug(slug, { publishedOnly: true })
if (!article) {
throw createError({ statusCode: 404, message: '文章不存在', data: { code: 'NOT_FOUND' } })
}
return { article }
})
+8
View File
@@ -0,0 +1,8 @@
import { listWorks } from '../utils/content'
/**
* 作品列表(前台,仅已发布)
*/
export default defineEventHandler(() => {
return { works: listWorks({ publishedOnly: true }) }
})
+14
View File
@@ -0,0 +1,14 @@
import { createError } from 'h3'
import { getWorkBySlug } from '../../utils/content'
/**
* 作品详情(前台,仅已发布)
*/
export default defineEventHandler((event) => {
const slug = getRouterParam(event, 'slug') ?? ''
const work = getWorkBySlug(slug, { publishedOnly: true })
if (!work) {
throw createError({ statusCode: 404, message: '作品不存在', data: { code: 'NOT_FOUND' } })
}
return { work }
})
+6 -5
View File
@@ -1,13 +1,14 @@
import { getConfig } from '../utils/config'
import { newsItems } from '../../app/data/news'
import { workItems } from '../../app/data/work'
import { listArticles, listWorks } from '../utils/content'
/**
* 动态站点地图 /sitemap.xml。
* 路由与数据均来自单一事实源(app/data/*),内容更新无需手工同步。
* 内容来自数据库(后台可维护),路由自动跟随。
*/
export default defineEventHandler(() => {
const { siteUrl } = getConfig()
const articles = listArticles({ publishedOnly: true })
const works = listWorks({ publishedOnly: true })
const urls: Array<{ loc: string; changefreq: string; priority: string }> = [
{ loc: '/', changefreq: 'weekly', priority: '1.0' },
@@ -18,10 +19,10 @@ export default defineEventHandler(() => {
{ loc: '/contact', changefreq: 'monthly', priority: '0.6' },
]
for (const item of workItems) {
for (const item of works) {
urls.push({ loc: `/work/${item.slug}`, changefreq: 'monthly', priority: '0.7' })
}
for (const item of newsItems) {
for (const item of articles) {
urls.push({ loc: `/news/${item.slug}`, changefreq: 'weekly', priority: '0.7' })
}
+40
View File
@@ -0,0 +1,40 @@
import { createError } from 'h3'
import { readFileSync, existsSync } from 'node:fs'
import { join, dirname, normalize } from 'node:path'
import { getConfig } from '../../utils/config'
const MIME: Record<string, string> = {
png: 'image/png',
jpg: 'image/jpeg',
jpeg: 'image/jpeg',
gif: 'image/gif',
webp: 'image/webp',
svg: 'image/svg+xml',
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))
// 防目录穿越
if (!filePath.startsWith(base + '/') && filePath !== 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',
'Cache-Control': 'public, max-age=31536000, immutable',
},
})
})
+4 -10
View File
@@ -3,7 +3,6 @@ import { promisify } from 'node:util'
import { createError, getCookie, setCookie, deleteCookie } from 'h3'
import type { H3Event } from 'h3'
import { getDb } from './db'
import { getConfig, isAdminEmail } from './config'
const scryptAsync = promisify(scrypt) as (
password: string,
@@ -54,7 +53,7 @@ export function destroySession(token: string): void {
getDb().prepare('DELETE FROM sessions WHERE token = ?').run(token)
}
/** 根据 token 返回有效用户(过期会话返回 null);role 随 ADMIN_EMAILS 实时判定 */
/** 根据 token 返回有效用户(过期会话返回 null);role 以数据库存储为准(后台可切换) */
export function getSessionUser(token: string | null): UserRow | null {
if (!token) return null
const row = getDb()
@@ -65,10 +64,7 @@ export function getSessionUser(token: string | null): UserRow | null {
WHERE s.token = ? AND s.expires_at > datetime('now')`,
)
.get(token) as UserRow | undefined
if (!row) return null
// 管理员角色以 ADMIN_EMAILS 配置为准(改配置即生效),数据库 role 仅作冗余存储
row.role = isAdminEmail(row.email) ? 'admin' : 'user'
return row
return row ?? null
}
/** 从请求 Cookie 中解析当前登录用户 */
@@ -112,7 +108,7 @@ export function clearSessionCookie(event: H3Event): void {
deleteCookie(event, SESSION_COOKIE, { path: '/' })
}
/** 返回给前端的脱敏用户对象(含 admin 角色,供个人中心展示) */
/** 返回给前端的脱敏用户对象(含 admin 角色,供个人中心/后台展示) */
export function toPublicUser(user: UserRow): {
id: number
username: string
@@ -121,14 +117,12 @@ export function toPublicUser(user: UserRow): {
role: 'user' | 'admin'
createdAt: string
} {
// 管理员角色跟随 ADMIN_EMAILS 配置实时判定,保证改配置即生效
const role: 'user' | 'admin' = isAdminEmail(user.email) ? 'admin' : 'user'
return {
id: user.id,
username: user.username,
email: user.email,
phone: user.phone,
role,
role: user.role,
createdAt: user.created_at,
}
}
+3
View File
@@ -26,6 +26,8 @@ export interface AppConfig {
}
contactTo: string
adminEmails: string[]
/** 首次初始化时预置 admin 账号的密码(NUXT_ADMIN_INITIAL_PASSWORD),未设则不预置 */
adminInitialPassword: string
siteUrl: string
}
@@ -46,6 +48,7 @@ export function getConfig(): AppConfig {
.split(',')
.map((s) => s.trim().toLowerCase())
.filter(Boolean),
adminInitialPassword: String((c as any).adminInitialPassword || ''),
siteUrl: String((c.public as { siteUrl?: string })?.siteUrl || '').replace(/\/$/, ''),
}
}
+166
View File
@@ -0,0 +1,166 @@
import { getDb, type ArticleBlock } from './db'
/**
* 内容读取层(动态/作品)。
* 统一负责 DB 行 -> 业务对象(解析 content/tags/gallery 的 JSON),
* 供前台内容 API、后台管理 API、sitemap 共用。
*/
export interface Article {
id: number
slug: string
category: 'insights' | 'projects' | 'announcements'
titleZh: string
titleEn: string
excerptZh: string
excerptEn: string
contentZh: ArticleBlock[]
contentEn: ArticleBlock[]
image: string | null
date: string | null
readTime: number
author: string
published: number
createdAt: string
updatedAt: string
}
export interface Work {
id: number
slug: string
category: 'webDesign' | 'branding' | 'development'
titleZh: string
titleEn: string
descriptionZh: string
descriptionEn: string
overviewZh: string
overviewEn: string
challengeZh: string
challengeEn: string
solutionZh: string
solutionEn: string
clientZh: string
clientEn: string
durationZh: string
durationEn: string
year: string
tags: string[]
image: string | null
gallery: string[]
url: string | null
published: number
createdAt: string
updatedAt: string
}
const parseJson = <T>(value: string | null, fallback: T): T => {
if (!value) return fallback
try {
return JSON.parse(value) as T
} catch {
return fallback
}
}
function rowToArticle(row: Record<string, unknown>): Article {
return {
id: Number(row.id),
slug: String(row.slug),
category: row.category as Article['category'],
titleZh: String(row.title_zh),
titleEn: String(row.title_en),
excerptZh: String(row.excerpt_zh),
excerptEn: String(row.excerpt_en),
contentZh: parseJson<ArticleBlock[]>(String(row.content_zh ?? ''), []),
contentEn: parseJson<ArticleBlock[]>(String(row.content_en ?? ''), []),
image: row.image ? String(row.image) : null,
date: row.date ? String(row.date) : null,
readTime: Number(row.read_time) || 5,
author: String(row.author),
published: Number(row.published) || 0,
createdAt: String(row.created_at),
updatedAt: String(row.updated_at),
}
}
function rowToWork(row: Record<string, unknown>): Work {
return {
id: Number(row.id),
slug: String(row.slug),
category: row.category as Work['category'],
titleZh: String(row.title_zh),
titleEn: String(row.title_en),
descriptionZh: String(row.description_zh),
descriptionEn: String(row.description_en),
overviewZh: String(row.overview_zh),
overviewEn: String(row.overview_en),
challengeZh: String(row.challenge_zh),
challengeEn: String(row.challenge_en),
solutionZh: String(row.solution_zh),
solutionEn: String(row.solution_en),
clientZh: String(row.client_zh),
clientEn: String(row.client_en),
durationZh: String(row.duration_zh),
durationEn: String(row.duration_en),
year: String(row.year),
tags: parseJson<string[]>(String(row.tags ?? ''), []),
image: row.image ? String(row.image) : null,
gallery: parseJson<string[]>(String(row.gallery ?? ''), []),
url: row.url ? String(row.url) : null,
published: Number(row.published) || 0,
createdAt: String(row.created_at),
updatedAt: String(row.updated_at),
}
}
const ARTICLE_COLS = `id, slug, category, title_zh, title_en, excerpt_zh, excerpt_en, content_zh, content_en, image, date, read_time, author, published, created_at, updated_at`
const WORK_COLS = `id, slug, category, title_zh, title_en, description_zh, description_en, overview_zh, overview_en, challenge_zh, challenge_en, solution_zh, solution_en, client_zh, client_en, duration_zh, duration_en, year, tags, image, gallery, url, published, created_at, updated_at`
export function listArticles(options: { publishedOnly?: boolean } = {}): Article[] {
const { publishedOnly = true } = options
const sql = `SELECT ${ARTICLE_COLS} FROM articles
${publishedOnly ? 'WHERE published = 1' : ''}
ORDER BY date DESC, id DESC`
const rows = getDb().prepare(sql).all() as Array<Record<string, unknown>>
return rows.map(rowToArticle)
}
export function getArticleBySlug(slug: string, options: { publishedOnly?: boolean } = {}): Article | null {
const { publishedOnly = true } = options
const sql = `SELECT ${ARTICLE_COLS} FROM articles WHERE slug = ? ${publishedOnly ? 'AND published = 1' : ''}`
const row = getDb().prepare(sql).get(slug) as Record<string, unknown> | undefined
return row ? rowToArticle(row) : null
}
export function listWorks(options: { publishedOnly?: boolean } = {}): Work[] {
const { publishedOnly = true } = options
const sql = `SELECT ${WORK_COLS} FROM works
${publishedOnly ? 'WHERE published = 1' : ''}
ORDER BY id ASC`
const rows = getDb().prepare(sql).all() as Array<Record<string, unknown>>
return rows.map(rowToWork)
}
export function getWorkBySlug(slug: string, options: { publishedOnly?: boolean } = {}): Work | null {
const { publishedOnly = true } = options
const sql = `SELECT ${WORK_COLS} FROM works WHERE slug = ? ${publishedOnly ? 'AND published = 1' : ''}`
const row = getDb().prepare(sql).get(slug) as Record<string, unknown> | undefined
return row ? rowToWork(row) : null
}
/** 后台统计 */
export function getContentStats(): {
articles: number
works: number
publishedArticles: number
publishedWorks: number
} {
const db = getDb()
const one = (sql: string) => (db.prepare(sql).get() as { c: number }).c
return {
articles: one('SELECT COUNT(*) AS c FROM articles'),
works: one('SELECT COUNT(*) AS c FROM works'),
publishedArticles: one('SELECT COUNT(*) AS c FROM articles WHERE published = 1'),
publishedWorks: one('SELECT COUNT(*) AS c FROM works WHERE published = 1'),
}
}
+120
View File
@@ -1,7 +1,15 @@
import Database from 'better-sqlite3'
import { mkdirSync } from 'node:fs'
import { dirname } from 'node:path'
import { scryptSync, randomBytes } from 'node:crypto'
import { getConfig } from './config'
import { articlesSeed, worksSeed } from './seed'
/** 文章正文内容块 */
export interface ArticleBlock {
type: 'paragraph' | 'heading' | 'quote' | 'image'
text: string
}
/**
* SQLite 数据层单例。
@@ -30,6 +38,7 @@ export function getDb(): Database.Database {
_db.pragma('journal_mode = WAL')
_db.pragma('foreign_keys = ON')
migrate(_db)
seedIfEmpty(_db)
return _db
}
@@ -89,9 +98,120 @@ function migrate(db: Database.Database): void {
);
CREATE INDEX IF NOT EXISTS idx_comments_news ON comments(news_slug);
-- 内容管理系统:动态(articles)与作品(works)
CREATE TABLE IF NOT EXISTS articles (
id INTEGER PRIMARY KEY AUTOINCREMENT,
slug TEXT NOT NULL UNIQUE,
category TEXT NOT NULL,
title_zh TEXT NOT NULL,
title_en TEXT NOT NULL,
excerpt_zh TEXT NOT NULL,
excerpt_en TEXT NOT NULL,
content_zh TEXT NOT NULL DEFAULT '[]',
content_en TEXT NOT NULL DEFAULT '[]',
image TEXT,
date TEXT,
read_time INTEGER NOT NULL DEFAULT 5,
author TEXT NOT NULL DEFAULT 'ArcticNewOne',
published INTEGER NOT NULL DEFAULT 1,
created_at TEXT NOT NULL DEFAULT (datetime('now')),
updated_at TEXT NOT NULL DEFAULT (datetime('now'))
);
CREATE INDEX IF NOT EXISTS idx_articles_category ON articles(category);
CREATE INDEX IF NOT EXISTS idx_articles_published ON articles(published);
CREATE TABLE IF NOT EXISTS works (
id INTEGER PRIMARY KEY AUTOINCREMENT,
slug TEXT NOT NULL UNIQUE,
category TEXT NOT NULL,
title_zh TEXT NOT NULL,
title_en TEXT NOT NULL,
description_zh TEXT NOT NULL,
description_en TEXT NOT NULL,
overview_zh TEXT NOT NULL DEFAULT '',
overview_en TEXT NOT NULL DEFAULT '',
challenge_zh TEXT NOT NULL DEFAULT '',
challenge_en TEXT NOT NULL DEFAULT '',
solution_zh TEXT NOT NULL DEFAULT '',
solution_en TEXT NOT NULL DEFAULT '',
client_zh TEXT NOT NULL DEFAULT '',
client_en TEXT NOT NULL DEFAULT '',
duration_zh TEXT NOT NULL DEFAULT '',
duration_en TEXT NOT NULL DEFAULT '',
year TEXT NOT NULL DEFAULT '',
tags TEXT NOT NULL DEFAULT '[]',
image TEXT,
gallery TEXT NOT NULL DEFAULT '[]',
url TEXT,
published INTEGER NOT NULL DEFAULT 1,
created_at TEXT NOT NULL DEFAULT (datetime('now')),
updated_at TEXT NOT NULL DEFAULT (datetime('now'))
);
CREATE INDEX IF NOT EXISTS idx_works_category ON works(category);
CREATE INDEX IF NOT EXISTS idx_works_published ON works(published);
`)
}
/**
* 初始化种子数据:内容表为空时灌入 articles/works 种子;
* users 为空且配置了 adminInitialPassword 时创建预置管理员。
*/
function seedIfEmpty(db: Database.Database): void {
const { adminInitialPassword, adminEmails } = getConfig()
const articleCount = (db.prepare('SELECT COUNT(*) AS c FROM articles').get() as { c: number }).c
if (articleCount === 0) {
const insert = db.prepare(
`INSERT INTO articles
(slug, category, title_zh, title_en, excerpt_zh, excerpt_en, content_zh, content_en, image, date, read_time, author, published)
VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)`,
)
const tx = db.transaction(() => {
for (const a of articlesSeed) {
insert.run(a.slug, a.category, a.titleZh, a.titleEn, a.excerptZh, a.excerptEn,
JSON.stringify(a.contentZh), JSON.stringify(a.contentEn), a.image, a.date, a.readTime, a.author, a.published)
}
})
tx()
}
const workCount = (db.prepare('SELECT COUNT(*) AS c FROM works').get() as { c: number }).c
if (workCount === 0) {
const insert = db.prepare(
`INSERT INTO works
(slug, category, title_zh, title_en, description_zh, description_en,
overview_zh, overview_en, challenge_zh, challenge_en, solution_zh, solution_en,
client_zh, client_en, duration_zh, duration_en, year, tags, image, gallery, url, published)
VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)`,
)
const tx = db.transaction(() => {
for (const w of worksSeed) {
insert.run(w.slug, w.category, w.titleZh, w.titleEn, w.descriptionZh, w.descriptionEn,
w.overviewZh, w.overviewEn, w.challengeZh, w.challengeEn, w.solutionZh, w.solutionEn,
w.clientZh, w.clientEn, w.durationZh, w.durationEn, w.year,
JSON.stringify(w.tags), w.image, JSON.stringify(w.gallery), w.url, w.published)
}
})
tx()
}
// 预置管理员(仅当首次初始化且配置了初始密码)
const userCount = (db.prepare('SELECT COUNT(*) AS c FROM users').get() as { c: number }).c
if (userCount === 0 && adminInitialPassword && adminEmails.length > 0) {
const email = adminEmails[0]
const username = 'admin'
// 与 auth.ts 相同的 salt:hash 存储格式(scrypt)
const salt = randomBytes(16).toString('hex')
const hash = scryptSync(adminInitialPassword, salt, 64).toString('hex')
db.prepare('INSERT INTO users (username, email, password_hash, role) VALUES (?, ?, ?, ?)')
.run(username, email, `${salt}:${hash}`, 'admin')
console.log('[seed] 已创建预置管理员账号: admin(邮箱 ' + email + ')')
}
}
/** 供服务端任意位置安全关闭数据库(测试/热更新用) */
export function closeDb(): void {
if (_db) {
+737
View File
@@ -0,0 +1,737 @@
/**
* 种子数据(由 scripts/generate-seed.mjs 生成,勿手改)。
* 站点初始内容:6 篇动态 + 6 个作品(中英双语)。
* DB 初始化(migrate)时若对应表为空则自动灌入。
*/
import type { ArticleBlock } from './db'
export interface ArticleSeed {
slug: string
category: 'insights' | 'projects' | 'announcements'
titleZh: string
titleEn: string
excerptZh: string
excerptEn: string
contentZh: ArticleBlock[]
contentEn: ArticleBlock[]
image: string
date: string
readTime: number
author: string
published: number
}
export interface WorkSeed {
slug: string
category: 'webDesign' | 'branding' | 'development'
titleZh: string
titleEn: string
descriptionZh: string
descriptionEn: string
overviewZh: string
overviewEn: string
challengeZh: string
challengeEn: string
solutionZh: string
solutionEn: string
clientZh: string
clientEn: string
durationZh: string
durationEn: string
year: string
tags: string[]
image: string
gallery: string[]
url: string | null
published: number
}
export const articlesSeed: ArticleSeed[] = [
{
"slug": "design-trends-2026",
"category": "insights",
"titleZh": "2026 年设计趋势展望",
"titleEn": "Design Trends Shaping 2026",
"excerptZh": "从极简主义的回归到大胆排版的兴起,从 3D 元素普及到 AI 辅助设计成熟,探索塑造今年数字体验的前沿趋势。",
"excerptEn": "Explore the emerging design trends defining digital experiences this year, from minimalism to bold typography.",
"contentZh": [
{
"type": "paragraph",
"text": "2026 年,设计行业正在经历一场深刻的变革。从极简主义的回归到大胆排版的兴起,从 3D 元素的普及到 AI 辅助设计的成熟,这些趋势正在重新定义数字体验的边界。作为设计从业者,我们需要紧跟这些变化,才能为客户创造更具竞争力的作品。"
},
{
"type": "heading",
"text": "极简主义的回归"
},
{
"type": "paragraph",
"text": "在信息过载的时代,用户越来越渴望简洁、清晰的界面。2026 年的极简主义不再是简单的「少即是多」,而是通过精心的信息架构和视觉层次,在有限的空间内传达更多价值。留白不再是空白,而是一种有意为之的设计语言。"
},
{
"type": "quote",
"text": "好的设计不是添加更多,而是去除不必要的。在 2026 年,这一点比以往任何时候都更加重要。"
},
{
"type": "heading",
"text": "大胆排版与动态文字"
},
{
"type": "paragraph",
"text": "排版正在从配角变成主角。大尺寸、高对比度的字体设计正在成为品牌表达的重要手段。动态文字效果的普及,让排版不再是静态的装饰,而是能够与用户互动的活元素。"
},
{
"type": "heading",
"text": "AI 辅助设计的成熟"
},
{
"type": "paragraph",
"text": "AI 工具正在从「替代设计师」转向「增强设计师」。智能布局建议、自动化配色方案、实时设计反馈等功能,让设计师能够专注于创意和策略,而非重复性的执行工作。"
}
],
"contentEn": [
{
"type": "paragraph",
"text": "In 2026, the design industry is undergoing a profound transformation. From the return of minimalism to the rise of bold typography, from the普及 of 3D elements to the maturity of AI-assisted design, these trends are redefining the boundaries of digital experiences."
},
{
"type": "heading",
"text": "The Return of Minimalism"
},
{
"type": "paragraph",
"text": "In an age of information overload, users increasingly渴望 clean, clear interfaces. 2026's minimalism isn't just 'less is more' — it's about delivering more value in limited space through careful information architecture and visual hierarchy."
},
{
"type": "quote",
"text": "Good design isn't about adding more, it's about removing the unnecessary. In 2026, this matters more than ever."
},
{
"type": "heading",
"text": "Bold Typography & Dynamic Text"
},
{
"type": "paragraph",
"text": "Typography is moving from supporting actor to leading role. Large, high-contrast font designs are becoming important brand expression tools. Dynamic text effects are making typography a living, interactive element rather than static decoration."
},
{
"type": "heading",
"text": "Maturity of AI-Assisted Design"
},
{
"type": "paragraph",
"text": "AI tools are shifting from 'replacing designers' to 'empowering designers.' Smart layout suggestions, automated color schemes, and real-time design feedback let designers focus on creativity and strategy rather than repetitive execution."
}
],
"image": "https://picsum.photos/id/1/800/500",
"date": "2026-05-28",
"readTime": 5,
"author": "ArcticNewOne",
"published": 1
},
{
"slug": "forma-digital-launch",
"category": "projects",
"titleZh": "Forma Digital 电商平台正式上线",
"titleEn": "Forma Digital Platform Launch",
"excerptZh": "我们很高兴地宣布 Forma Digital 电商平台正式上线,上线后转化率提升 45%。",
"excerptEn": "We are excited to announce the successful launch of Forma Digital, a revolutionary e-commerce experience.",
"contentZh": [
{
"type": "paragraph",
"text": "经过三个月的精心打造,我们很高兴地宣布 Forma Digital 电商平台正式上线!这个项目是我们团队迄今为止最具挑战性的作品之一,也是我们技术实力和设计能力的集中体现。"
},
{
"type": "heading",
"text": "项目背景"
},
{
"type": "paragraph",
"text": "Forma Digital 是一家专注于高端家居用品的电商品牌。他们需要一个能够完美展示产品质感、提供流畅购物体验的平台。原有的网站存在加载缓慢、移动端体验差、转化率低等问题。"
},
{
"type": "quote",
"text": "北极新一团队不仅理解我们的需求,更超越了我们的期望。新平台上线后,我们的转化率提升了 45%。"
},
{
"type": "heading",
"text": "技术亮点"
},
{
"type": "paragraph",
"text": "我们采用了 React + Next.js 技术栈,实现了服务端渲染和静态生成。通过图片懒加载、代码分割、CDN 加速等技术手段,将首屏加载时间从 4.5 秒降低到 1.2 秒。"
},
{
"type": "heading",
"text": "成果展示"
},
{
"type": "paragraph",
"text": "新平台上线后,用户停留时间增加了 60%,跳出率降低了 35%,转化率提升了 45%。客户对新平台的设计和性能都非常满意。"
}
],
"contentEn": [
{
"type": "paragraph",
"text": "After three months of careful crafting, we're excited to announce the official launch of the Forma Digital e-commerce platform! This project is one of our team's most challenging works to date."
},
{
"type": "heading",
"text": "Project Background"
},
{
"type": "paragraph",
"text": "Forma Digital is an e-commerce brand focusing on premium home goods. They needed a platform that could perfectly showcase product quality while delivering a smooth shopping experience."
},
{
"type": "quote",
"text": "The ArcticNewOne team not only understood our needs but exceeded our expectations. After the new platform launched, our conversion rate increased by 45%."
},
{
"type": "heading",
"text": "Technical Highlights"
},
{
"type": "paragraph",
"text": "We used React + Next.js for server-side rendering and static generation. Through lazy loading, code splitting, and CDN acceleration, we reduced first load time from 4.5s to 1.2s."
},
{
"type": "heading",
"text": "Results"
},
{
"type": "paragraph",
"text": "After launch, user停留 time increased by 60%, bounce rate decreased by 35%, and conversion rate improved by 45%."
}
],
"image": "https://picsum.photos/id/201/800/500",
"date": "2026-05-15",
"readTime": 3,
"author": "ArcticNewOne",
"published": 1
},
{
"slug": "studio-expansion",
"category": "announcements",
"titleZh": "工作室扩张公告",
"titleEn": "Studio Expansion Announcement",
"excerptZh": "ArcticNewOne 正在成长!我们正在扩展团队与服务能力,以更好地服务客户。",
"excerptEn": "ArcticNewOne is growing! We are expanding our team and capabilities to serve you better.",
"contentZh": [
{
"type": "paragraph",
"text": "随着业务的持续增长和客户需求的不断增加,我们很高兴地宣布 ArcticNewOne 工作室正式扩展!我们将增加新的团队成员,拓展服务能力,为客户提供更优质的数字化解决方案。"
},
{
"type": "heading",
"text": "团队扩展"
},
{
"type": "paragraph",
"text": "我们将新增 5 名资深设计师和 3 名高级开发工程师,覆盖前端、后端、UI/UX 等多个领域。这些新成员都拥有丰富的行业经验,曾服务于多家知名企业。"
},
{
"type": "quote",
"text": "人才是我们最宝贵的资产。通过扩展团队,我们能够承接更多项目,同时保持一贯的高品质交付。"
},
{
"type": "heading",
"text": "服务升级"
},
{
"type": "paragraph",
"text": "除了现有的网页设计、品牌设计、程序开发等服务,我们还将新增数据可视化、AI 应用开发、AR/VR 体验设计等前沿服务。"
},
{
"type": "heading",
"text": "展望未来"
},
{
"type": "paragraph",
"text": "我们计划在未来一年内完成 50+ 项目,服务 30+ 新客户。同时,我们将继续深耕技术创新,探索更多可能性,为客户创造更大价值。"
}
],
"contentEn": [
{
"type": "paragraph",
"text": "With continued business growth and increasing client demand, we're excited to announce the official expansion of ArcticNewOne Studio!"
},
{
"type": "heading",
"text": "Team Growth"
},
{
"type": "paragraph",
"text": "We're adding 5 senior designers and 3 senior developers covering frontend, backend, UI/UX, and more. All new members have extensive industry experience."
},
{
"type": "quote",
"text": "Talent is our most valuable asset. By expanding our team, we can take on more projects while maintaining consistent high-quality delivery."
},
{
"type": "heading",
"text": "Service Upgrade"
},
{
"type": "paragraph",
"text": "In addition to existing services, we're adding data visualization, AI application development, AR/VR experience design, and other cutting-edge services."
},
{
"type": "heading",
"text": "Looking Ahead"
},
{
"type": "paragraph",
"text": "We plan to complete 50+ projects and serve 30+ new clients in the coming year while continuing to explore new possibilities."
}
],
"image": "https://picsum.photos/id/164/800/500",
"date": "2026-05-10",
"readTime": 2,
"author": "ArcticNewOne",
"published": 1
},
{
"slug": "ux-research-methods",
"category": "insights",
"titleZh": "现代 UX 研究方法",
"titleEn": "Modern UX Research Methods",
"excerptZh": "深入解析影响我们设计决策的最新用户体验研究方法,从远程测试到行为数据分析。",
"excerptEn": "Dive into the latest user experience research methodologies, from remote testing to behavioral analytics.",
"contentZh": [
{
"type": "paragraph",
"text": "用户体验研究是设计决策的基础。在 2026 年,随着技术的发展和用户行为的变化,UX 研究方法也在不断演进。本文将介绍几种最有效的现代 UX 研究方法。"
},
{
"type": "heading",
"text": "远程用户测试"
},
{
"type": "paragraph",
"text": "远程用户测试已经成为 UX 研究的主流方法。通过专业的远程测试平台,我们可以在短时间内招募到全球各地的测试用户,获取更广泛的反馈。"
},
{
"type": "quote",
"text": "远程测试不仅降低了成本,更重要的是让我们能够接触到更真实的用户场景。"
},
{
"type": "heading",
"text": "行为数据分析"
},
{
"type": "paragraph",
"text": "通过热力图、滚动深度、点击流等行为数据,我们可以客观地了解用户如何与产品互动。这些数据弥补了传统访谈和问卷的不足,提供了更真实的用户行为洞察。"
},
{
"type": "heading",
"text": "AI 辅助分析"
},
{
"type": "paragraph",
"text": "AI 工具正在帮助我们更高效地分析用户反馈。情感分析、主题聚类、趋势预测等功能,让我们能够从海量数据中快速提取有价值的洞察。"
}
],
"contentEn": [
{
"type": "paragraph",
"text": "UX research is the foundation of design decisions. In 2026, as technology evolves and user behaviors change, UX research methods continue to advance."
},
{
"type": "heading",
"text": "Remote User Testing"
},
{
"type": "paragraph",
"text": "Remote user testing has become mainstream. Through professional platforms, we can recruit test users globally and gather broader feedback in less time."
},
{
"type": "quote",
"text": "Remote testing not only reduces costs but more importantly lets us access more authentic user scenarios."
},
{
"type": "heading",
"text": "Behavioral Data Analysis"
},
{
"type": "paragraph",
"text": "Through heatmaps, scroll depth, click streams, and other behavioral data, we can objectively understand how users interact with products."
},
{
"type": "heading",
"text": "AI-Assisted Analysis"
},
{
"type": "paragraph",
"text": "AI tools help us analyze user feedback more efficiently. Sentiment analysis, topic clustering, and trend prediction help extract valuable insights from massive data."
}
],
"image": "https://picsum.photos/id/180/800/500",
"date": "2026-04-28",
"readTime": 7,
"author": "ArcticNewOne",
"published": 1
},
{
"slug": "bold-moves-case-study",
"category": "projects",
"titleZh": "Bold Moves:项目复盘",
"titleEn": "Bold Moves: A Case Study",
"excerptZh": "走进我们屡获殊荣的建筑可视化项目幕后,见证前沿 3D 技术如何重塑用户体验。",
"excerptEn": "Behind the scenes of our award-winning architectural visualization project featuring cutting-edge 3D technology.",
"contentZh": [
{
"type": "paragraph",
"text": "Bold Moves 是一个展示创新建筑设计的交互式网站项目。本文将深入介绍这个项目的设计思路、技术实现和最终成果。"
},
{
"type": "heading",
"text": "设计理念"
},
{
"type": "paragraph",
"text": "Bold Moves 希望通过数字方式展示建筑设计的魅力。我们决定采用 3D 可视化技术,让用户能够从任意角度欣赏建筑细节,获得沉浸式的体验。"
},
{
"type": "quote",
"text": "我们想要的不只是一个展示网站,而是一个能够让用户「走进」建筑的数字空间。"
},
{
"type": "heading",
"text": "技术挑战"
},
{
"type": "paragraph",
"text": "高质量的 3D 渲染需要强大的计算能力,而网页端的性能有限。我们通过模型优化、LOD 技术、WebGL 渲染等手段,在保证视觉质量的同时,实现了流畅的交互体验。"
},
{
"type": "heading",
"text": "最终成果"
},
{
"type": "paragraph",
"text": "项目上线后获得了广泛好评,赢得了多个设计奖项。用户平均停留时间超过 5 分钟,远高于行业平均水平。"
}
],
"contentEn": [
{
"type": "paragraph",
"text": "Bold Moves is an interactive website showcasing innovative architectural designs. This article provides an in-depth look at the design思路, technical implementation, and final results."
},
{
"type": "heading",
"text": "Design Philosophy"
},
{
"type": "paragraph",
"text": "Bold Moves wanted to showcase architectural beauty digitally. We decided to use 3D visualization to let users appreciate architectural details from any angle."
},
{
"type": "quote",
"text": "We didn't just want a showcase website — we wanted a digital space where users could 'walk into' the architecture."
},
{
"type": "heading",
"text": "Technical Challenges"
},
{
"type": "paragraph",
"text": "High-quality 3D rendering requires significant computing power, but web performance is limited. We achieved smooth interactions through model optimization, LOD techniques, and WebGL rendering."
},
{
"type": "heading",
"text": "Final Results"
},
{
"type": "paragraph",
"text": "The project received widespread acclaim and won multiple design awards. Average user停留 time exceeded 5 minutes, well above industry average."
}
],
"image": "https://picsum.photos/id/119/800/500",
"date": "2026-04-20",
"readTime": 6,
"author": "ArcticNewOne",
"published": 1
},
{
"slug": "new-tools-integration",
"category": "announcements",
"titleZh": "工具箱新增多款实用工具",
"titleEn": "New Tools Added to Our Platform",
"excerptZh": "看看我们工具箱的最新成员,覆盖设计、开发、协作,助你精简工作流、提升生产力。",
"excerptEn": "Check out the latest additions to our toolbox across design, development and collaboration.",
"contentZh": [
{
"type": "paragraph",
"text": "为了更好地服务客户,我们不断扩充和完善我们的工具箱。最近,我们新增了多款实用工具,涵盖设计、开发、协作等多个领域。"
},
{
"type": "heading",
"text": "设计工具升级"
},
{
"type": "paragraph",
"text": "我们引入了最新的设计协作平台,支持实时多人编辑、版本管理、设计系统集成等功能。设计师和开发者可以在同一个平台上无缝协作。"
},
{
"type": "quote",
"text": "工欲善其事,必先利其器。好的工具能够大幅提升团队效率。"
},
{
"type": "heading",
"text": "开发工具增强"
},
{
"type": "paragraph",
"text": "新增了自动化测试框架、性能监控工具、代码质量检查等开发工具。这些工具帮助我们在开发过程中及时发现和解决问题,保证代码质量。"
},
{
"type": "heading",
"text": "协作工具优化"
},
{
"type": "paragraph",
"text": "我们升级了项目管理平台,新增了看板视图、时间追踪、资源分配等功能。项目经理可以更直观地掌控项目进度,团队成员可以更高效地协作。"
}
],
"contentEn": [
{
"type": "paragraph",
"text": "To better serve our clients, we continuously expand and improve our toolbox. Recently, we've added several practical tools covering design, development, collaboration, and more."
},
{
"type": "heading",
"text": "Design Tool Upgrades"
},
{
"type": "paragraph",
"text": "We've引入 the latest design collaboration platform supporting real-time multi-person editing, version management, and design system integration."
},
{
"type": "quote",
"text": "Good tools significantly boost team efficiency. The right toolchain is key to delivering quality work."
},
{
"type": "heading",
"text": "Development Tool Enhancements"
},
{
"type": "paragraph",
"text": "Added automated testing frameworks, performance monitoring tools, and code quality checks to help identify and resolve issues during development."
},
{
"type": "heading",
"text": "Collaboration Tool Optimization"
},
{
"type": "paragraph",
"text": "We upgraded our project management platform with new Kanban views, time tracking, and resource allocation features for better project oversight."
}
],
"image": "https://picsum.photos/id/326/800/500",
"date": "2026-04-12",
"readTime": 4,
"author": "ArcticNewOne",
"published": 1
}
]
export const worksSeed: WorkSeed[] = [
{
"slug": "forma-digital",
"category": "webDesign",
"titleZh": "Forma Digital",
"titleEn": "Forma Digital",
"descriptionZh": "现代化的电商平台,无缝用户体验与动态产品展示。",
"descriptionEn": "A modern e-commerce platform with seamless user experience and dynamic product showcases.",
"overviewZh": "Forma Digital 是一个现代化的电商平台,致力于为用户提供无缝的购物体验。我们重新设计了整个用户界面,采用极简主义设计风格,突出产品展示,提升转化率。",
"overviewEn": "Forma Digital is a modern e-commerce platform designed to provide a seamless shopping experience. We redesigned the entire user interface with a minimalist design approach, focusing on product showcase and conversion optimization.",
"challengeZh": "客户需要一个既能展示高端产品,又能提供流畅购物体验的平台。原有的网站加载缓慢,用户体验差,转化率低下。",
"challengeEn": "The client needed a platform that could both showcase premium products and deliver a smooth shopping experience. The existing website was slow, had poor mobile experience, and low conversion rates.",
"solutionZh": "我们采用了 React + Next.js 技术栈,实现了服务端渲染和静态生成,大幅提升加载速度。同时重新设计了产品展示页面,采用沉浸式大图展示,配合流畅的动画过渡。",
"solutionEn": "We built the platform with React + Next.js, implementing server-side rendering and static generation for blazing fast load times. The product pages feature immersive large-format imagery with smooth animation transitions.",
"clientZh": "Forma Digital Inc.",
"clientEn": "Forma Digital Inc.",
"durationZh": "3 个月",
"durationEn": "3 months",
"year": "2026",
"tags": [
"Web Design",
"E-commerce",
"React"
],
"image": "https://picsum.photos/id/201/1200/800",
"gallery": [
"https://picsum.photos/id/201/800/600",
"https://picsum.photos/id/202/800/600",
"https://picsum.photos/id/203/800/600",
"https://picsum.photos/id/204/800/600"
],
"url": null,
"published": 1
},
{
"slug": "one-step",
"category": "branding",
"titleZh": "One Step",
"titleEn": "One Step",
"descriptionZh": "为健身应用打造的品牌形象与营销战役,聚焦可持续习惯养成。",
"descriptionEn": "Brand identity and marketing campaign for a fitness app focused on sustainable habits.",
"overviewZh": "One Step 是一款专注于健康习惯养成的健身应用。我们为其打造了完整的品牌视觉识别系统,包括 Logo 设计、UI 界面和营销物料。",
"overviewEn": "One Step is a fitness app focused on building healthy habits. We created a complete brand visual identity system including logo design, UI interface, and marketing materials.",
"challengeZh": "在竞争激烈的健身应用市场中,如何通过品牌设计脱颖而出,建立独特的品牌认知。",
"challengeEn": "In the competitive fitness app market, how to stand out through brand design and establish unique brand recognition.",
"solutionZh": "我们以「一步一个脚印」为核心理念,设计了简洁有力的品牌标识。采用渐变色彩和圆润的图形语言,传达健康、积极、向上的品牌调性。",
"solutionEn": "With the core concept of 'one step at a time', we designed a clean and powerful brand identity. Using gradient colors and rounded graphic language to convey health, positivity, and progress.",
"clientZh": "One Step Fitness",
"clientEn": "One Step Fitness",
"durationZh": "2 个月",
"durationEn": "2 months",
"year": "2024",
"tags": [
"Branding",
"Marketing",
"UI/UX"
],
"image": "https://picsum.photos/id/180/1200/800",
"gallery": [
"https://picsum.photos/id/180/800/600",
"https://picsum.photos/id/181/800/600",
"https://picsum.photos/id/182/800/600",
"https://picsum.photos/id/183/800/600"
],
"url": null,
"published": 1
},
{
"slug": "nero-vision",
"category": "development",
"titleZh": "Nero Vision",
"titleEn": "Nero Vision",
"descriptionZh": "面向创意专业人士的全栈作品集管理应用。",
"descriptionEn": "Full-stack web application for creative professionals to manage their portfolios.",
"overviewZh": "Nero Vision 是一个面向创意专业人士的作品集管理平台,帮助设计师和艺术家展示和管理他们的创作。",
"overviewEn": "Nero Vision is a portfolio management platform for creative professionals, helping designers and artists showcase and manage their work.",
"challengeZh": "创意人士需要一个既能完美展示作品,又能方便管理的平台。现有解决方案要么太复杂,要么展示效果不佳。",
"challengeEn": "Creative professionals need a platform that can perfectly showcase work while being easy to manage. Existing solutions are either too complex or have poor display quality.",
"solutionZh": "我们采用 Vue.js + Node.js 全栈开发,设计了直观的拖拽式作品管理界面,配合精美的展示模板,让创意人士轻松打造个人品牌。",
"solutionEn": "We developed a full-stack application with Vue.js + Node.js, designing an intuitive drag-and-drop portfolio management interface with beautiful display templates.",
"clientZh": "Nero Studio",
"clientEn": "Nero Studio",
"durationZh": "4 个月",
"durationEn": "4 months",
"year": "2025",
"tags": [
"Development",
"Vue.js",
"Node.js"
],
"image": "https://picsum.photos/id/119/1200/800",
"gallery": [
"https://picsum.photos/id/119/800/600",
"https://picsum.photos/id/120/800/600",
"https://picsum.photos/id/121/800/600",
"https://picsum.photos/id/122/800/600"
],
"url": null,
"published": 1
},
{
"slug": "bold-moves",
"category": "webDesign",
"titleZh": "Bold Moves",
"titleEn": "Bold Moves",
"descriptionZh": "以 3D 可视化展示创新建筑设计的交互式网站。",
"descriptionEn": "Interactive website showcasing innovative architectural designs with 3D visualizations.",
"overviewZh": "Bold Moves 是一个展示创新建筑设计的交互式网站,通过 3D 可视化技术,让用户身临其境地体验建筑之美。",
"overviewEn": "Bold Moves is an interactive website showcasing innovative architectural designs through 3D visualization technology, letting users experience architecture immersively.",
"challengeZh": "如何将复杂的建筑设计以直观、吸引人的方式展示给普通用户,同时保持专业性。",
"challengeEn": "How to present complex architectural designs in an intuitive and engaging way to general users while maintaining professionalism.",
"solutionZh": "我们使用 Three.js 实现了高质量的 3D 渲染,配合流畅的交互设计,用户可以从任意角度欣赏建筑细节。同时加入了光影效果和材质展示,提升视觉冲击力。",
"solutionEn": "We used Three.js for high-quality 3D rendering with smooth interactive design, allowing users to appreciate architectural details from any angle, with lighting effects and material displays.",
"clientZh": "Bold Moves Architecture",
"clientEn": "Bold Moves Architecture",
"durationZh": "5 个月",
"durationEn": "5 months",
"year": "2024",
"tags": [
"Web Design",
"3D",
"Three.js"
],
"image": "https://picsum.photos/id/164/1200/800",
"gallery": [
"https://picsum.photos/id/164/800/600",
"https://picsum.photos/id/165/800/600",
"https://picsum.photos/id/166/800/600",
"https://picsum.photos/id/167/800/600"
],
"url": null,
"published": 1
},
{
"slug": "echo-labs",
"category": "branding",
"titleZh": "Echo Labs",
"titleEn": "Echo Labs",
"descriptionZh": "AI 科技创业公司的企业品牌与视觉识别。",
"descriptionEn": "Corporate branding and visual identity for a tech startup in the AI space.",
"overviewZh": "Echo Labs 是一家 AI 领域的科技创业公司,我们为其打造了完整的品牌视觉识别系统和企业官网。",
"overviewEn": "Echo Labs is an AI tech startup. We created a complete brand visual identity system and corporate website for them.",
"challengeZh": "AI 领域的品牌需要既体现科技感,又要有人文温度,避免过于冷冰冰的技术感。",
"challengeEn": "AI brands need to convey both technology and humanity, avoiding being too cold or technical.",
"solutionZh": "我们以「回声」为概念,设计了富有动感的品牌标识。采用深色主题配合渐变色彩,营造科技感的同时,通过圆润的图形语言增添亲和力。",
"solutionEn": "With the concept of 'echo', we designed a dynamic brand identity. Using dark themes with gradient colors for a tech feel, while rounded graphic language adds approachability.",
"clientZh": "Echo Labs AI",
"clientEn": "Echo Labs AI",
"durationZh": "3 个月",
"durationEn": "3 months",
"year": "2025",
"tags": [
"Branding",
"Visual Identity",
"Corporate"
],
"image": "https://picsum.photos/id/101/1200/800",
"gallery": [
"https://picsum.photos/id/101/800/600",
"https://picsum.photos/id/102/800/600",
"https://picsum.photos/id/103/800/600",
"https://picsum.photos/id/104/800/600"
],
"url": null,
"published": 1
},
{
"slug": "flux-api",
"category": "development",
"titleZh": "Flux API",
"titleEn": "Flux API",
"descriptionZh": "具备完善文档与开发者工具的可扩展 REST API 服务。",
"descriptionEn": "Scalable REST API with comprehensive documentation and developer tools.",
"overviewZh": "Flux API 是一个可扩展的 REST API 服务平台,提供全面的文档和开发者工具,帮助开发者快速集成。",
"overviewEn": "Flux API is a scalable REST API service platform with comprehensive documentation and developer tools to help developers integrate quickly.",
"challengeZh": "API 文档和开发者体验是技术产品的核心竞争力,如何让复杂的 API 变得易于理解和使用。",
"challengeEn": "API documentation and developer experience are core competitive advantages. How to make complex APIs easy to understand and use.",
"solutionZh": "我们设计了交互式 API 文档,支持在线测试和代码生成。同时提供了多语言 SDK 和详细的教程,大幅降低开发者的学习成本。",
"solutionEn": "We designed interactive API documentation with online testing and code generation. Multi-language SDKs and detailed tutorials significantly reduce the learning curve for developers.",
"clientZh": "Flux Technologies",
"clientEn": "Flux Technologies",
"durationZh": "6 个月",
"durationEn": "6 months",
"year": "2025",
"tags": [
"Development",
"API",
"Python"
],
"image": "https://picsum.photos/id/326/1200/800",
"gallery": [
"https://picsum.photos/id/326/800/600",
"https://picsum.photos/id/327/800/600",
"https://picsum.photos/id/328/800/600",
"https://picsum.photos/id/329/800/600"
],
"url": null,
"published": 1
}
]
+49
View File
@@ -0,0 +1,49 @@
import type { ArticleBlock } from './db'
/**
* 后台内容校验/归一化(articles / works 的 post/patch 共用)。
*/
export const ARTICLE_CATEGORIES = ['insights', 'projects', 'announcements']
export const WORK_CATEGORIES = ['webDesign', 'branding', 'development']
export const BLOCK_TYPES = ['paragraph', 'heading', 'quote', 'image']
export function normalizeSlug(value: unknown): string {
return String(value ?? '').trim()
}
export function isValidSlug(slug: string): boolean {
return /^[a-z0-9-]{2,64}$/.test(slug)
}
export function isValidArticleCategory(value: unknown): boolean {
return typeof value === 'string' && ARTICLE_CATEGORIES.includes(value)
}
export function isValidWorkCategory(value: unknown): boolean {
return typeof value === 'string' && WORK_CATEGORIES.includes(value)
}
/** 归一化内容块数组(过滤非法块) */
export function normalizeBlocks(value: unknown): ArticleBlock[] {
if (!Array.isArray(value)) return []
return value
.filter(
(b): b is ArticleBlock =>
!!b &&
typeof b === 'object' &&
BLOCK_TYPES.includes((b as ArticleBlock).type) &&
typeof (b as ArticleBlock).text === 'string',
)
.map((b) => ({ type: b.type, text: b.text.slice(0, 20000) }))
}
export function normalizeTags(value: unknown): string[] {
if (!Array.isArray(value)) return []
return value.filter((t): t is string => typeof t === 'string' && t.trim()).map((t) => t.trim()).slice(0, 20)
}
export function normalizeGallery(value: unknown): string[] {
if (!Array.isArray(value)) return []
return value.filter((u): u is string => typeof u === 'string' && u.trim()).map((u) => u.trim()).slice(0, 20)
}