From d67849a311a2d0ae4ffde2178063e9377191f12d Mon Sep 17 00:00:00 2001 From: chenchun Date: Thu, 6 Aug 2026 16:15:14 +0800 Subject: [PATCH] =?UTF-8?q?feat:=20=E5=90=8E=E5=8F=B0=E7=AE=A1=E7=90=86?= =?UTF-8?q?=E7=B3=BB=E7=BB=9F=EF=BC=88Admin=20Backend=20+=20=E5=85=A8?= =?UTF-8?q?=E9=87=8F=20CMS=EF=BC=89?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit - 内容迁入数据库: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 中间件 + 客户端会话恢复插件 --- .env.example | 3 + README.md | 22 +- app/components/admin/AdminBlockEditor.vue | 130 ++++ app/components/admin/AdminConfirmDialog.vue | 88 +++ app/components/admin/AdminImageUpload.vue | 86 +++ app/components/admin/AdminSidebar.vue | 68 ++ app/components/home/HomePartnersWork.vue | 29 +- app/components/home/HomeUpdates.vue | 58 +- app/data/news.ts | 98 --- app/data/work.ts | 108 --- app/layouts/admin.vue | 71 ++ app/middleware/admin.ts | 23 + app/pages/account.vue | 98 +-- app/pages/admin/comments.vue | 208 ++++++ app/pages/admin/contacts.vue | 175 +++++ app/pages/admin/index.vue | 135 ++++ app/pages/admin/news.vue | 533 ++++++++++++++ app/pages/admin/subscribers.vue | 171 +++++ app/pages/admin/users.vue | 212 ++++++ app/pages/admin/work.vue | 709 +++++++++++++++++++ app/pages/news/[slug].vue | 128 ++-- app/pages/news/index.vue | 57 +- app/pages/work/[slug].vue | 70 +- app/pages/work/index.vue | 38 +- app/plugins/auth.client.ts | 10 + deploy.sh | 9 + i18n/locales/en.json | 165 +---- i18n/locales/zh.json | 165 +---- nuxt.config.ts | 1 + scripts/generate-seed.mjs | 144 ++++ server/api/account/admin.get.ts | 30 - server/api/admin/articles.get.ts | 10 + server/api/admin/articles.post.ts | 52 ++ server/api/admin/articles/[id].delete.ts | 25 + server/api/admin/articles/[id].patch.ts | 82 +++ server/api/admin/comments.get.ts | 18 + server/api/admin/comments/[id].delete.ts | 18 + server/api/admin/contacts.get.ts | 13 + server/api/admin/contacts/[id].delete.ts | 18 + server/api/admin/stats.get.ts | 20 + server/api/admin/subscribers.get.ts | 13 + server/api/admin/subscribers/[id].delete.ts | 18 + server/api/admin/subscribers/export.get.ts | 23 + server/api/admin/upload.post.ts | 46 ++ server/api/admin/users.get.ts | 13 + server/api/admin/users/[id].delete.ts | 22 + server/api/admin/users/[id].patch.ts | 28 + server/api/admin/works.get.ts | 10 + server/api/admin/works.post.ts | 69 ++ server/api/admin/works/[id].delete.ts | 25 + server/api/admin/works/[id].patch.ts | 95 +++ server/api/auth/register.post.ts | 7 +- server/api/comments.get.ts | 4 +- server/api/comments.post.ts | 4 +- server/api/favorites.post.ts | 4 +- server/api/news.get.ts | 8 + server/api/news/[slug].get.ts | 14 + server/api/work.get.ts | 8 + server/api/work/[slug].get.ts | 14 + server/routes/sitemap.xml.ts | 11 +- server/routes/uploads/[...path].get.ts | 40 ++ server/utils/auth.ts | 14 +- server/utils/config.ts | 3 + server/utils/content.ts | 166 +++++ server/utils/db.ts | 120 ++++ server/utils/seed.ts | 737 ++++++++++++++++++++ server/utils/validateContent.ts | 49 ++ 67 files changed, 4909 insertions(+), 754 deletions(-) create mode 100644 app/components/admin/AdminBlockEditor.vue create mode 100644 app/components/admin/AdminConfirmDialog.vue create mode 100644 app/components/admin/AdminImageUpload.vue create mode 100644 app/components/admin/AdminSidebar.vue delete mode 100644 app/data/news.ts delete mode 100644 app/data/work.ts create mode 100644 app/layouts/admin.vue create mode 100644 app/middleware/admin.ts create mode 100644 app/pages/admin/comments.vue create mode 100644 app/pages/admin/contacts.vue create mode 100644 app/pages/admin/index.vue create mode 100644 app/pages/admin/news.vue create mode 100644 app/pages/admin/subscribers.vue create mode 100644 app/pages/admin/users.vue create mode 100644 app/pages/admin/work.vue create mode 100644 app/plugins/auth.client.ts create mode 100644 scripts/generate-seed.mjs delete mode 100644 server/api/account/admin.get.ts create mode 100644 server/api/admin/articles.get.ts create mode 100644 server/api/admin/articles.post.ts create mode 100644 server/api/admin/articles/[id].delete.ts create mode 100644 server/api/admin/articles/[id].patch.ts create mode 100644 server/api/admin/comments.get.ts create mode 100644 server/api/admin/comments/[id].delete.ts create mode 100644 server/api/admin/contacts.get.ts create mode 100644 server/api/admin/contacts/[id].delete.ts create mode 100644 server/api/admin/stats.get.ts create mode 100644 server/api/admin/subscribers.get.ts create mode 100644 server/api/admin/subscribers/[id].delete.ts create mode 100644 server/api/admin/subscribers/export.get.ts create mode 100644 server/api/admin/upload.post.ts create mode 100644 server/api/admin/users.get.ts create mode 100644 server/api/admin/users/[id].delete.ts create mode 100644 server/api/admin/users/[id].patch.ts create mode 100644 server/api/admin/works.get.ts create mode 100644 server/api/admin/works.post.ts create mode 100644 server/api/admin/works/[id].delete.ts create mode 100644 server/api/admin/works/[id].patch.ts create mode 100644 server/api/news.get.ts create mode 100644 server/api/news/[slug].get.ts create mode 100644 server/api/work.get.ts create mode 100644 server/api/work/[slug].get.ts create mode 100644 server/routes/uploads/[...path].get.ts create mode 100644 server/utils/content.ts create mode 100644 server/utils/seed.ts create mode 100644 server/utils/validateContent.ts diff --git a/.env.example b/.env.example index a12906d..41dc9fa 100644 --- a/.env.example +++ b/.env.example @@ -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 diff --git a/README.md b/README.md index 15f8d4f..2ce12ca 100644 --- a/README.md +++ b/README.md @@ -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/ # 公开静态文件 diff --git a/app/components/admin/AdminBlockEditor.vue b/app/components/admin/AdminBlockEditor.vue new file mode 100644 index 0000000..9091473 --- /dev/null +++ b/app/components/admin/AdminBlockEditor.vue @@ -0,0 +1,130 @@ + + + diff --git a/app/components/admin/AdminConfirmDialog.vue b/app/components/admin/AdminConfirmDialog.vue new file mode 100644 index 0000000..2188d9a --- /dev/null +++ b/app/components/admin/AdminConfirmDialog.vue @@ -0,0 +1,88 @@ + + + + + diff --git a/app/components/admin/AdminImageUpload.vue b/app/components/admin/AdminImageUpload.vue new file mode 100644 index 0000000..7864f6b --- /dev/null +++ b/app/components/admin/AdminImageUpload.vue @@ -0,0 +1,86 @@ + + + diff --git a/app/components/admin/AdminSidebar.vue b/app/components/admin/AdminSidebar.vue new file mode 100644 index 0000000..6f54702 --- /dev/null +++ b/app/components/admin/AdminSidebar.vue @@ -0,0 +1,68 @@ + + + diff --git a/app/components/home/HomePartnersWork.vue b/app/components/home/HomePartnersWork.vue index bf14abe..62b7e34 100755 --- a/app/components/home/HomePartnersWork.vue +++ b/app/components/home/HomePartnersWork.vue @@ -1,13 +1,26 @@ + + + + diff --git a/app/middleware/admin.ts b/app/middleware/admin.ts new file mode 100644 index 0000000..db48bae --- /dev/null +++ b/app/middleware/admin.ts @@ -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('/') + } +}) diff --git a/app/pages/account.vue b/app/pages/account.vue index 7ea4556..6047f15 100644 --- a/app/pages/account.vue +++ b/app/pages/account.vue @@ -26,6 +26,17 @@

{{ userStore.user?.email }}

+ +
+ + + {{ t('account.adminEntry') }} + +
+
- - -
-
-

{{ t('account.admin.contacts') }}

-

{{ t('account.admin.emptyContacts') }}

-
-
-
-
- {{ c.name }} - {{ c.email }} -
- - {{ c.delivered ? t('account.admin.delivered') : t('account.admin.notDelivered') }} - -
-

{{ c.subject }}

-

{{ c.message }}

-

{{ formatDate(c.createdAt) }}

-
-
-
- -
-

{{ t('account.admin.subscribers') }}

-

{{ t('account.admin.emptySubscribers') }}

-
-
- {{ s.email }} - {{ formatDate(s.createdAt) }} -
-
-
-
@@ -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([]) +interface FavedWork { slug: string; titleZh: string; titleEn: string; image: string | null } +const favorites = ref([]) +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('/api/account/admin') - adminData.contacts = data.contacts - adminData.subscribers = data.subscribers - } catch (err) { - console.error('load admin error:', err) - } -} - // ---- 页面进场动画 ---- const mainRef = ref(null) let ctx: gsap.Context | null = null diff --git a/app/pages/admin/comments.vue b/app/pages/admin/comments.vue new file mode 100644 index 0000000..76d8ab8 --- /dev/null +++ b/app/pages/admin/comments.vue @@ -0,0 +1,208 @@ + + + diff --git a/app/pages/admin/contacts.vue b/app/pages/admin/contacts.vue new file mode 100644 index 0000000..5c9eeef --- /dev/null +++ b/app/pages/admin/contacts.vue @@ -0,0 +1,175 @@ + + + diff --git a/app/pages/admin/index.vue b/app/pages/admin/index.vue new file mode 100644 index 0000000..13e65fc --- /dev/null +++ b/app/pages/admin/index.vue @@ -0,0 +1,135 @@ + + + diff --git a/app/pages/admin/news.vue b/app/pages/admin/news.vue new file mode 100644 index 0000000..e612e8f --- /dev/null +++ b/app/pages/admin/news.vue @@ -0,0 +1,533 @@ + + + diff --git a/app/pages/admin/subscribers.vue b/app/pages/admin/subscribers.vue new file mode 100644 index 0000000..1b406e7 --- /dev/null +++ b/app/pages/admin/subscribers.vue @@ -0,0 +1,171 @@ + + + diff --git a/app/pages/admin/users.vue b/app/pages/admin/users.vue new file mode 100644 index 0000000..d6fa44f --- /dev/null +++ b/app/pages/admin/users.vue @@ -0,0 +1,212 @@ + + + diff --git a/app/pages/admin/work.vue b/app/pages/admin/work.vue new file mode 100644 index 0000000..d96b27a --- /dev/null +++ b/app/pages/admin/work.vue @@ -0,0 +1,709 @@ + + + diff --git a/app/pages/news/[slug].vue b/app/pages/news/[slug].vue index ecc3dd4..f976a14 100644 --- a/app/pages/news/[slug].vue +++ b/app/pages/news/[slug].vue @@ -14,7 +14,7 @@
@@ -23,7 +23,7 @@
{{ t(`news.categories.${article.category}`) }} @@ -48,41 +48,38 @@
- +
-

- {{ t(`news.detail.items.${slug}.content`) }} -

+
@@ -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" >
- +
{{ formatNewsDate(related.date, locale) }}

- {{ t(`news.items.${related.slug}.title`) }} + {{ locText(related.titleZh, related.titleEn) }}

@@ -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(() => 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 = { + 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), }) // ---- 分享(真实动作) ---- diff --git a/app/pages/news/index.vue b/app/pages/news/index.vue index 5f827bc..468b416 100644 --- a/app/pages/news/index.vue +++ b/app/pages/news/index.vue @@ -58,15 +58,15 @@ >
{{ t(`news.categories.${article.category}`) }} @@ -86,11 +86,11 @@

- {{ t(`news.items.${article.slug}.title`) }} + {{ locText(article.titleZh, article.titleEn) }}

- {{ t(`news.items.${article.slug}.excerpt`) }} + {{ locText(article.excerptZh, article.excerptEn) }}

@@ -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 = { + insights: 'bg-purple-100 text-purple-700', + projects: 'bg-blue-100 text-blue-700', + announcements: 'bg-green-100 text-green-700', +} + const headerWrapRef = ref(null) const titleRef = ref(null) const descRef = ref(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) }) }) diff --git a/app/pages/work/[slug].vue b/app/pages/work/[slug].vue index 32a141a..f4c8925 100644 --- a/app/pages/work/[slug].vue +++ b/app/pages/work/[slug].vue @@ -14,7 +14,7 @@
@@ -34,7 +34,7 @@ {{ title }}

- {{ t(`work.items.${slug}.description`) }} + {{ description }}

@@ -48,26 +48,26 @@

{{ t('work.detail.overview') }}

- {{ t(`work.detail.items.${slug}.overview`) }} + {{ locText(project.overviewZh, project.overviewEn) }}

{{ t('work.detail.challenge') }}

- {{ t(`work.detail.items.${slug}.challenge`) }} + {{ locText(project.challengeZh, project.challengeEn) }}

{{ t('work.detail.solution') }}

- {{ t(`work.detail.items.${slug}.solution`) }} + {{ locText(project.solutionZh, project.solutionEn) }}

-
+

{{ t('work.detail.gallery') }}

{{ t('work.detail.client') }}

-

{{ t(`work.detail.items.${slug}.client`) }}

+

{{ locText(project.clientZh, project.clientEn) }}

{{ t('work.detail.year') }}

@@ -97,7 +97,7 @@

{{ t('work.detail.duration') }}

-

{{ t(`work.detail.items.${slug}.duration`) }}

+

{{ locText(project.durationZh, project.durationEn) }}

{{ t('work.detail.services') }}

@@ -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" >
- +
-

{{ t(`work.items.${related.slug}.title`) }}

-

{{ related.tags[0] }}

+

{{ locText(related.titleZh, related.titleEn) }}

+

{{ related.tags?.[0] }}

@@ -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(() => 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, }) diff --git a/app/pages/work/index.vue b/app/pages/work/index.vue index d1e0b18..f9e7f03 100644 --- a/app/pages/work/index.vue +++ b/app/pages/work/index.vue @@ -58,8 +58,8 @@ >
@@ -69,13 +69,13 @@

- {{ t(`work.items.${project.slug}.title`) }} + {{ locText(project.titleZh, project.titleEn) }}

-

{{ t(`work.items.${project.slug}.description`) }}

+

{{ locText(project.descriptionZh, project.descriptionEn) }}

('/api/work') +const works = computed(() => data.value?.works ?? []) + +// 双语选择:切换语言即时生效 +const locText = (zh: string, en: string) => (locale.value === 'zh' ? zh : en) + const headerWrapRef = ref(null) const titleRef = ref(null) const descRef = ref(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) }) }) diff --git a/app/plugins/auth.client.ts b/app/plugins/auth.client.ts new file mode 100644 index 0000000..624a8e3 --- /dev/null +++ b/app/plugins/auth.client.ts @@ -0,0 +1,10 @@ +import { defineNuxtPlugin } from '#app' + +/** + * 客户端启动时从服务端会话恢复登录状态(在路由守卫前完成, + * 保证 admin 中间件与 /account 页能立即拿到真实用户)。 + */ +export default defineNuxtPlugin(async () => { + const userStore = useUserStore() + await userStore.restoreUser() +}) diff --git a/deploy.sh b/deploy.sh index 7d6a3fe..e4bfd47 100755 --- a/deploy.sh +++ b/deploy.sh @@ -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}" \ diff --git a/i18n/locales/en.json b/i18n/locales/en.json index af074b1..935978b 100755 --- a/i18n/locales/en.json +++ b/i18n/locales/en.json @@ -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", diff --git a/i18n/locales/zh.json b/i18n/locales/zh.json index 5e01efb..bf61d45 100755 --- a/i18n/locales/zh.json +++ b/i18n/locales/zh.json @@ -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": "评论", diff --git a/nuxt.config.ts b/nuxt.config.ts index 328459d..59b2ce4 100755 --- a/nuxt.config.ts +++ b/nuxt.config.ts @@ -32,6 +32,7 @@ export default defineNuxtConfig({ smtpFrom: '', contactTo: '', adminEmails: '', + adminInitialPassword: '', public: { // 客户端可见(环境变量:NUXT_PUBLIC_SITE_URL),用于 sitemap/robots/og 等绝对链接 siteUrl: '', diff --git a/scripts/generate-seed.mjs b/scripts/generate-seed.mjs new file mode 100644 index 0000000..948fcfa --- /dev/null +++ b/scripts/generate-seed.mjs @@ -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`) diff --git a/server/api/account/admin.get.ts b/server/api/account/admin.get.ts deleted file mode 100644 index 70bad32..0000000 --- a/server/api/account/admin.get.ts +++ /dev/null @@ -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 } -}) diff --git a/server/api/admin/articles.get.ts b/server/api/admin/articles.get.ts new file mode 100644 index 0000000..6c922d1 --- /dev/null +++ b/server/api/admin/articles.get.ts @@ -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 }) } +}) diff --git a/server/api/admin/articles.post.ts b/server/api/admin/articles.post.ts new file mode 100644 index 0000000..0c8611e --- /dev/null +++ b/server/api/admin/articles.post.ts @@ -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 }) } +}) diff --git a/server/api/admin/articles/[id].delete.ts b/server/api/admin/articles/[id].delete.ts new file mode 100644 index 0000000..cb48417 --- /dev/null +++ b/server/api/admin/articles/[id].delete.ts @@ -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 } +}) diff --git a/server/api/admin/articles/[id].patch.ts b/server/api/admin/articles/[id].patch.ts new file mode 100644 index 0000000..69ed000 --- /dev/null +++ b/server/api/admin/articles/[id].patch.ts @@ -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 = { + titleZh: 'title_zh', titleEn: 'title_en', + excerptZh: 'excerpt_zh', excerptEn: 'excerpt_en', + image: 'image', date: 'date', author: 'author', + } + return map[field] +} diff --git a/server/api/admin/comments.get.ts b/server/api/admin/comments.get.ts new file mode 100644 index 0000000..b10e744 --- /dev/null +++ b/server/api/admin/comments.get.ts @@ -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 } +}) diff --git a/server/api/admin/comments/[id].delete.ts b/server/api/admin/comments/[id].delete.ts new file mode 100644 index 0000000..b5e44c9 --- /dev/null +++ b/server/api/admin/comments/[id].delete.ts @@ -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 } +}) diff --git a/server/api/admin/contacts.get.ts b/server/api/admin/contacts.get.ts new file mode 100644 index 0000000..65961b3 --- /dev/null +++ b/server/api/admin/contacts.get.ts @@ -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 } +}) diff --git a/server/api/admin/contacts/[id].delete.ts b/server/api/admin/contacts/[id].delete.ts new file mode 100644 index 0000000..2eeb142 --- /dev/null +++ b/server/api/admin/contacts/[id].delete.ts @@ -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 } +}) diff --git a/server/api/admin/stats.get.ts b/server/api/admin/stats.get.ts new file mode 100644 index 0000000..83a6ae9 --- /dev/null +++ b/server/api/admin/stats.get.ts @@ -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'), + } +}) diff --git a/server/api/admin/subscribers.get.ts b/server/api/admin/subscribers.get.ts new file mode 100644 index 0000000..c5bd49d --- /dev/null +++ b/server/api/admin/subscribers.get.ts @@ -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 } +}) diff --git a/server/api/admin/subscribers/[id].delete.ts b/server/api/admin/subscribers/[id].delete.ts new file mode 100644 index 0000000..1f42424 --- /dev/null +++ b/server/api/admin/subscribers/[id].delete.ts @@ -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 } +}) diff --git a/server/api/admin/subscribers/export.get.ts b/server/api/admin/subscribers/export.get.ts new file mode 100644 index 0000000..c2422ce --- /dev/null +++ b/server/api/admin/subscribers/export.get.ts @@ -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"`, + }, + }) +}) diff --git a/server/api/admin/upload.post.ts b/server/api/admin/upload.post.ts new file mode 100644 index 0000000..d3c5742 --- /dev/null +++ b/server/api/admin/upload.post.ts @@ -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 = { + 'image/png': 'png', + 'image/jpeg': 'jpg', + 'image/gif': 'gif', + 'image/webp': 'webp', + 'image/svg+xml': 'svg', + 'image/avif': 'avif', +} + +/** + * 后台图片上传 -> 保存到 PVC 的 uploads 目录(/data/uploads), + * 通过 /uploads/ 对外提供。 + */ +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}` } +}) diff --git a/server/api/admin/users.get.ts b/server/api/admin/users.get.ts new file mode 100644 index 0000000..39efa57 --- /dev/null +++ b/server/api/admin/users.get.ts @@ -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 } +}) diff --git a/server/api/admin/users/[id].delete.ts b/server/api/admin/users/[id].delete.ts new file mode 100644 index 0000000..5b235f9 --- /dev/null +++ b/server/api/admin/users/[id].delete.ts @@ -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 } +}) diff --git a/server/api/admin/users/[id].patch.ts b/server/api/admin/users/[id].patch.ts new file mode 100644 index 0000000..9cb9aa9 --- /dev/null +++ b/server/api/admin/users/[id].patch.ts @@ -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 } +}) diff --git a/server/api/admin/works.get.ts b/server/api/admin/works.get.ts new file mode 100644 index 0000000..bcb580b --- /dev/null +++ b/server/api/admin/works.get.ts @@ -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 }) } +}) diff --git a/server/api/admin/works.post.ts b/server/api/admin/works.post.ts new file mode 100644 index 0000000..019986e --- /dev/null +++ b/server/api/admin/works.post.ts @@ -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 }) } +}) diff --git a/server/api/admin/works/[id].delete.ts b/server/api/admin/works/[id].delete.ts new file mode 100644 index 0000000..b692945 --- /dev/null +++ b/server/api/admin/works/[id].delete.ts @@ -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 } +}) diff --git a/server/api/admin/works/[id].patch.ts b/server/api/admin/works/[id].patch.ts new file mode 100644 index 0000000..242ab13 --- /dev/null +++ b/server/api/admin/works/[id].patch.ts @@ -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 = { + 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] +} diff --git a/server/api/auth/register.post.ts b/server/api/auth/register.post.ts index 07f78a6..e995b8e 100644 --- a/server/api/auth/register.post.ts +++ b/server/api/auth/register.post.ts @@ -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 = ?') diff --git a/server/api/comments.get.ts b/server/api/comments.get.ts index 0c74ee5..295e91c 100644 --- a/server/api/comments.get.ts +++ b/server/api/comments.get.ts @@ -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' } }) } diff --git a/server/api/comments.post.ts b/server/api/comments.post.ts index 5d93a14..fb0358a 100644 --- a/server/api/comments.post.ts +++ b/server/api/comments.post.ts @@ -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) { diff --git a/server/api/favorites.post.ts b/server/api/favorites.post.ts index f24ab4f..e641472 100644 --- a/server/api/favorites.post.ts +++ b/server/api/favorites.post.ts @@ -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' } }) } diff --git a/server/api/news.get.ts b/server/api/news.get.ts new file mode 100644 index 0000000..6f5bb79 --- /dev/null +++ b/server/api/news.get.ts @@ -0,0 +1,8 @@ +import { listArticles } from '../utils/content' + +/** + * 动态列表(前台,仅已发布) + */ +export default defineEventHandler(() => { + return { articles: listArticles({ publishedOnly: true }) } +}) diff --git a/server/api/news/[slug].get.ts b/server/api/news/[slug].get.ts new file mode 100644 index 0000000..0142056 --- /dev/null +++ b/server/api/news/[slug].get.ts @@ -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 } +}) diff --git a/server/api/work.get.ts b/server/api/work.get.ts new file mode 100644 index 0000000..a62e10c --- /dev/null +++ b/server/api/work.get.ts @@ -0,0 +1,8 @@ +import { listWorks } from '../utils/content' + +/** + * 作品列表(前台,仅已发布) + */ +export default defineEventHandler(() => { + return { works: listWorks({ publishedOnly: true }) } +}) diff --git a/server/api/work/[slug].get.ts b/server/api/work/[slug].get.ts new file mode 100644 index 0000000..5548f19 --- /dev/null +++ b/server/api/work/[slug].get.ts @@ -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 } +}) diff --git a/server/routes/sitemap.xml.ts b/server/routes/sitemap.xml.ts index c493a0b..c56a1f2 100644 --- a/server/routes/sitemap.xml.ts +++ b/server/routes/sitemap.xml.ts @@ -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' }) } diff --git a/server/routes/uploads/[...path].get.ts b/server/routes/uploads/[...path].get.ts new file mode 100644 index 0000000..06a5709 --- /dev/null +++ b/server/routes/uploads/[...path].get.ts @@ -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 = { + 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', + }, + }) +}) diff --git a/server/utils/auth.ts b/server/utils/auth.ts index 505bbc2..f41550d 100644 --- a/server/utils/auth.ts +++ b/server/utils/auth.ts @@ -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, } } diff --git a/server/utils/config.ts b/server/utils/config.ts index a678d3b..b40a299 100644 --- a/server/utils/config.ts +++ b/server/utils/config.ts @@ -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(/\/$/, ''), } } diff --git a/server/utils/content.ts b/server/utils/content.ts new file mode 100644 index 0000000..61af0f6 --- /dev/null +++ b/server/utils/content.ts @@ -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 = (value: string | null, fallback: T): T => { + if (!value) return fallback + try { + return JSON.parse(value) as T + } catch { + return fallback + } +} + +function rowToArticle(row: Record): 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(String(row.content_zh ?? ''), []), + contentEn: parseJson(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): 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(row.tags ?? ''), []), + image: row.image ? String(row.image) : null, + gallery: parseJson(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> + 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 | 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> + 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 | 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'), + } +} diff --git a/server/utils/db.ts b/server/utils/db.ts index a6422c7..6f70923 100644 --- a/server/utils/db.ts +++ b/server/utils/db.ts @@ -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) { diff --git a/server/utils/seed.ts b/server/utils/seed.ts new file mode 100644 index 0000000..73421f8 --- /dev/null +++ b/server/utils/seed.ts @@ -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 + } +] diff --git a/server/utils/validateContent.ts b/server/utils/validateContent.ts new file mode 100644 index 0000000..d62b8b2 --- /dev/null +++ b/server/utils/validateContent.ts @@ -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) +}