feat: 全量落地后端与功能闭环
- 真实后端(server/):SQLite 存储 + scrypt 会话鉴权 + SMTP 邮件 - auth 注册/登录/登出/me/资料更新 - contact 联系表单(落库+邮件)、newsletter 订阅(去重) - favorites 作品收藏、comments 新闻评论、account 管理收件箱 - 用户系统 UI:个人中心 /account(资料/收藏/评论/管理员面板)、 收藏按钮、评论组件、登录/注册弹窗接真实 API(useApiError 错误映射) - 内容单点事实源:app/data/news|work 消除三处重复,页面全部引用 - 修复断链:首页动态/作品卡可点击、分享按钮真实动作、移除 # 死链、 语言切换器、社交链接统一 siteConfig - SEO:动态 sitemap/robots、JSON-LD、脚本生成真实 og-image.png - 列表增强:搜索 + 加载更多 - 部署自动化:build-and-push.sh 支持 git tag 版本化镜像; deploy.sh 一条命令构建推送+注入 Secret/ConfigMap+kubectl 滚动升级; deployment 挂 PVC 持久化;Dockerfile 支持 better-sqlite3 原生编译 - 组件注册去目录前缀,修复 AppLoader/AnimatedButton 等未渲染问题
This commit is contained in:
+6
-1
@@ -1,10 +1,15 @@
|
||||
# 依赖目录
|
||||
node_modules/
|
||||
pnpm-workspace.yaml
|
||||
|
||||
# 编译产出目录
|
||||
.output/
|
||||
.nuxt/
|
||||
.nitro/
|
||||
.cache/
|
||||
dist/
|
||||
|
||||
# 本地数据(开发数据库,不进镜像)
|
||||
.data/
|
||||
|
||||
# 环境变量文件(通常不应该被打包进去)
|
||||
.env
|
||||
|
||||
@@ -0,0 +1,29 @@
|
||||
# =========================================================
|
||||
# Arcticnewone 本地开发环境变量示例
|
||||
# 复制为 .env 使用(.env 已被 gitignore,不会提交)
|
||||
#
|
||||
# Nuxt runtimeConfig 的环境变量映射约定:一律使用 NUXT_ 前缀
|
||||
# =========================================================
|
||||
|
||||
# 站点公开地址(用于 sitemap/robots/og 等绝对链接)
|
||||
NUXT_PUBLIC_SITE_URL=https://personal.virtheart.com
|
||||
|
||||
# 会话安全密钥(生产必须设置为高强度随机值)
|
||||
# 生成方式: node -e "console.log(require('crypto').randomBytes(48).toString('hex'))"
|
||||
NUXT_SESSION_SECRET=dev-change-me-to-a-long-random-string
|
||||
|
||||
# 数据文件路径(默认:生产 /data/arcticnewone.db,开发 .data/arcticnewone.db)
|
||||
# NUXT_DB_PATH=/data/arcticnewone.db
|
||||
|
||||
# ---- SMTP 邮件(可选)----
|
||||
# 未配置时:联系表单与邮箱订阅仍会真实写入数据库,但不会发送邮件
|
||||
NUXT_SMTP_HOST=
|
||||
NUXT_SMTP_PORT=587
|
||||
NUXT_SMTP_USER=
|
||||
NUXT_SMTP_PASS=
|
||||
NUXT_SMTP_FROM=
|
||||
# 联系表单留言的接收邮箱
|
||||
NUXT_CONTACT_TO=chenchun@virtheart.com
|
||||
|
||||
# 管理员邮箱(逗号分隔),命中邮箱的用户在个人中心显示管理面板
|
||||
NUXT_ADMIN_EMAILS=chenchun@virtheart.com
|
||||
+7
-4
@@ -4,16 +4,19 @@
|
||||
# 使用国内可访问的 DaoCloud 镜像源(Docker Hub 在国内不可达)
|
||||
FROM docker.m.daocloud.io/library/node:22-alpine AS builder
|
||||
|
||||
# 启用 corepack 并安装 pnpm
|
||||
RUN corepack enable && corepack prepare pnpm@9 --activate
|
||||
# 启用 corepack 并安装 pnpm(与本地 pnpm 11 保持一致,兼容 pnpm-workspace.yaml 配置)
|
||||
RUN corepack enable && corepack prepare pnpm@11 --activate
|
||||
|
||||
# 安装原生模块编译依赖(better-sqlite3 等,构建期兜底;产物无需运行期依赖)
|
||||
RUN apk add --no-cache python3 make g++
|
||||
|
||||
# 设置工作目录
|
||||
WORKDIR /app
|
||||
|
||||
# 复制依赖相关文件
|
||||
COPY package.json pnpm-lock.yaml ./
|
||||
COPY package.json pnpm-lock.yaml pnpm-workspace.yaml ./
|
||||
|
||||
# 安装依赖项
|
||||
# 安装依赖项(含原生模块编译;build 需要 devDependencies,故安装全部)
|
||||
RUN pnpm install --frozen-lockfile
|
||||
|
||||
# 复制项目源代码
|
||||
|
||||
@@ -1,15 +1,17 @@
|
||||
# Arcticnewone 个人网站
|
||||
|
||||
北极新一(Arcticnewone)的个人网站,提供个人介绍、作品集、工作室服务、动态资讯、工具箱与联系页面,是一个现代化的展示型站点。
|
||||
北极新一(Arcticnewone)的个人网站,提供个人介绍、作品集、工作室服务、动态资讯、工具箱与联系页面,是一个现代化的展示型站点。已内置**真实后端**(登录/注册、联系留言、邮箱订阅、作品收藏、新闻评论、管理员收件箱)与 **中英双语、SEO、搜索分页** 等完整功能。
|
||||
|
||||
## 技术栈
|
||||
|
||||
- [Nuxt 4](https://nuxt.com/) — 应用框架(服务端渲染 + 静态生成)
|
||||
- [Nuxt 4](https://nuxt.com/) — 应用框架(服务端渲染 + Nitro 后端 API)
|
||||
- [Vue 3](https://vuejs.org/) — 视图层
|
||||
- [Tailwind CSS](https://tailwindcss.com/) — 样式方案(通过 `@nuxtjs/tailwindcss` 集成)
|
||||
- [GSAP](https://gsap.com/) — 页面动画(配合 Lenis 平滑滚动)
|
||||
- [Pinia](https://pinia.vuejs.org/) — 状态管理
|
||||
- [@nuxtjs/i18n](https://i18n.nuxtjs.org/) — 国际化(中/英双语)
|
||||
- [better-sqlite3](https://github.com/WiseLibs/better-sqlite3) — 数据存储(SQLite,K8s PVC 持久化)
|
||||
- [nodemailer](https://nodemailer.com/) — 邮件发送(SMTP)
|
||||
- [@nuxt/icon](https://nuxt.com/modules/icon) — 图标
|
||||
- [pnpm](https://pnpm.io/) — 包管理器
|
||||
|
||||
@@ -26,7 +28,10 @@
|
||||
# 1. 安装依赖
|
||||
pnpm install
|
||||
|
||||
# 2. 启动开发服务器(默认 http://localhost:3000)
|
||||
# 2. 配置环境变量(可选,SMTP 未配置时联系/订阅仍会真实落库)
|
||||
cp .env.example .env
|
||||
|
||||
# 3. 启动开发服务器(默认 http://localhost:3000)
|
||||
pnpm dev
|
||||
```
|
||||
|
||||
@@ -42,64 +47,101 @@ pnpm dev
|
||||
| `pnpm preview` | 本地预览生产构建 |
|
||||
| `pnpm start` | 以 Node 方式启动 `.output/server/index.mjs` |
|
||||
|
||||
## 功能一览
|
||||
|
||||
| 模块 | 说明 |
|
||||
| --- | --- |
|
||||
| 页面 | 首页、工作室、作品(列表/详情)、动态(列表/详情)、工具箱、联系、个人中心 |
|
||||
| 用户系统 | 真实注册/登录/登出(scrypt 密码哈希 + httpOnly Cookie 会话) |
|
||||
| 个人中心 | `/account`:资料编辑、作品收藏、我的评论;管理员可见联系/订阅收件箱 |
|
||||
| 交互 | 作品收藏、新闻评论、分享(X/LinkedIn/复制链接)、搜索、加载更多 |
|
||||
| 国际化 | 中/英双语,Header 一键切换(`no_prefix`,默认中文) |
|
||||
| SEO | 动态 `sitemap.xml` / `robots.txt`、JSON-LD、自动生成的 `og-image.png` |
|
||||
| 邮件 | SMTP 发送联系/订阅邮件;未配置 SMTP 时数据仍真实写入 SQLite |
|
||||
|
||||
### 环境变量(详见 `.env.example`,Nuxt runtimeConfig 使用 `NUXT_` 前缀)
|
||||
|
||||
| 变量 | 说明 |
|
||||
| --- | --- |
|
||||
| `NUXT_PUBLIC_SITE_URL` | 站点公开地址(sitemap/robots/og 绝对链接) |
|
||||
| `NUXT_SESSION_SECRET` | 会话安全密钥(生产必须设置强随机值) |
|
||||
| `NUXT_DB_PATH` | 数据库文件路径(默认生产 `/data/arcticnewone.db`,开发 `.data/`) |
|
||||
| `NUXT_SMTP_HOST/PORT/USER/PASS/FROM` | SMTP 邮件服务(可选) |
|
||||
| `NUXT_CONTACT_TO` | 联系表单留言收件邮箱 |
|
||||
| `NUXT_ADMIN_EMAILS` | 管理员邮箱(逗号分隔),命中者个人中心可见管理面板 |
|
||||
|
||||
> `deploy.sh` 中的对外变量名(`SESSION_SECRET`/`SMTP_*`/`CONTACT_TO`/`ADMIN_EMAILS`)会在写入 K8s Secret 时自动加 `NUXT_` 前缀。
|
||||
|
||||
## 项目结构
|
||||
|
||||
```text
|
||||
.
|
||||
├── app/ # 应用源码(Nuxt 4 约定目录)
|
||||
│ ├── app.vue # 应用入口(全局 SEO / Meta)
|
||||
│ ├── assets/ # 静态资源(样式、图片等)
|
||||
│ ├── components/ # 组件(common / home)
|
||||
│ ├── composables/ # 组合式函数
|
||||
│ ├── layouts/ # 布局
|
||||
│ ├── pages/ # 页面(首页、工作室、作品、动态、工具、联系)
|
||||
│ ├── plugins/ # 插件(如 Lenis 平滑滚动)
|
||||
│ ├── stores/ # Pinia 状态
|
||||
│ └── types/ # 类型定义
|
||||
├── i18n/
|
||||
│ └── locales/ # 国际化文案(zh.json / en.json)
|
||||
├── public/ # 公开静态文件(favicon、robots.txt 等)
|
||||
├── Dockerfile # 容器镜像构建
|
||||
├── deploy/ # 生产部署配置(Kubernetes Deployment/Service/Ingress)
|
||||
├── docker-compose.yml # 本地容器编排(使用 SWR 镜像)
|
||||
├── nuxt.config.ts # Nuxt 配置(模块、i18n、Tailwind 等)
|
||||
├── tailwind.config.js # Tailwind 配置
|
||||
└── package.json # 项目依赖与脚本
|
||||
│ ├── app.vue # 应用入口(全局 SEO / Meta / JSON-LD)
|
||||
│ ├── config/ # 站点配置(品牌、邮箱、社交链接)
|
||||
│ ├── data/ # 内容单一事实源(news / work,列表/详情/首页共用)
|
||||
│ ├── pages/ # 页面(含 account.vue 个人中心)
|
||||
│ ├── components/ # 组件(common / home / layouts)
|
||||
│ ├── stores/ # Pinia 状态(用户、认证弹窗)
|
||||
│ └── ...
|
||||
├── server/ # Nitro 后端(utils 数据/鉴权/邮件 + api 路由 + sitemap/robots)
|
||||
├── i18n/locales/ # 国际化文案(zh.json / en.json)
|
||||
├── scripts/ # 工具脚本(generate-og.mjs 生成分享图)
|
||||
├── public/ # 公开静态文件
|
||||
├── deploy/ # 生产部署配置(K8s)
|
||||
├── deploy.sh # 一条命令部署 / 升级
|
||||
├── build-and-push.sh # 版本化镜像构建推送(SWR)
|
||||
└── Dockerfile
|
||||
```
|
||||
|
||||
## 构建与部署
|
||||
## 构建与部署(一条命令)
|
||||
|
||||
构建并推送镜像:
|
||||
镜像版本取自 git tag(如 `0.0.1-dev` → `:0.0.1-dev`,同时更新 `:latest`),构建后推送华为云 SWR。
|
||||
|
||||
> SWR 兼容性:华为云 SWR 无法解析 Docker manifest list(多架构合并会报 `Invalid image`),
|
||||
> 因此版本 tag 与 `latest` 以 **amd64 单架构 manifest** 输出(生产集群为 amd64);
|
||||
> 同时分架构推送 `-amd64`/`-arm64` 标签,arm64 环境可按需使用。
|
||||
|
||||
```bash
|
||||
./build-and-push.sh
|
||||
# 1. 打版本标签
|
||||
git add -A && git commit -m "release: 0.0.1-dev"
|
||||
git tag 0.0.1-dev
|
||||
|
||||
# 2. 设置环境变量(凭据绝不写入仓库)
|
||||
export SWR_REGISTRY="swr.cn-north-4.myhuaweicloud.com"
|
||||
export SWR_NAMESPACE="virtheart"
|
||||
export SWR_USERNAME="<用户名>"
|
||||
export SWR_PASSWORD="<密码>"
|
||||
# 可选:export SESSION_SECRET="$(openssl rand -hex 32)" / SMTP_* / CONTACT_TO / ADMIN_EMAILS
|
||||
|
||||
# 3. 一条命令:构建镜像 + 推送 + 更新集群 + 滚动升级
|
||||
./deploy.sh 0.0.1-dev # 不带参数则自动取最新 git tag
|
||||
```
|
||||
|
||||
脚本从环境变量读取 SWR 凭据(`SWR_REGISTRY`、`SWR_NAMESPACE`、`SWR_USERNAME`、`SWR_PASSWORD`),
|
||||
多架构(`linux/amd64,linux/arm64`)构建并推送到华为云 SWR:分架构推送后用 `docker manifest` 合并为 `latest`(标准 Docker manifest list,SWR 可正常解析)。
|
||||
`deploy.sh` 自动完成:构建推送版本化镜像 → 注入 Secret(会话密钥/SMTP/管理员)与 ConfigMap(站点地址/DB 路径)→ `kubectl apply`(namespace/PVC/Deployment/Service/Ingress)→ 等待滚动更新 → 健康检查。
|
||||
|
||||
Dockerfile 基础镜像使用国内可访问的 DaoCloud 镜像源(`docker.m.daocloud.io/library/node:22-alpine`,Docker Hub 在国内不可达)。
|
||||
|
||||
本地启动(使用 SWR 镜像,与生产一致):
|
||||
### 仅构建镜像(不部署)
|
||||
|
||||
```bash
|
||||
docker compose up -d
|
||||
./build-and-push.sh # 版本取最新 git tag
|
||||
./build-and-push.sh 0.0.1-dev # 显式指定版本
|
||||
```
|
||||
|
||||
生产部署使用 `deploy/` 目录下的 Kubernetes 配置(Deployment / Service / Ingress),
|
||||
镜像统一推送到华为云 SWR(`swr.cn-north-4.myhuaweicloud.com/virtheart/arcticnewone:latest`),
|
||||
部署与回滚步骤见 [deploy/README.md](deploy/README.md)。
|
||||
### 生产部署说明
|
||||
|
||||
- 域名 `personal.virtheart.com`,Traefik Ingress + cert-manager 自动签发证书
|
||||
- SQLite 数据持久化在 PVC `arcticnewone-data`(挂载 `/data`),Pod 升级/重启不丢数据
|
||||
- 回滚:`kubectl rollout undo deployment/arcticnewone -n arcticnewone`
|
||||
- 详见 [deploy/README.md](deploy/README.md)
|
||||
|
||||
## 国际化(i18n)
|
||||
|
||||
项目使用 `@nuxtjs/i18n` 实现中/英双语:
|
||||
|
||||
- 语言文件位于 `i18n/locales/`:`zh.json`(中文)、`en.json`(英文)
|
||||
- 默认语言为中文(`defaultLocale: 'zh'`),URL 不包含语言前缀(`strategy: 'no_prefix'`),不自动探测浏览器语言
|
||||
- 组件中通过 `useI18n()` 的 `t()` 方法读取文案,例如 `t('nav.home')`
|
||||
|
||||
新增文案时,在 `zh.json` 和 `en.json` 中同步添加对应键即可。
|
||||
- 默认语言为中文(`defaultLocale: 'zh'`),URL 不包含语言前缀(`strategy: 'no_prefix'`),Header 提供中/EN 切换
|
||||
- 组件中通过 `useI18n()` 的 `t()` 方法读取文案;新增文案时同步更新两个语言文件(可用根目录脚本校验键对齐)
|
||||
|
||||
## 说明
|
||||
|
||||
本项目不含任何密钥或敏感信息;本地环境变量请使用 `.env` 文件(已被 `.gitignore` 忽略)。
|
||||
- 本项目不含任何密钥或敏感信息;本地环境变量请使用 `.env` 文件(已被 `.gitignore` 忽略)
|
||||
- 联系/订阅依赖 SMTP:未配置时数据仍真实写入数据库,仅在管理面板可见但不会发邮件
|
||||
- 社交链接为品牌占位地址(`app/config/site.ts`),正式上线前请替换为真实账号
|
||||
|
||||
+23
-3
@@ -1,18 +1,37 @@
|
||||
<script setup lang="ts">
|
||||
import { useHead, useSeoMeta } from '#imports'
|
||||
import { useHead, useSeoMeta, useRuntimeConfig } from '#imports'
|
||||
import { useI18n } from 'vue-i18n'
|
||||
import { siteConfig } from '~/config/site'
|
||||
|
||||
const { t } = useI18n()
|
||||
const { public: publicCfg } = useRuntimeConfig()
|
||||
const baseUrl = String(publicCfg.siteUrl || '').replace(/\/$/, '')
|
||||
|
||||
// 站点通用基础信息
|
||||
const siteImage = '/og-image.png'
|
||||
const siteImage = baseUrl ? `${baseUrl}/og-image.png` : '/og-image.png'
|
||||
|
||||
// 配置全局 Title 模板
|
||||
useHead({
|
||||
titleTemplate: (titleChunk?: string) => {
|
||||
const siteName = t('app.name')
|
||||
return titleChunk ? `${titleChunk} - ${siteName}` : siteName
|
||||
}
|
||||
},
|
||||
// JSON-LD 结构化数据(Organization)
|
||||
script: [
|
||||
{
|
||||
type: 'application/ld+json',
|
||||
innerHTML: JSON.stringify({
|
||||
'@context': 'https://schema.org',
|
||||
'@type': 'Organization',
|
||||
name: t('app.name'),
|
||||
alternateName: siteConfig.brandZh,
|
||||
description: t('app.description'),
|
||||
url: baseUrl || undefined,
|
||||
logo: siteImage,
|
||||
sameAs: siteConfig.socials.map((s) => s.url),
|
||||
}),
|
||||
},
|
||||
],
|
||||
})
|
||||
|
||||
// 配置全局基础 SEO 和 Meta (响应式支持国际化)
|
||||
@@ -21,6 +40,7 @@ useSeoMeta({
|
||||
ogTitle: () => t('app.name'),
|
||||
ogDescription: () => t('app.description'),
|
||||
ogImage: siteImage,
|
||||
ogType: 'website',
|
||||
twitterCard: 'summary_large_image',
|
||||
twitterTitle: () => t('app.name'),
|
||||
twitterDescription: () => t('app.description'),
|
||||
|
||||
@@ -0,0 +1,154 @@
|
||||
<template>
|
||||
<section class="mt-16">
|
||||
<h2 class="text-2xl md:text-3xl font-bold text-black mb-8">{{ t('comments.title') }}</h2>
|
||||
|
||||
<!-- 登录提示 -->
|
||||
<div
|
||||
v-if="!userStore.isAuthenticated"
|
||||
class="p-6 rounded-2xl bg-gray-50 border border-gray-200 text-center"
|
||||
>
|
||||
<p class="text-gray-600 mb-4">{{ t('comments.loginToComment') }}</p>
|
||||
<button
|
||||
@click="authModal.openLogin()"
|
||||
class="px-6 py-2.5 rounded-full bg-black text-white text-sm font-semibold hover:bg-gray-800 transition-colors"
|
||||
>
|
||||
{{ t('auth.login') }}
|
||||
</button>
|
||||
</div>
|
||||
|
||||
<!-- 评论表单(已登录) -->
|
||||
<form v-else @submit.prevent="handleSubmit" class="mb-10">
|
||||
<div class="flex items-start gap-4">
|
||||
<img
|
||||
:src="userStore.avatar"
|
||||
:alt="userStore.user?.username"
|
||||
class="w-10 h-10 rounded-full object-cover flex-shrink-0"
|
||||
/>
|
||||
<div class="flex-1">
|
||||
<textarea
|
||||
v-model="content"
|
||||
rows="3"
|
||||
maxlength="2000"
|
||||
:placeholder="t('comments.placeholder')"
|
||||
:disabled="isSubmitting"
|
||||
class="w-full px-4 py-3 rounded-xl border border-gray-200 focus:border-black focus:ring-2 focus:ring-black/5 outline-none transition-all duration-300 resize-none disabled:opacity-50"
|
||||
></textarea>
|
||||
<div class="flex items-center justify-between mt-3">
|
||||
<span v-if="errorMessage" class="text-sm text-red-600">{{ errorMessage }}</span>
|
||||
<button
|
||||
type="submit"
|
||||
:disabled="isSubmitting || !content.trim()"
|
||||
class="ml-auto px-6 py-2.5 rounded-full bg-black text-white text-sm font-semibold flex items-center gap-2 transition-all"
|
||||
:class="isSubmitting || !content.trim() ? 'opacity-50 cursor-not-allowed' : 'hover:bg-gray-800'"
|
||||
>
|
||||
<Icon v-if="isSubmitting" name="ph:circle-notch" class="w-4 h-4 animate-spin" />
|
||||
{{ isSubmitting ? t('comments.submitting') : t('comments.submit') }}
|
||||
</button>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
</form>
|
||||
|
||||
<!-- 评论列表 -->
|
||||
<div v-if="comments.length" class="space-y-6">
|
||||
<div
|
||||
v-for="comment in comments"
|
||||
:key="comment.id"
|
||||
class="flex items-start gap-4 p-5 rounded-2xl bg-gray-50 border border-gray-100"
|
||||
>
|
||||
<img
|
||||
:src="avatarUrl(comment.author.username)"
|
||||
:alt="comment.author.username"
|
||||
class="w-10 h-10 rounded-full object-cover flex-shrink-0"
|
||||
/>
|
||||
<div class="flex-1 min-w-0">
|
||||
<div class="flex items-center justify-between gap-3 mb-1">
|
||||
<p class="text-sm font-semibold text-black">{{ comment.author.username }}</p>
|
||||
<p class="text-xs text-gray-400 shrink-0">{{ formatDate(comment.createdAt) }}</p>
|
||||
</div>
|
||||
<p class="text-gray-700 text-sm md:text-base leading-relaxed break-words">{{ comment.content }}</p>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
<div v-else-if="!loading && userStore.isAuthenticated" class="text-center text-gray-500 py-8">
|
||||
{{ t('comments.empty') }}
|
||||
</div>
|
||||
</section>
|
||||
</template>
|
||||
|
||||
<script setup lang="ts">
|
||||
import { ref, watch, onMounted } from 'vue'
|
||||
import { useI18n } from 'vue-i18n'
|
||||
import { useUserStore } from '~/stores/user'
|
||||
import { useAuthModalStore } from '~/stores/authModal'
|
||||
|
||||
const props = defineProps<{ newsSlug: string }>()
|
||||
|
||||
const { t, locale } = useI18n()
|
||||
const userStore = useUserStore()
|
||||
const authModal = useAuthModalStore()
|
||||
|
||||
interface CommentItem {
|
||||
id: number
|
||||
content: string
|
||||
createdAt: string
|
||||
author: { username: string }
|
||||
}
|
||||
|
||||
const comments = ref<CommentItem[]>([])
|
||||
const content = ref('')
|
||||
const isSubmitting = ref(false)
|
||||
const isLoading = ref(true)
|
||||
const errorMessage = ref('')
|
||||
|
||||
const avatarUrl = (name: string) =>
|
||||
`https://ui-avatars.com/api/?name=${encodeURIComponent(name)}&background=000&color=fff&size=128`
|
||||
|
||||
const formatDate = (raw: string) => {
|
||||
const d = new Date(String(raw).replace(' ', 'T') + 'Z')
|
||||
if (Number.isNaN(d.getTime())) return raw
|
||||
return new Intl.DateTimeFormat(locale.value === 'zh' ? 'zh-CN' : 'en-US', {
|
||||
year: 'numeric',
|
||||
month: 'short',
|
||||
day: 'numeric',
|
||||
hour: '2-digit',
|
||||
minute: '2-digit',
|
||||
}).format(d)
|
||||
}
|
||||
|
||||
const fetchComments = async () => {
|
||||
isLoading.value = true
|
||||
try {
|
||||
const data = await $fetch<{ comments: CommentItem[] }>('/api/comments', {
|
||||
query: { newsSlug: props.newsSlug },
|
||||
})
|
||||
comments.value = data.comments
|
||||
} catch (err) {
|
||||
console.error('fetch comments error:', err)
|
||||
} finally {
|
||||
isLoading.value = false
|
||||
}
|
||||
}
|
||||
|
||||
const handleSubmit = async () => {
|
||||
if (isSubmitting.value || !content.value.trim()) return
|
||||
isSubmitting.value = true
|
||||
errorMessage.value = ''
|
||||
try {
|
||||
await $fetch('/api/comments', {
|
||||
method: 'POST',
|
||||
body: { newsSlug: props.newsSlug, content: content.value.trim() },
|
||||
})
|
||||
content.value = ''
|
||||
await fetchComments()
|
||||
} catch (err) {
|
||||
console.error('post comment error:', err)
|
||||
errorMessage.value = t('comments.commentError')
|
||||
} finally {
|
||||
isSubmitting.value = false
|
||||
}
|
||||
}
|
||||
|
||||
onMounted(fetchComments)
|
||||
watch(() => props.newsSlug, fetchComments)
|
||||
</script>
|
||||
@@ -0,0 +1,71 @@
|
||||
<template>
|
||||
<button
|
||||
type="button"
|
||||
:disabled="isLoading"
|
||||
@click="toggle"
|
||||
class="inline-flex w-full items-center justify-center gap-2 px-6 py-3.5 rounded-full font-semibold transition-all duration-300"
|
||||
:class="isFavorite
|
||||
? 'bg-gray-100 text-black hover:bg-gray-200'
|
||||
: 'bg-black text-white hover:bg-gray-800'"
|
||||
>
|
||||
<Icon v-if="isLoading" name="ph:circle-notch" class="w-5 h-5 animate-spin" />
|
||||
<Icon v-else :name="isFavorite ? 'ph:bookmark-simple-fill' : 'ph:bookmark-simple'" class="w-5 h-5" />
|
||||
<span>{{ isFavorite ? t('favorites.remove') : t('favorites.add') }}</span>
|
||||
</button>
|
||||
</template>
|
||||
|
||||
<script setup lang="ts">
|
||||
import { ref, watch, onMounted } from 'vue'
|
||||
import { useI18n } from 'vue-i18n'
|
||||
import { useUserStore } from '~/stores/user'
|
||||
import { useAuthModalStore } from '~/stores/authModal'
|
||||
|
||||
const props = defineProps<{ workSlug: string }>()
|
||||
|
||||
const { t } = useI18n()
|
||||
const userStore = useUserStore()
|
||||
const authModal = useAuthModalStore()
|
||||
|
||||
const isFavorite = ref(false)
|
||||
const isLoading = ref(false)
|
||||
|
||||
// 已登录时同步收藏状态
|
||||
const refresh = async () => {
|
||||
if (!userStore.isAuthenticated) {
|
||||
isFavorite.value = false
|
||||
return
|
||||
}
|
||||
try {
|
||||
const data = await $fetch<{ slugs: string[] }>('/api/favorites')
|
||||
isFavorite.value = data.slugs.includes(props.workSlug)
|
||||
} catch {
|
||||
// 忽略,保持现状
|
||||
}
|
||||
}
|
||||
|
||||
const toggle = async () => {
|
||||
if (!userStore.isAuthenticated) {
|
||||
authModal.openLogin()
|
||||
return
|
||||
}
|
||||
if (isLoading.value) return
|
||||
isLoading.value = true
|
||||
try {
|
||||
if (isFavorite.value) {
|
||||
await $fetch('/api/favorites', { method: 'DELETE', body: { workSlug: props.workSlug } })
|
||||
isFavorite.value = false
|
||||
} else {
|
||||
await $fetch('/api/favorites', { method: 'POST', body: { workSlug: props.workSlug } })
|
||||
isFavorite.value = true
|
||||
}
|
||||
} catch (err) {
|
||||
console.error('favorite toggle error:', err)
|
||||
} finally {
|
||||
isLoading.value = false
|
||||
}
|
||||
}
|
||||
|
||||
onMounted(refresh)
|
||||
watch(() => userStore.isAuthenticated, refresh)
|
||||
watch(() => props.workSlug, refresh)
|
||||
</script>
|
||||
@@ -2,7 +2,7 @@
|
||||
<Teleport to="body">
|
||||
<Transition name="modal">
|
||||
<div
|
||||
v-if="isOpen"
|
||||
v-if="authModal.isLoginOpen"
|
||||
class="fixed inset-0 z-[100] flex items-center justify-center bg-black/50 backdrop-blur-sm px-4"
|
||||
@click.self="closeModal"
|
||||
>
|
||||
@@ -35,7 +35,8 @@
|
||||
v-model="account"
|
||||
type="text"
|
||||
required
|
||||
:disabled="isLoggingIn"
|
||||
autocomplete="username"
|
||||
:disabled="isSubmitting"
|
||||
class="w-full px-4 py-3 rounded-xl border border-gray-200 focus:border-black focus:ring-2 focus:ring-black/5 outline-none transition-all duration-300 disabled:opacity-50 disabled:cursor-not-allowed"
|
||||
:placeholder="t('auth.accountPlaceholder')"
|
||||
/>
|
||||
@@ -50,7 +51,8 @@
|
||||
v-model="password"
|
||||
type="password"
|
||||
required
|
||||
:disabled="isLoggingIn"
|
||||
autocomplete="current-password"
|
||||
:disabled="isSubmitting"
|
||||
class="w-full px-4 py-3 rounded-xl border border-gray-200 focus:border-black focus:ring-2 focus:ring-black/5 outline-none transition-all duration-300 disabled:opacity-50 disabled:cursor-not-allowed"
|
||||
:placeholder="t('auth.passwordPlaceholder')"
|
||||
/>
|
||||
@@ -64,26 +66,21 @@
|
||||
<!-- 登录按钮 -->
|
||||
<button
|
||||
type="submit"
|
||||
:disabled="isLoggingIn || !account || !password"
|
||||
:disabled="isSubmitting || !account || !password"
|
||||
class="w-full py-3 rounded-xl font-semibold text-white transition-all duration-300 flex items-center justify-center gap-2"
|
||||
:class="isLoggingIn || !account || !password
|
||||
:class="isSubmitting || !account || !password
|
||||
? 'bg-gray-400 cursor-not-allowed'
|
||||
: 'bg-black hover:bg-gray-800 shadow-lg hover:shadow-xl'"
|
||||
>
|
||||
<Icon v-if="isLoggingIn" name="ph:circle-notch" class="w-5 h-5 animate-spin" />
|
||||
<span>{{ isLoggingIn ? t('auth.loggingIn') : t('auth.loginButton') }}</span>
|
||||
<Icon v-if="isSubmitting" name="ph:circle-notch" class="w-5 h-5 animate-spin" />
|
||||
<span>{{ isSubmitting ? t('auth.loggingIn') : t('auth.loginButton') }}</span>
|
||||
</button>
|
||||
</form>
|
||||
|
||||
<!-- 提示信息 -->
|
||||
<p class="mt-6 text-center text-sm text-gray-500">
|
||||
{{ t('auth.demoHint') }}
|
||||
</p>
|
||||
|
||||
<!-- 注册账号链接 -->
|
||||
<p class="mt-4 text-center text-sm text-gray-600">
|
||||
<p class="mt-6 text-center text-sm text-gray-600">
|
||||
{{ t('auth.noAccount') }}
|
||||
<button @click="switchToRegister" class="text-black font-semibold hover:underline">
|
||||
<button @click="authModal.switchToRegister()" class="text-black font-semibold hover:underline">
|
||||
{{ t('auth.createAccount') }}
|
||||
</button>
|
||||
</p>
|
||||
@@ -98,86 +95,60 @@
|
||||
import { ref, watch } from 'vue'
|
||||
import { useI18n } from 'vue-i18n'
|
||||
import { useUserStore } from '~/stores/user'
|
||||
import { useAuthModalStore } from '~/stores/authModal'
|
||||
import { useApiError } from '~/composables/useApiError'
|
||||
|
||||
const { t } = useI18n()
|
||||
const userStore = useUserStore()
|
||||
const authModal = useAuthModalStore()
|
||||
const apiError = useApiError()
|
||||
|
||||
interface Props {
|
||||
isOpen: boolean
|
||||
}
|
||||
|
||||
const props = defineProps<Props>()
|
||||
const emit = defineEmits<{
|
||||
close: []
|
||||
switchToRegister: []
|
||||
}>()
|
||||
|
||||
const modalRef = ref<HTMLElement | null>(null)
|
||||
const account = ref('')
|
||||
const password = ref('')
|
||||
const isLoggingIn = ref(false)
|
||||
const isSubmitting = ref(false)
|
||||
const errorMessage = ref('')
|
||||
|
||||
// 关闭模态框
|
||||
const closeModal = () => {
|
||||
if (!isLoggingIn.value) {
|
||||
emit('close')
|
||||
if (!isSubmitting.value) {
|
||||
authModal.closeAll()
|
||||
}
|
||||
}
|
||||
|
||||
// 切换到注册
|
||||
const switchToRegister = () => {
|
||||
emit('switchToRegister')
|
||||
// 打开时重置表单
|
||||
watch(
|
||||
() => authModal.isLoginOpen,
|
||||
(open) => {
|
||||
if (open) {
|
||||
account.value = ''
|
||||
password.value = ''
|
||||
errorMessage.value = ''
|
||||
}
|
||||
},
|
||||
)
|
||||
|
||||
// 处理登录
|
||||
const handleLogin = async () => {
|
||||
if (isLoggingIn.value) return
|
||||
|
||||
isLoggingIn.value = true
|
||||
if (isSubmitting.value) return
|
||||
isSubmitting.value = true
|
||||
errorMessage.value = ''
|
||||
|
||||
try {
|
||||
const result = await userStore.login(account.value, password.value)
|
||||
|
||||
if (result.success) {
|
||||
// 登录成功,关闭模态框
|
||||
account.value = ''
|
||||
password.value = ''
|
||||
closeModal()
|
||||
authModal.closeAll()
|
||||
} else {
|
||||
errorMessage.value = t('auth.loginError')
|
||||
}
|
||||
} catch (error) {
|
||||
console.error('Login error:', error)
|
||||
errorMessage.value = t('auth.loginError')
|
||||
} finally {
|
||||
isLoggingIn.value = false
|
||||
errorMessage.value = apiError({ data: { code: result.code } })
|
||||
}
|
||||
isSubmitting.value = false
|
||||
}
|
||||
|
||||
// 监听打开状态,重置表单
|
||||
watch(() => props.isOpen, (isOpen) => {
|
||||
if (isOpen) {
|
||||
account.value = ''
|
||||
password.value = ''
|
||||
errorMessage.value = ''
|
||||
// 禁止背景滚动
|
||||
document.body.style.overflow = 'hidden'
|
||||
} else {
|
||||
// 恢复滚动
|
||||
document.body.style.overflow = ''
|
||||
}
|
||||
})
|
||||
|
||||
// ESC 键关闭
|
||||
// ESC 关闭
|
||||
const handleKeydown = (e: KeyboardEvent) => {
|
||||
if (e.key === 'Escape' && props.isOpen) {
|
||||
if (e.key === 'Escape' && authModal.isLoginOpen) {
|
||||
closeModal()
|
||||
}
|
||||
}
|
||||
|
||||
// 添加键盘事件监听
|
||||
if (typeof window !== 'undefined') {
|
||||
window.addEventListener('keydown', handleKeydown)
|
||||
}
|
||||
|
||||
@@ -2,7 +2,7 @@
|
||||
<Teleport to="body">
|
||||
<Transition name="modal">
|
||||
<div
|
||||
v-if="isOpen"
|
||||
v-if="authModal.isRegisterOpen"
|
||||
class="fixed inset-0 z-[100] flex items-center justify-center bg-black/50 backdrop-blur-sm px-4"
|
||||
@click.self="closeModal"
|
||||
>
|
||||
@@ -35,7 +35,8 @@
|
||||
v-model="username"
|
||||
type="text"
|
||||
required
|
||||
:disabled="isRegistering"
|
||||
autocomplete="username"
|
||||
:disabled="isSubmitting"
|
||||
class="w-full px-4 py-3 rounded-xl border border-gray-200 focus:border-black focus:ring-2 focus:ring-black/5 outline-none transition-all duration-300 disabled:opacity-50 disabled:cursor-not-allowed"
|
||||
:placeholder="t('auth.usernamePlaceholder')"
|
||||
/>
|
||||
@@ -50,7 +51,8 @@
|
||||
v-model="email"
|
||||
type="email"
|
||||
required
|
||||
:disabled="isRegistering"
|
||||
autocomplete="email"
|
||||
:disabled="isSubmitting"
|
||||
class="w-full px-4 py-3 rounded-xl border border-gray-200 focus:border-black focus:ring-2 focus:ring-black/5 outline-none transition-all duration-300 disabled:opacity-50 disabled:cursor-not-allowed"
|
||||
:placeholder="t('auth.emailPlaceholder')"
|
||||
/>
|
||||
@@ -64,7 +66,8 @@
|
||||
id="reg-phone"
|
||||
v-model="phone"
|
||||
type="tel"
|
||||
:disabled="isRegistering"
|
||||
autocomplete="tel"
|
||||
:disabled="isSubmitting"
|
||||
class="w-full px-4 py-3 rounded-xl border border-gray-200 focus:border-black focus:ring-2 focus:ring-black/5 outline-none transition-all duration-300 disabled:opacity-50 disabled:cursor-not-allowed"
|
||||
:placeholder="t('auth.phonePlaceholder')"
|
||||
/>
|
||||
@@ -79,7 +82,8 @@
|
||||
v-model="password"
|
||||
type="password"
|
||||
required
|
||||
:disabled="isRegistering"
|
||||
autocomplete="new-password"
|
||||
:disabled="isSubmitting"
|
||||
class="w-full px-4 py-3 rounded-xl border border-gray-200 focus:border-black focus:ring-2 focus:ring-black/5 outline-none transition-all duration-300 disabled:opacity-50 disabled:cursor-not-allowed"
|
||||
:placeholder="t('auth.passwordPlaceholder')"
|
||||
/>
|
||||
@@ -94,7 +98,8 @@
|
||||
v-model="confirmPassword"
|
||||
type="password"
|
||||
required
|
||||
:disabled="isRegistering"
|
||||
autocomplete="new-password"
|
||||
:disabled="isSubmitting"
|
||||
class="w-full px-4 py-3 rounded-xl border border-gray-200 focus:border-black focus:ring-2 focus:ring-black/5 outline-none transition-all duration-300 disabled:opacity-50 disabled:cursor-not-allowed"
|
||||
:placeholder="t('auth.confirmPasswordPlaceholder')"
|
||||
/>
|
||||
@@ -113,21 +118,21 @@
|
||||
<!-- 注册按钮 -->
|
||||
<button
|
||||
type="submit"
|
||||
:disabled="isRegistering || !username || !email || !password || !confirmPassword"
|
||||
:disabled="isSubmitting || !username || !email || !password || !confirmPassword"
|
||||
class="w-full py-3 rounded-xl font-semibold text-white transition-all duration-300 flex items-center justify-center gap-2"
|
||||
:class="isRegistering || !username || !email || !password || !confirmPassword
|
||||
:class="isSubmitting || !username || !email || !password || !confirmPassword
|
||||
? 'bg-gray-400 cursor-not-allowed'
|
||||
: 'bg-black hover:bg-gray-800 shadow-lg hover:shadow-xl'"
|
||||
>
|
||||
<Icon v-if="isRegistering" name="ph:circle-notch" class="w-5 h-5 animate-spin" />
|
||||
<span>{{ isRegistering ? t('auth.registering') : t('auth.registerButton') }}</span>
|
||||
<Icon v-if="isSubmitting" name="ph:circle-notch" class="w-5 h-5 animate-spin" />
|
||||
<span>{{ isSubmitting ? t('auth.registering') : t('auth.registerButton') }}</span>
|
||||
</button>
|
||||
</form>
|
||||
|
||||
<!-- 返回登录链接 -->
|
||||
<p class="mt-6 text-center text-sm text-gray-600">
|
||||
{{ t('auth.alreadyHaveAccount') }}
|
||||
<button @click="switchToLogin" class="text-black font-semibold hover:underline">
|
||||
<button @click="authModal.switchToLogin()" class="text-black font-semibold hover:underline">
|
||||
{{ t('auth.backToLogin') }}
|
||||
</button>
|
||||
</p>
|
||||
@@ -142,122 +147,89 @@
|
||||
import { ref, watch } from 'vue'
|
||||
import { useI18n } from 'vue-i18n'
|
||||
import { useUserStore } from '~/stores/user'
|
||||
import { useAuthModalStore } from '~/stores/authModal'
|
||||
import { useApiError } from '~/composables/useApiError'
|
||||
|
||||
const { t } = useI18n()
|
||||
const userStore = useUserStore()
|
||||
const authModal = useAuthModalStore()
|
||||
const apiError = useApiError()
|
||||
|
||||
interface Props {
|
||||
isOpen: boolean
|
||||
}
|
||||
|
||||
const props = defineProps<Props>()
|
||||
const emit = defineEmits<{
|
||||
close: []
|
||||
switchToLogin: []
|
||||
}>()
|
||||
|
||||
const modalRef = ref<HTMLElement | null>(null)
|
||||
const username = ref('')
|
||||
const email = ref('')
|
||||
const phone = ref('')
|
||||
const password = ref('')
|
||||
const confirmPassword = ref('')
|
||||
const isRegistering = ref(false)
|
||||
const isSubmitting = ref(false)
|
||||
const errorMessage = ref('')
|
||||
const successMessage = ref('')
|
||||
|
||||
// 关闭模态框
|
||||
const closeModal = () => {
|
||||
if (!isRegistering.value) {
|
||||
emit('close')
|
||||
if (!isSubmitting.value) {
|
||||
authModal.closeAll()
|
||||
}
|
||||
}
|
||||
|
||||
// 切换到登录
|
||||
const switchToLogin = () => {
|
||||
emit('switchToLogin')
|
||||
// 打开时重置表单
|
||||
watch(
|
||||
() => authModal.isRegisterOpen,
|
||||
(open) => {
|
||||
if (open) {
|
||||
username.value = ''
|
||||
email.value = ''
|
||||
phone.value = ''
|
||||
password.value = ''
|
||||
confirmPassword.value = ''
|
||||
errorMessage.value = ''
|
||||
successMessage.value = ''
|
||||
}
|
||||
},
|
||||
)
|
||||
|
||||
// 处理注册
|
||||
const handleRegister = async () => {
|
||||
if (isRegistering.value) return
|
||||
if (isSubmitting.value) return
|
||||
errorMessage.value = ''
|
||||
successMessage.value = ''
|
||||
|
||||
// 验证密码匹配
|
||||
if (password.value !== confirmPassword.value) {
|
||||
errorMessage.value = t('auth.passwordMismatch')
|
||||
return
|
||||
}
|
||||
|
||||
// 验证手机号格式(如果填写了)
|
||||
if (phone.value && !/^1[3-9]\d{9}$/.test(phone.value)) {
|
||||
errorMessage.value = t('auth.invalidPhone')
|
||||
return
|
||||
}
|
||||
|
||||
isRegistering.value = true
|
||||
errorMessage.value = ''
|
||||
successMessage.value = ''
|
||||
|
||||
try {
|
||||
isSubmitting.value = true
|
||||
const result = await userStore.register({
|
||||
username: username.value,
|
||||
email: email.value,
|
||||
phone: phone.value,
|
||||
password: password.value
|
||||
password: password.value,
|
||||
})
|
||||
|
||||
if (result.success) {
|
||||
// 注册成功
|
||||
successMessage.value = t('auth.registerSuccess')
|
||||
|
||||
// 清空表单
|
||||
username.value = ''
|
||||
email.value = ''
|
||||
phone.value = ''
|
||||
password.value = ''
|
||||
confirmPassword.value = ''
|
||||
|
||||
// 2秒后关闭并自动登录
|
||||
setTimeout(() => {
|
||||
closeModal()
|
||||
}, 2000)
|
||||
authModal.closeAll()
|
||||
}, 1500)
|
||||
} else {
|
||||
errorMessage.value = result.error || t('auth.registerError')
|
||||
}
|
||||
} catch (error) {
|
||||
console.error('Register error:', error)
|
||||
errorMessage.value = t('auth.registerError')
|
||||
} finally {
|
||||
isRegistering.value = false
|
||||
errorMessage.value = apiError({ data: { code: result.code } })
|
||||
}
|
||||
isSubmitting.value = false
|
||||
}
|
||||
|
||||
// 监听打开状态,重置表单
|
||||
watch(() => props.isOpen, (isOpen) => {
|
||||
if (isOpen) {
|
||||
username.value = ''
|
||||
email.value = ''
|
||||
phone.value = ''
|
||||
password.value = ''
|
||||
confirmPassword.value = ''
|
||||
errorMessage.value = ''
|
||||
successMessage.value = ''
|
||||
// 禁止背景滚动
|
||||
document.body.style.overflow = 'hidden'
|
||||
} else {
|
||||
// 恢复滚动
|
||||
document.body.style.overflow = ''
|
||||
}
|
||||
})
|
||||
|
||||
// ESC 键关闭
|
||||
// ESC 关闭
|
||||
const handleKeydown = (e: KeyboardEvent) => {
|
||||
if (e.key === 'Escape' && props.isOpen) {
|
||||
if (e.key === 'Escape' && authModal.isRegisterOpen) {
|
||||
closeModal()
|
||||
}
|
||||
}
|
||||
|
||||
// 添加键盘事件监听
|
||||
if (typeof window !== 'undefined') {
|
||||
window.addEventListener('keydown', handleKeydown)
|
||||
}
|
||||
|
||||
@@ -3,6 +3,7 @@ import { onMounted, onUnmounted, ref, nextTick } from 'vue'
|
||||
import { useI18n } from 'vue-i18n'
|
||||
import gsap from 'gsap'
|
||||
import { ScrollTrigger } from 'gsap/ScrollTrigger'
|
||||
import { workItems } from '~/data/work'
|
||||
|
||||
gsap.registerPlugin(ScrollTrigger)
|
||||
|
||||
@@ -49,46 +50,6 @@ const partners = [
|
||||
},
|
||||
]
|
||||
|
||||
const toImageUrl = (prompt: string, imageSize: string) => {
|
||||
const encoded = encodeURIComponent(prompt)
|
||||
return `https://coresg-normal.trae.ai/api/ide/v1/text_to_image?prompt=${encoded}&image_size=${imageSize}`
|
||||
}
|
||||
|
||||
const workItems = [
|
||||
{
|
||||
titleKey: 'home.work.items.forma',
|
||||
year: '26',
|
||||
image: toImageUrl(
|
||||
'high-end editorial product still life, minimal composition, matte ceramics and brushed aluminum on soft neutral background, studio lighting, shallow depth of field, premium, clean, realistic, 35mm photo',
|
||||
'landscape_16_9'
|
||||
),
|
||||
},
|
||||
{
|
||||
titleKey: 'home.work.items.oneStep',
|
||||
year: '24',
|
||||
image: toImageUrl(
|
||||
'architectural close-up, modern brutalist concrete facade with sharp shadows, minimal, cinematic lighting, high contrast, ultra realistic, 35mm photography, no people',
|
||||
'landscape_16_9'
|
||||
),
|
||||
},
|
||||
{
|
||||
titleKey: 'home.work.items.neroVision',
|
||||
year: '25',
|
||||
image: toImageUrl(
|
||||
'minimal graphic poster photographed in studio, black ink typography on off-white textured paper, premium editorial style, soft shadow, ultra realistic, no people',
|
||||
'landscape_16_9'
|
||||
),
|
||||
},
|
||||
{
|
||||
titleKey: 'home.work.items.boldMoves',
|
||||
year: '24',
|
||||
image: toImageUrl(
|
||||
'moody nighttime city street still life, neon reflection on wet asphalt, abstract bokeh, premium cinematic photography, no people, high detail',
|
||||
'landscape_16_9'
|
||||
),
|
||||
},
|
||||
] as const
|
||||
|
||||
let ctx: gsap.Context | null = null
|
||||
|
||||
const refresh = () => {
|
||||
@@ -140,12 +101,12 @@ onMounted(async () => {
|
||||
tl.to(
|
||||
next,
|
||||
{ y: 0, duration: 1, ease: 'power2.out' },
|
||||
start
|
||||
start,
|
||||
)
|
||||
tl.to(
|
||||
prev,
|
||||
{ scale: scaleTo, y: depthOffsetY, duration: 0.6, ease: 'power2.out' },
|
||||
start + 0.35
|
||||
start + 0.35,
|
||||
)
|
||||
tl.set(prev, { scale: scaleTo, y: depthOffsetY }, start + 1)
|
||||
}
|
||||
@@ -235,29 +196,30 @@ onUnmounted(() => {
|
||||
<div class="relative flex-1 h-full flex items-center">
|
||||
<div class="relative w-full h-[78svh] md:h-[82svh] lg:h-[88svh] p-[clamp(14px,2.4vw,28px)]">
|
||||
<div class="relative h-full w-full">
|
||||
<article
|
||||
<NuxtLink
|
||||
v-for="(item, idx) in workItems"
|
||||
:key="`${item.titleKey}-${idx}`"
|
||||
:key="item.slug"
|
||||
:to="`/work/${item.slug}`"
|
||||
ref="cardRefs"
|
||||
class="will-change-transform relative"
|
||||
class="will-change-transform relative block"
|
||||
>
|
||||
<img
|
||||
class="h-full w-full object-cover"
|
||||
:src="item.image"
|
||||
:alt="t(item.titleKey)"
|
||||
:alt="t(`work.items.${item.slug}.title`)"
|
||||
loading="lazy"
|
||||
decoding="async"
|
||||
@load="refresh"
|
||||
/>
|
||||
<div class="absolute left-6 top-6 flex items-baseline gap-3">
|
||||
<p class="text-white text-sm md:text-base font-semibold tracking-tight drop-shadow-[0_10px_18px_rgba(0,0,0,0.4)]">
|
||||
{{ t(item.titleKey) }}
|
||||
{{ t(`work.items.${item.slug}.title`) }}
|
||||
</p>
|
||||
<p class="text-white/80 text-xs md:text-sm font-semibold tracking-tight drop-shadow-[0_10px_18px_rgba(0,0,0,0.4)]">
|
||||
{{ item.year }} ©
|
||||
</p>
|
||||
</div>
|
||||
</article>
|
||||
</NuxtLink>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
@@ -15,7 +15,7 @@
|
||||
v-for="(tech, index) in technologies"
|
||||
:key="tech.id"
|
||||
:ref="el => setTechRef(el, index)"
|
||||
class="tech-tag absolute flex items-center gap-3 px-5 py-3 bg-white rounded-full shadow-lg border-2 cursor-pointer hover:scale-110 transition-transform duration-300"
|
||||
class="tech-tag absolute flex items-center gap-3 px-5 py-3 bg-white rounded-full shadow-lg border-2 hover:scale-110 transition-transform duration-300"
|
||||
:class="tech.borderColor"
|
||||
:style="getTechStyle(index)"
|
||||
>
|
||||
|
||||
@@ -13,11 +13,12 @@
|
||||
|
||||
<!-- Bento 网格 -->
|
||||
<div class="grid grid-cols-12 gap-4 md:gap-6 auto-rows-[200px]">
|
||||
<div
|
||||
<NuxtLink
|
||||
v-for="(item, index) in updates"
|
||||
:key="item.id"
|
||||
:key="item.slug"
|
||||
:to="`/news/${item.slug}`"
|
||||
:ref="el => setCardRef(el, index)"
|
||||
class="update-card group relative overflow-hidden rounded-3xl cursor-pointer"
|
||||
class="update-card group relative overflow-hidden rounded-3xl cursor-pointer block"
|
||||
:class="item.gridClass"
|
||||
:style="{ opacity: 0 }"
|
||||
@mouseenter="() => handleCardHover(index, true)"
|
||||
@@ -31,27 +32,27 @@
|
||||
<div>
|
||||
<div class="inline-flex items-center gap-2 px-3 py-1.5 rounded-full bg-white/20 backdrop-blur-sm text-xs md:text-sm font-semibold mb-4">
|
||||
<Icon :name="item.categoryIcon" class="w-4 h-4" />
|
||||
{{ t(`home.updates.categories.${item.category}`) }}
|
||||
{{ t(`news.categories.${item.category}`) }}
|
||||
</div>
|
||||
|
||||
<h3 class="text-xl md:text-3xl font-bold mb-3 line-clamp-2">
|
||||
{{ t(`home.updates.items.${item.id}.title`) }}
|
||||
{{ t(`news.items.${item.slug}.title`) }}
|
||||
</h3>
|
||||
|
||||
<p v-if="item.showDescription" class="text-white/90 text-sm md:text-base line-clamp-3">
|
||||
{{ t(`home.updates.items.${item.id}.description`) }}
|
||||
{{ t(`news.items.${item.slug}.excerpt`) }}
|
||||
</p>
|
||||
</div>
|
||||
|
||||
<div class="flex items-center justify-between">
|
||||
<span class="text-xs md:text-sm text-white/80">{{ item.date }}</span>
|
||||
<span class="text-xs md:text-sm text-white/80">{{ formatNewsDate(item.date, locale) }}</span>
|
||||
<Icon name="ph:arrow-up-right" class="w-5 h-5 md:w-6 md:h-6 transition-transform duration-300 group-hover:translate-x-1 group-hover:-translate-y-1" />
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<!-- 悬浮效果 -->
|
||||
<div class="absolute inset-0 bg-black/0 group-hover:bg-black/10 transition-colors duration-300"></div>
|
||||
</div>
|
||||
</NuxtLink>
|
||||
</div>
|
||||
|
||||
<!-- 查看更多 -->
|
||||
@@ -73,10 +74,11 @@ import { ref, onMounted, onUnmounted, nextTick } from 'vue'
|
||||
import { useI18n } from 'vue-i18n'
|
||||
import gsap from 'gsap'
|
||||
import { ScrollTrigger } from 'gsap/ScrollTrigger'
|
||||
import { newsItems, formatNewsDate } from '~/data/news'
|
||||
|
||||
gsap.registerPlugin(ScrollTrigger)
|
||||
|
||||
const { t } = useI18n()
|
||||
const { t, locale } = useI18n()
|
||||
|
||||
const rootRef = ref<HTMLElement | null>(null)
|
||||
const headerRef = ref<HTMLElement | null>(null)
|
||||
@@ -87,62 +89,21 @@ const setCardRef = (el: any, index: number) => {
|
||||
if (el) cardElements.value[index] = el
|
||||
}
|
||||
|
||||
const updates = [
|
||||
{
|
||||
id: 'project1',
|
||||
category: 'project',
|
||||
categoryIcon: 'ph:briefcase',
|
||||
gradient: 'bg-gradient-to-br from-blue-500 via-purple-500 to-pink-500',
|
||||
gridClass: 'col-span-12 md:col-span-6 md:row-span-2',
|
||||
showDescription: true,
|
||||
date: '2026-06-01'
|
||||
},
|
||||
{
|
||||
id: 'blog1',
|
||||
category: 'blog',
|
||||
categoryIcon: 'ph:article',
|
||||
gradient: 'bg-gradient-to-br from-orange-500 to-red-500',
|
||||
gridClass: 'col-span-12 md:col-span-3 md:row-span-1',
|
||||
showDescription: false,
|
||||
date: '2026-05-28'
|
||||
},
|
||||
{
|
||||
id: 'news1',
|
||||
category: 'news',
|
||||
categoryIcon: 'ph:newspaper',
|
||||
gradient: 'bg-gradient-to-br from-green-500 to-emerald-500',
|
||||
gridClass: 'col-span-12 md:col-span-3 md:row-span-1',
|
||||
showDescription: false,
|
||||
date: '2026-05-25'
|
||||
},
|
||||
{
|
||||
id: 'project2',
|
||||
category: 'project',
|
||||
categoryIcon: 'ph:briefcase',
|
||||
gradient: 'bg-gradient-to-br from-indigo-500 to-blue-500',
|
||||
gridClass: 'col-span-12 md:col-span-3 md:row-span-2',
|
||||
showDescription: true,
|
||||
date: '2026-05-20'
|
||||
},
|
||||
{
|
||||
id: 'blog2',
|
||||
category: 'blog',
|
||||
categoryIcon: 'ph:article',
|
||||
gradient: 'bg-gradient-to-br from-pink-500 to-rose-500',
|
||||
gridClass: 'col-span-12 md:col-span-6 md:row-span-1',
|
||||
showDescription: false,
|
||||
date: '2026-05-15'
|
||||
},
|
||||
{
|
||||
id: 'news2',
|
||||
category: 'news',
|
||||
categoryIcon: 'ph:newspaper',
|
||||
gradient: 'bg-gradient-to-br from-amber-500 to-orange-500',
|
||||
gridClass: 'col-span-12 md:col-span-3 md:row-span-1',
|
||||
showDescription: false,
|
||||
date: '2026-05-10'
|
||||
}
|
||||
]
|
||||
// Bento 布局(与动态数据一一对应;分类图标/渐变/跨度)
|
||||
const layout = [
|
||||
{ categoryIcon: 'ph:article', gradient: 'bg-gradient-to-br from-blue-500 via-purple-500 to-pink-500', gridClass: 'col-span-12 md:col-span-6 md:row-span-2', showDescription: true },
|
||||
{ categoryIcon: 'ph:briefcase', gradient: 'bg-gradient-to-br from-orange-500 to-red-500', gridClass: 'col-span-12 md:col-span-3 md:row-span-1', showDescription: false },
|
||||
{ categoryIcon: 'ph:newspaper', gradient: 'bg-gradient-to-br from-green-500 to-emerald-500', gridClass: 'col-span-12 md:col-span-3 md:row-span-1', showDescription: false },
|
||||
{ categoryIcon: 'ph:article', gradient: 'bg-gradient-to-br from-indigo-500 to-blue-500', gridClass: 'col-span-12 md:col-span-3 md:row-span-2', showDescription: true },
|
||||
{ categoryIcon: 'ph:briefcase', gradient: 'bg-gradient-to-br from-pink-500 to-rose-500', gridClass: 'col-span-12 md:col-span-6 md:row-span-1', showDescription: false },
|
||||
{ categoryIcon: 'ph:newspaper', gradient: 'bg-gradient-to-br from-amber-500 to-orange-500', gridClass: 'col-span-12 md:col-span-3 md:row-span-1', showDescription: false },
|
||||
] as const
|
||||
|
||||
// 取前 6 条动态,绑定布局
|
||||
const updates = newsItems.slice(0, 6).map((item, i) => ({
|
||||
...item,
|
||||
...layout[i],
|
||||
}))
|
||||
|
||||
// 卡片悬浮效果
|
||||
const handleCardHover = (index: number, isHover: boolean) => {
|
||||
@@ -155,7 +116,7 @@ const handleCardHover = (index: number, isHover: boolean) => {
|
||||
? '0 25px 50px -12px rgba(0, 0, 0, 0.25)'
|
||||
: '0 10px 15px -3px rgba(0, 0, 0, 0.1)',
|
||||
duration: 0.3,
|
||||
ease: 'power2.out'
|
||||
ease: 'power2.out',
|
||||
})
|
||||
}
|
||||
|
||||
@@ -171,7 +132,7 @@ onMounted(async () => {
|
||||
gsap.set(card, { autoAlpha: 0, y: 60, scale: 0.9 })
|
||||
})
|
||||
|
||||
// 入场动画(无 pin):标题 + 卡片错开出现
|
||||
// 入场动画:标题 + 卡片错开出现
|
||||
const tl = gsap.timeline()
|
||||
|
||||
tl.to(headerRef.value, { autoAlpha: 1, y: 0, duration: 0.8, ease: 'power3.out' }, 0)
|
||||
|
||||
@@ -5,6 +5,7 @@ import { gsap } from 'gsap'
|
||||
import { ScrollTrigger } from 'gsap/ScrollTrigger'
|
||||
import FooterLogo from '~/components/common/FooterLogo.vue'
|
||||
import AnimatedButton from '~/components/common/AnimatedButton.vue'
|
||||
import { siteConfig } from '~/config/site'
|
||||
|
||||
gsap.registerPlugin(ScrollTrigger)
|
||||
|
||||
@@ -43,14 +44,8 @@ const handleNewsletterSubmit = async () => {
|
||||
subscribeStatus.value = 'idle'
|
||||
|
||||
try {
|
||||
// 模拟 API 调用 - 你需要替换为真实的 Newsletter 服务
|
||||
// 可选方案:
|
||||
// 1. Mailchimp: await $fetch('/api/newsletter/subscribe', { method: 'POST', body: { email: newsletterEmail.value } })
|
||||
// 2. ConvertKit, SendGrid, 或其他邮件服务
|
||||
|
||||
await new Promise(resolve => setTimeout(resolve, 1000)) // 模拟网络延迟
|
||||
|
||||
console.log('Newsletter subscription:', newsletterEmail.value)
|
||||
// 真实订阅:落库 + 尽力发送欢迎邮件
|
||||
await $fetch('/api/newsletter', { method: 'POST', body: { email: newsletterEmail.value } })
|
||||
|
||||
subscribeStatus.value = 'success'
|
||||
newsletterEmail.value = ''
|
||||
@@ -61,8 +56,12 @@ const handleNewsletterSubmit = async () => {
|
||||
}, 3000)
|
||||
|
||||
} catch (error) {
|
||||
console.error('Newsletter subscription error:', error)
|
||||
// 已在订阅列表视为成功(用户确实已订阅)
|
||||
if ((error as any)?.data?.code === 'ALREADY_SUBSCRIBED') {
|
||||
subscribeStatus.value = 'success'
|
||||
} else {
|
||||
subscribeStatus.value = 'error'
|
||||
}
|
||||
|
||||
setTimeout(() => {
|
||||
subscribeStatus.value = 'idle'
|
||||
@@ -227,10 +226,10 @@ onUnmounted(() => {
|
||||
<div class="grid grid-cols-1 sm:grid-cols-2 gap-8">
|
||||
<ul class="space-y-3">
|
||||
<li class="animated-item">
|
||||
<a href="mailto:chenchun@virtheart.com" class="group flex items-center overflow-hidden text-[16px] font-bold text-white/80 hover:text-white transition-colors" style="justify-content: flex-start;">
|
||||
<a :href="`mailto:${siteConfig.email}`" class="group flex items-center overflow-hidden text-[16px] font-bold text-white/80 hover:text-white transition-colors" style="justify-content: flex-start;">
|
||||
<div class="flex items-center transition-transform duration-300 group-hover:translate-x-0 -translate-x-[21px] pr-[21px]">
|
||||
<span class="mr-[10px] h-[11px] w-[11px] rounded-full bg-white shrink-0"></span>
|
||||
<span>chenchun@virtheart.com</span>
|
||||
<span>{{ siteConfig.email }}</span>
|
||||
</div>
|
||||
</a>
|
||||
</li>
|
||||
@@ -238,7 +237,7 @@ onUnmounted(() => {
|
||||
<span class="group flex items-center overflow-hidden text-[16px] font-bold text-white/80 transition-colors cursor-default" style="justify-content: flex-start;">
|
||||
<div class="flex items-center transition-transform duration-300 group-hover:translate-x-0 -translate-x-[21px] pr-[21px]">
|
||||
<span class="mr-[10px] h-[11px] w-[11px] rounded-full bg-white shrink-0"></span>
|
||||
<span>{{ t('footer.wechat') }}: LucskyNew</span>
|
||||
<span>{{ t('footer.wechat') }}: {{ siteConfig.wechat }}</span>
|
||||
</div>
|
||||
</span>
|
||||
</li>
|
||||
@@ -246,10 +245,10 @@ onUnmounted(() => {
|
||||
|
||||
<ul class="space-y-3">
|
||||
<li class="animated-item">
|
||||
<a href="mailto:info@virtheart.com" class="group flex items-center overflow-hidden text-[16px] font-bold text-white/80 hover:text-white transition-colors" style="justify-content: flex-start;">
|
||||
<a :href="`mailto:${siteConfig.infoEmail}`" class="group flex items-center overflow-hidden text-[16px] font-bold text-white/80 hover:text-white transition-colors" style="justify-content: flex-start;">
|
||||
<div class="flex items-center transition-transform duration-300 group-hover:translate-x-0 -translate-x-[21px] pr-[21px]">
|
||||
<span class="mr-[10px] h-[11px] w-[11px] rounded-full bg-white shrink-0"></span>
|
||||
<span>info@virtheart.com</span>
|
||||
<span>{{ siteConfig.infoEmail }}</span>
|
||||
</div>
|
||||
</a>
|
||||
</li>
|
||||
@@ -266,14 +265,16 @@ onUnmounted(() => {
|
||||
</div>
|
||||
|
||||
<div class="flex gap-3 animated-item">
|
||||
<a href="#" class="w-10 h-10 rounded-full bg-[#1f1f1f] hover:bg-[#2f2f2f] flex items-center justify-center transition-colors text-white">
|
||||
<Icon name="ph:instagram-logo" class="w-4 h-4" />
|
||||
</a>
|
||||
<a href="#" class="w-10 h-10 rounded-full bg-[#1f1f1f] hover:bg-[#2f2f2f] flex items-center justify-center transition-colors text-white">
|
||||
<Icon name="ph:x-logo" class="w-4 h-4" />
|
||||
</a>
|
||||
<a href="#" class="w-10 h-10 rounded-full bg-[#1f1f1f] hover:bg-[#2f2f2f] flex items-center justify-center transition-colors text-white">
|
||||
<Icon name="ph:diamond-fill" class="w-4 h-4" />
|
||||
<a
|
||||
v-for="social in siteConfig.socials"
|
||||
:key="social.name"
|
||||
:href="social.url"
|
||||
target="_blank"
|
||||
rel="noopener noreferrer"
|
||||
class="w-10 h-10 rounded-full bg-[#1f1f1f] hover:bg-[#2f2f2f] flex items-center justify-center transition-colors text-white"
|
||||
:aria-label="social.name"
|
||||
>
|
||||
<Icon :name="social.icon" class="w-4 h-4" />
|
||||
</a>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
@@ -6,16 +6,18 @@ import gsap from 'gsap'
|
||||
import { ScrollTrigger } from 'gsap/ScrollTrigger'
|
||||
import { useAppStore } from '~/stores/app'
|
||||
import { useUserStore } from '~/stores/user'
|
||||
import { useAuthModalStore } from '~/stores/authModal'
|
||||
import AppLogo from '~/components/common/AppLogo.vue'
|
||||
import LoginModal from '~/components/common/LoginModal.vue'
|
||||
import RegisterModal from '~/components/common/RegisterModal.vue'
|
||||
|
||||
gsap.registerPlugin(ScrollTrigger)
|
||||
|
||||
const { t } = useI18n()
|
||||
const { t, locale, setLocale } = useI18n()
|
||||
const route = useRoute()
|
||||
const appStore = useAppStore()
|
||||
const userStore = useUserStore()
|
||||
const authModal = useAuthModalStore()
|
||||
|
||||
// 恢复用户状态
|
||||
onMounted(() => {
|
||||
@@ -36,46 +38,15 @@ const topHeaderRef = ref<HTMLElement | null>(null)
|
||||
const bottomHeaderRef = ref<HTMLElement | null>(null)
|
||||
const mobileMenuRef = ref<HTMLElement | null>(null)
|
||||
const isMobileMenuOpen = ref(false)
|
||||
const isLoginModalOpen = ref(false)
|
||||
const isRegisterModalOpen = ref(false)
|
||||
const isUserMenuOpen = ref(false)
|
||||
let topHeaderTween: gsap.core.Tween | null = null
|
||||
let bottomHeaderScrollTrigger: ReturnType<typeof ScrollTrigger.create> | null = null
|
||||
let isBottomHeaderVisible = false
|
||||
let fallbackTimer: ReturnType<typeof setTimeout> | null = null
|
||||
|
||||
// 打开登录弹窗
|
||||
const openLoginModal = () => {
|
||||
isLoginModalOpen.value = true
|
||||
isRegisterModalOpen.value = false
|
||||
}
|
||||
|
||||
// 关闭登录弹窗
|
||||
const closeLoginModal = () => {
|
||||
isLoginModalOpen.value = false
|
||||
}
|
||||
|
||||
// 打开注册弹窗
|
||||
const openRegisterModal = () => {
|
||||
isRegisterModalOpen.value = true
|
||||
isLoginModalOpen.value = false
|
||||
}
|
||||
|
||||
// 关闭注册弹窗
|
||||
const closeRegisterModal = () => {
|
||||
isRegisterModalOpen.value = false
|
||||
}
|
||||
|
||||
// 从登录切换到注册
|
||||
const switchToRegister = () => {
|
||||
isLoginModalOpen.value = false
|
||||
isRegisterModalOpen.value = true
|
||||
}
|
||||
|
||||
// 从注册切换到登录
|
||||
const switchToLogin = () => {
|
||||
isRegisterModalOpen.value = false
|
||||
isLoginModalOpen.value = true
|
||||
// 语言切换
|
||||
const switchLocale = () => {
|
||||
setLocale(locale.value === 'zh' ? 'en' : 'zh')
|
||||
}
|
||||
|
||||
// 切换用户菜单
|
||||
@@ -368,12 +339,21 @@ if (typeof window !== 'undefined') {
|
||||
</NuxtLink>
|
||||
</nav>
|
||||
|
||||
<!-- 右侧:登录按钮 / 用户信息(桌面端) -->
|
||||
<!-- 右侧:登录按钮 / 用户信息 / 语言切换(桌面端) -->
|
||||
<div class="hidden md:flex items-center gap-4">
|
||||
<!-- 语言切换 -->
|
||||
<button
|
||||
@click="switchLocale"
|
||||
class="px-3 py-2 rounded-full border border-gray-200 text-sm font-semibold text-black hover:bg-gray-100 transition-all duration-300"
|
||||
:aria-label="locale === 'zh' ? t('lang.toEnglish') : t('lang.toChinese')"
|
||||
>
|
||||
{{ locale === 'zh' ? t('lang.toEnglish') : t('lang.toChinese') }}
|
||||
</button>
|
||||
|
||||
<!-- 未登录:显示登录按钮 -->
|
||||
<button
|
||||
v-if="!userStore.isAuthenticated"
|
||||
@click="openLoginModal"
|
||||
@click="authModal.openLogin()"
|
||||
class="px-5 py-2.5 rounded-full bg-black text-white text-sm font-semibold hover:bg-gray-800 transition-all duration-300 shadow-md hover:shadow-lg"
|
||||
>
|
||||
{{ t('auth.login') }}
|
||||
@@ -387,10 +367,10 @@ if (typeof window !== 'undefined') {
|
||||
>
|
||||
<img
|
||||
:src="userStore.user?.avatar"
|
||||
:alt="userStore.user?.name"
|
||||
:alt="userStore.user?.username"
|
||||
class="w-9 h-9 rounded-full object-cover border-2 border-gray-200"
|
||||
/>
|
||||
<span class="text-sm font-semibold text-black">{{ userStore.user?.name }}</span>
|
||||
<span class="text-sm font-semibold text-black">{{ userStore.user?.username }}</span>
|
||||
<Icon
|
||||
name="ph:caret-down"
|
||||
class="w-4 h-4 text-gray-600 transition-transform duration-300"
|
||||
@@ -406,9 +386,17 @@ if (typeof window !== 'undefined') {
|
||||
@click="closeUserMenu"
|
||||
>
|
||||
<div class="px-4 py-3 border-b border-gray-100">
|
||||
<p class="text-sm font-semibold text-black">{{ userStore.user?.name }}</p>
|
||||
<p class="text-sm font-semibold text-black">{{ userStore.user?.username }}</p>
|
||||
<p class="text-xs text-gray-500 truncate">{{ userStore.user?.email }}</p>
|
||||
</div>
|
||||
<NuxtLink
|
||||
to="/account"
|
||||
@click="closeUserMenu"
|
||||
class="w-full px-4 py-2.5 text-left text-sm font-medium text-gray-700 hover:bg-gray-100 transition-colors duration-200 flex items-center gap-2"
|
||||
>
|
||||
<Icon name="ph:user-circle" class="w-4 h-4" />
|
||||
{{ t('account.title') }}
|
||||
</NuxtLink>
|
||||
<button
|
||||
@click="handleLogout"
|
||||
class="w-full px-4 py-2.5 text-left text-sm font-medium text-red-600 hover:bg-red-50 transition-colors duration-200 flex items-center gap-2"
|
||||
@@ -458,10 +446,18 @@ if (typeof window !== 'undefined') {
|
||||
|
||||
<!-- 移动端登录/用户信息 -->
|
||||
<div class="mobile-menu-item mt-8 pt-8 border-t border-gray-200 w-full flex flex-col items-center gap-4">
|
||||
<!-- 语言切换 -->
|
||||
<button
|
||||
@click="switchLocale"
|
||||
class="px-8 py-3 rounded-full border-2 border-black text-black text-base font-semibold hover:bg-gray-100 transition-all duration-300"
|
||||
>
|
||||
{{ locale === 'zh' ? t('lang.toEnglish') : t('lang.toChinese') }}
|
||||
</button>
|
||||
|
||||
<!-- 未登录 -->
|
||||
<button
|
||||
v-if="!userStore.isAuthenticated"
|
||||
@click="openLoginModal"
|
||||
@click="authModal.openLogin()"
|
||||
class="px-8 py-3 rounded-full bg-black text-white text-base font-semibold hover:bg-gray-800 transition-all duration-300"
|
||||
>
|
||||
{{ t('auth.login') }}
|
||||
@@ -472,11 +468,11 @@ if (typeof window !== 'undefined') {
|
||||
<div class="flex items-center gap-3">
|
||||
<img
|
||||
:src="userStore.user?.avatar"
|
||||
:alt="userStore.user?.name"
|
||||
:alt="userStore.user?.username"
|
||||
class="w-12 h-12 rounded-full object-cover border-2 border-gray-200"
|
||||
/>
|
||||
<div class="text-left">
|
||||
<p class="text-lg font-bold text-black">{{ userStore.user?.name }}</p>
|
||||
<p class="text-lg font-bold text-black">{{ userStore.user?.username }}</p>
|
||||
<p class="text-sm text-gray-500">{{ userStore.user?.email }}</p>
|
||||
</div>
|
||||
</div>
|
||||
@@ -492,19 +488,11 @@ if (typeof window !== 'undefined') {
|
||||
</nav>
|
||||
</div>
|
||||
|
||||
<!-- 登录弹窗 -->
|
||||
<LoginModal
|
||||
:is-open="isLoginModalOpen"
|
||||
@close="closeLoginModal"
|
||||
@switch-to-register="switchToRegister"
|
||||
/>
|
||||
<!-- 登录弹窗(由 authModal store 控制开关) -->
|
||||
<LoginModal />
|
||||
|
||||
<!-- 注册弹窗 -->
|
||||
<RegisterModal
|
||||
:is-open="isRegisterModalOpen"
|
||||
@close="closeRegisterModal"
|
||||
@switch-to-login="switchToLogin"
|
||||
/>
|
||||
<!-- 注册弹窗(由 authModal store 控制开关) -->
|
||||
<RegisterModal />
|
||||
|
||||
<header ref="bottomHeaderRef" class="site-header-bottom z-50 bg-white/80 backdrop-blur-md">
|
||||
<!-- 左侧菜单 (前两个菜单项) -->
|
||||
|
||||
@@ -0,0 +1,31 @@
|
||||
import { useI18n } from 'vue-i18n'
|
||||
|
||||
/**
|
||||
* 把后端 API 错误码映射为已翻译的 i18n 文案。
|
||||
* 用法:`const apiError = useApiError()`;`apiError(err)` 返回中文/英文消息。
|
||||
*/
|
||||
export function useApiError() {
|
||||
const { t } = useI18n()
|
||||
|
||||
const codeKeyMap: Record<string, string> = {
|
||||
USERNAME_TAKEN: 'auth.usernameTaken',
|
||||
EMAIL_TAKEN: 'auth.emailTaken',
|
||||
INVALID_CREDENTIALS: 'auth.invalidCredentials',
|
||||
UNAUTHORIZED: 'auth.loginRequired',
|
||||
FORBIDDEN: 'auth.loginRequired',
|
||||
ALREADY_SUBSCRIBED: 'newsletter.alreadySubscribed',
|
||||
VALIDATION_ERROR: 'auth.serverError',
|
||||
}
|
||||
|
||||
return (err: any, fallbackKey = 'auth.serverError'): string => {
|
||||
const code = err?.data?.code
|
||||
if (code && codeKeyMap[code]) {
|
||||
return t(codeKeyMap[code])
|
||||
}
|
||||
// 后端若带具体 message 也如实展示
|
||||
if (typeof err?.data?.message === 'string' && err.data.message) {
|
||||
return err.data.message
|
||||
}
|
||||
return t(fallbackKey)
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,27 @@
|
||||
/**
|
||||
* 站点全局元数据(品牌、联系、社交)。
|
||||
*
|
||||
* 单一事实源:Footer、联系页、账号页等不再各自硬编码邮箱/社交链接。
|
||||
*
|
||||
* 注意:社交地址为品牌官方占位链接,正式上线前请替换为北极新一真实账号。
|
||||
*/
|
||||
export interface SocialLink {
|
||||
name: string
|
||||
icon: string
|
||||
url: string
|
||||
}
|
||||
|
||||
export const siteConfig = {
|
||||
brand: 'ArcticNewOne',
|
||||
brandZh: '北极新一',
|
||||
email: 'chenchun@virtheart.com',
|
||||
infoEmail: 'info@virtheart.com',
|
||||
wechat: 'LucskyNew',
|
||||
copyright: '© 2026 北极新一工作室',
|
||||
socials: [
|
||||
{ name: 'X', icon: 'ph:x-logo', url: 'https://x.com/arcticnewone' },
|
||||
{ name: 'Instagram', icon: 'ph:instagram-logo', url: 'https://instagram.com/arcticnewone' },
|
||||
{ name: 'LinkedIn', icon: 'ph:linkedin-logo', url: 'https://www.linkedin.com/company/arcticnewone' },
|
||||
{ name: 'GitHub', icon: 'ph:github-logo', url: 'https://github.com/arcticnewone' },
|
||||
],
|
||||
}
|
||||
@@ -0,0 +1,98 @@
|
||||
/**
|
||||
* 动态(news)单一事实源。
|
||||
*
|
||||
* 列表页、详情页、首页 HomeUpdates 一律引用本模块,杜绝三处重复。
|
||||
* 标题/摘要/正文属于本地化文案,按 slug 存放在 i18n(news.items.<slug>.*),
|
||||
* 本模块只保存与语言无关的结构化元数据。
|
||||
*/
|
||||
export interface NewsItem {
|
||||
slug: string
|
||||
category: 'insights' | 'projects' | 'announcements'
|
||||
/** 分类徽章 tailwind 类(静态字符串,Tailwind 扫描 ./app/** 可命中) */
|
||||
badge: string
|
||||
date: string
|
||||
readTime: string
|
||||
author: string
|
||||
image: string
|
||||
}
|
||||
|
||||
export const newsItems: NewsItem[] = [
|
||||
{
|
||||
slug: 'design-trends-2026',
|
||||
category: 'insights',
|
||||
badge: 'bg-purple-100 text-purple-700',
|
||||
date: '2026-05-28',
|
||||
readTime: '5',
|
||||
author: 'ArcticNewOne',
|
||||
image: 'https://picsum.photos/id/1/800/500',
|
||||
},
|
||||
{
|
||||
slug: 'forma-digital-launch',
|
||||
category: 'projects',
|
||||
badge: 'bg-blue-100 text-blue-700',
|
||||
date: '2026-05-15',
|
||||
readTime: '3',
|
||||
author: 'ArcticNewOne',
|
||||
image: 'https://picsum.photos/id/201/800/500',
|
||||
},
|
||||
{
|
||||
slug: 'studio-expansion',
|
||||
category: 'announcements',
|
||||
badge: 'bg-green-100 text-green-700',
|
||||
date: '2026-05-10',
|
||||
readTime: '2',
|
||||
author: 'ArcticNewOne',
|
||||
image: 'https://picsum.photos/id/164/800/500',
|
||||
},
|
||||
{
|
||||
slug: 'ux-research-methods',
|
||||
category: 'insights',
|
||||
badge: 'bg-purple-100 text-purple-700',
|
||||
date: '2026-04-28',
|
||||
readTime: '7',
|
||||
author: 'ArcticNewOne',
|
||||
image: 'https://picsum.photos/id/180/800/500',
|
||||
},
|
||||
{
|
||||
slug: 'bold-moves-case-study',
|
||||
category: 'projects',
|
||||
badge: 'bg-blue-100 text-blue-700',
|
||||
date: '2026-04-20',
|
||||
readTime: '6',
|
||||
author: 'ArcticNewOne',
|
||||
image: 'https://picsum.photos/id/119/800/500',
|
||||
},
|
||||
{
|
||||
slug: 'new-tools-integration',
|
||||
category: 'announcements',
|
||||
badge: 'bg-green-100 text-green-700',
|
||||
date: '2026-04-12',
|
||||
readTime: '4',
|
||||
author: 'ArcticNewOne',
|
||||
image: 'https://picsum.photos/id/326/800/500',
|
||||
},
|
||||
]
|
||||
|
||||
export const newsBySlug: Record<string, NewsItem> = Object.fromEntries(
|
||||
newsItems.map((item) => [item.slug, item]),
|
||||
)
|
||||
|
||||
export function getNewsCategories(): Array<NewsItem['category']> {
|
||||
return ['insights', 'projects', 'announcements']
|
||||
}
|
||||
|
||||
/** 显示用的日期(本地化格式化在组件内完成) */
|
||||
export function formatNewsDate(date: string, locale: string): string {
|
||||
const d = new Date(`${date}T00:00:00`)
|
||||
if (Number.isNaN(d.getTime())) return date
|
||||
return new Intl.DateTimeFormat(locale === 'zh' ? 'zh-CN' : 'en-US', {
|
||||
year: 'numeric',
|
||||
month: 'long',
|
||||
day: 'numeric',
|
||||
}).format(d)
|
||||
}
|
||||
|
||||
/** 显示用的阅读时长(本地化文案在 i18n,数字在此) */
|
||||
export function newsReadTime(item: NewsItem): string {
|
||||
return item.readTime
|
||||
}
|
||||
@@ -0,0 +1,108 @@
|
||||
/**
|
||||
* 作品(work)单一事实源。
|
||||
*
|
||||
* 列表页、详情页、首页 HomePartnersWork 一律引用本模块,杜绝三处重复。
|
||||
* 标题/概述属于本地化文案,按 slug 存放在 i18n(work.items.<slug>.*)。
|
||||
*
|
||||
* 说明:`url` 只在存在真实线上地址时填写;没有真实地址的作品
|
||||
* 详情页不渲染「访问项目」按钮,避免 `#` 死链。
|
||||
*/
|
||||
export interface WorkItem {
|
||||
slug: string
|
||||
category: 'webDesign' | 'branding' | 'development'
|
||||
year: string
|
||||
tags: string[]
|
||||
image: string
|
||||
gallery: string[]
|
||||
/** 真实线上地址;不存在时省略,详情页隐藏「访问项目」按钮 */
|
||||
url?: string
|
||||
}
|
||||
|
||||
export const workItems: WorkItem[] = [
|
||||
{
|
||||
slug: 'forma-digital',
|
||||
category: 'webDesign',
|
||||
year: '2026',
|
||||
tags: ['Web Design', 'E-commerce', 'React'],
|
||||
image: 'https://picsum.photos/id/201/1200/800',
|
||||
gallery: [
|
||||
'https://picsum.photos/id/201/800/600',
|
||||
'https://picsum.photos/id/202/800/600',
|
||||
'https://picsum.photos/id/203/800/600',
|
||||
'https://picsum.photos/id/204/800/600',
|
||||
],
|
||||
},
|
||||
{
|
||||
slug: 'one-step',
|
||||
category: 'branding',
|
||||
year: '2024',
|
||||
tags: ['Branding', 'Marketing', 'UI/UX'],
|
||||
image: 'https://picsum.photos/id/180/1200/800',
|
||||
gallery: [
|
||||
'https://picsum.photos/id/180/800/600',
|
||||
'https://picsum.photos/id/181/800/600',
|
||||
'https://picsum.photos/id/182/800/600',
|
||||
'https://picsum.photos/id/183/800/600',
|
||||
],
|
||||
},
|
||||
{
|
||||
slug: 'nero-vision',
|
||||
category: 'development',
|
||||
year: '2025',
|
||||
tags: ['Development', 'Vue.js', 'Node.js'],
|
||||
image: 'https://picsum.photos/id/119/1200/800',
|
||||
gallery: [
|
||||
'https://picsum.photos/id/119/800/600',
|
||||
'https://picsum.photos/id/120/800/600',
|
||||
'https://picsum.photos/id/121/800/600',
|
||||
'https://picsum.photos/id/122/800/600',
|
||||
],
|
||||
},
|
||||
{
|
||||
slug: 'bold-moves',
|
||||
category: 'webDesign',
|
||||
year: '2024',
|
||||
tags: ['Web Design', '3D', 'Three.js'],
|
||||
image: 'https://picsum.photos/id/164/1200/800',
|
||||
gallery: [
|
||||
'https://picsum.photos/id/164/800/600',
|
||||
'https://picsum.photos/id/165/800/600',
|
||||
'https://picsum.photos/id/166/800/600',
|
||||
'https://picsum.photos/id/167/800/600',
|
||||
],
|
||||
},
|
||||
{
|
||||
slug: 'echo-labs',
|
||||
category: 'branding',
|
||||
year: '2025',
|
||||
tags: ['Branding', 'Visual Identity', 'Corporate'],
|
||||
image: 'https://picsum.photos/id/101/1200/800',
|
||||
gallery: [
|
||||
'https://picsum.photos/id/101/800/600',
|
||||
'https://picsum.photos/id/102/800/600',
|
||||
'https://picsum.photos/id/103/800/600',
|
||||
'https://picsum.photos/id/104/800/600',
|
||||
],
|
||||
},
|
||||
{
|
||||
slug: 'flux-api',
|
||||
category: 'development',
|
||||
year: '2025',
|
||||
tags: ['Development', 'API', 'Python'],
|
||||
image: 'https://picsum.photos/id/326/1200/800',
|
||||
gallery: [
|
||||
'https://picsum.photos/id/326/800/600',
|
||||
'https://picsum.photos/id/327/800/600',
|
||||
'https://picsum.photos/id/328/800/600',
|
||||
'https://picsum.photos/id/329/800/600',
|
||||
],
|
||||
},
|
||||
]
|
||||
|
||||
export const workBySlug: Record<string, WorkItem> = Object.fromEntries(
|
||||
workItems.map((item) => [item.slug, item]),
|
||||
)
|
||||
|
||||
export function getWorkCategories(): Array<WorkItem['category']> {
|
||||
return ['webDesign', 'branding', 'development']
|
||||
}
|
||||
@@ -0,0 +1,308 @@
|
||||
<template>
|
||||
<main class="page-container min-h-screen pt-32 pb-20 px-4 md:px-8 mx-auto max-w-[1200px]">
|
||||
<!-- 未登录 -->
|
||||
<div
|
||||
v-if="!userStore.isAuthenticated"
|
||||
class="max-w-md mx-auto mt-16 p-10 rounded-3xl bg-white border border-gray-100 shadow-xl text-center"
|
||||
>
|
||||
<div class="w-16 h-16 mx-auto rounded-full bg-gray-100 flex items-center justify-center mb-6">
|
||||
<Icon name="ph:user-duotone" class="w-8 h-8 text-gray-400" />
|
||||
</div>
|
||||
<h1 class="text-2xl font-bold text-black mb-3">{{ t('account.title') }}</h1>
|
||||
<p class="text-gray-500 mb-8">{{ t('auth.loginRequired') }}</p>
|
||||
<button
|
||||
@click="authModal.openLogin()"
|
||||
class="px-8 py-3 rounded-full bg-black text-white font-semibold hover:bg-gray-800 transition-colors"
|
||||
>
|
||||
{{ t('auth.login') }}
|
||||
</button>
|
||||
</div>
|
||||
|
||||
<!-- 已登录 -->
|
||||
<div v-else>
|
||||
<div class="mb-10 text-center">
|
||||
<img :src="userStore.avatar" :alt="userStore.user?.username" class="w-20 h-20 rounded-full object-cover mx-auto mb-4" />
|
||||
<h1 class="text-3xl md:text-4xl font-bold text-black mb-2">{{ userStore.user?.username }}</h1>
|
||||
<p class="text-gray-500">{{ userStore.user?.email }}</p>
|
||||
</div>
|
||||
|
||||
<!-- 页签 -->
|
||||
<div class="flex justify-center gap-2 md:gap-3 mb-10 flex-wrap">
|
||||
<button
|
||||
v-for="tab in tabs"
|
||||
:key="tab.key"
|
||||
@click="switchTab(tab.key)"
|
||||
class="px-5 py-2 rounded-full text-sm md:text-base font-semibold transition-all duration-300"
|
||||
:class="activeTab === tab.key ? 'bg-black text-white shadow-lg' : 'bg-gray-100 text-gray-700 hover:bg-gray-200'"
|
||||
>
|
||||
{{ tab.label }}
|
||||
</button>
|
||||
</div>
|
||||
|
||||
<!-- 个人资料 -->
|
||||
<section v-if="activeTab === 'profile'" class="max-w-lg mx-auto space-y-5">
|
||||
<div class="p-6 rounded-2xl bg-white border border-gray-100 shadow-sm space-y-5">
|
||||
<div>
|
||||
<label class="block text-sm font-semibold text-gray-800 mb-2">{{ t('account.username') }}</label>
|
||||
<input v-model="profileForm.username" type="text" class="w-full px-4 py-3 rounded-xl border border-gray-200 focus:border-black focus:ring-2 focus:ring-black/5 outline-none transition-all" />
|
||||
</div>
|
||||
<div>
|
||||
<label class="block text-sm font-semibold text-gray-800 mb-2">{{ t('account.phone') }}</label>
|
||||
<input v-model="profileForm.phone" type="tel" class="w-full px-4 py-3 rounded-xl border border-gray-200 focus:border-black focus:ring-2 focus:ring-black/5 outline-none transition-all" />
|
||||
</div>
|
||||
<div>
|
||||
<label class="block text-sm font-semibold text-gray-800 mb-2">{{ t('account.email') }}</label>
|
||||
<input :value="userStore.user?.email" type="email" disabled class="w-full px-4 py-3 rounded-xl border border-gray-200 bg-gray-50 text-gray-500 cursor-not-allowed" />
|
||||
</div>
|
||||
<div class="grid grid-cols-2 gap-4 text-sm text-gray-600">
|
||||
<div>
|
||||
<p class="text-gray-400 mb-1">{{ t('account.joinedAt') }}</p>
|
||||
<p class="font-medium text-black">{{ formatDate(userStore.user?.createdAt) }}</p>
|
||||
</div>
|
||||
<div>
|
||||
<p class="text-gray-400 mb-1">{{ t('account.role') }}</p>
|
||||
<p class="font-medium text-black">
|
||||
{{ userStore.user?.role === 'admin' ? t('account.roleAdmin') : t('account.roleUser') }}
|
||||
</p>
|
||||
</div>
|
||||
</div>
|
||||
<p v-if="saveMessage" class="text-sm" :class="saveFailed ? 'text-red-600' : 'text-green-600'">{{ saveMessage }}</p>
|
||||
<button
|
||||
@click="saveProfile"
|
||||
:disabled="saving"
|
||||
class="w-full py-3 rounded-xl bg-black text-white font-semibold flex items-center justify-center gap-2 transition-colors disabled:opacity-50"
|
||||
>
|
||||
<Icon v-if="saving" name="ph:circle-notch" class="w-5 h-5 animate-spin" />
|
||||
{{ saving ? t('account.saving') : t('account.save') }}
|
||||
</button>
|
||||
</div>
|
||||
</section>
|
||||
|
||||
<!-- 我的收藏 -->
|
||||
<section v-if="activeTab === 'favorites'" class="max-w-3xl mx-auto">
|
||||
<p v-if="!favorites.length" class="text-center text-gray-500 py-12">{{ t('account.emptyFavorites') }}</p>
|
||||
<div v-else class="grid grid-cols-1 sm:grid-cols-2 gap-5">
|
||||
<div
|
||||
v-for="slug in favorites"
|
||||
:key="slug"
|
||||
class="group rounded-2xl overflow-hidden bg-white border border-gray-100 shadow-sm hover:shadow-xl transition-all duration-300"
|
||||
>
|
||||
<NuxtLink :to="`/work/${slug}`" class="block relative aspect-[4/3] overflow-hidden">
|
||||
<img :src="workBySlug[slug]?.image" :alt="t(`work.items.${slug}.title`)" class="w-full h-full object-cover transition-transform duration-500 group-hover:scale-105" />
|
||||
</NuxtLink>
|
||||
<div class="p-5 flex items-center justify-between">
|
||||
<NuxtLink :to="`/work/${slug}`" class="font-bold text-black group-hover:text-gray-600 transition-colors">
|
||||
{{ t(`work.items.${slug}.title`) }}
|
||||
</NuxtLink>
|
||||
<button
|
||||
@click="removeFavorite(slug)"
|
||||
class="w-9 h-9 rounded-full bg-gray-50 text-gray-500 hover:bg-red-50 hover:text-red-600 flex items-center justify-center transition-colors"
|
||||
aria-label="unfavorite"
|
||||
>
|
||||
<Icon name="ph:bookmark-simple-fill" class="w-4 h-4" />
|
||||
</button>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
</section>
|
||||
|
||||
<!-- 我的评论 -->
|
||||
<section v-if="activeTab === 'comments'" class="max-w-2xl mx-auto space-y-4">
|
||||
<p v-if="!myComments.length" class="text-center text-gray-500 py-12">{{ t('account.emptyComments') }}</p>
|
||||
<div
|
||||
v-for="comment in myComments"
|
||||
:key="comment.id"
|
||||
class="p-5 rounded-2xl bg-white border border-gray-100 shadow-sm"
|
||||
>
|
||||
<div class="flex items-center justify-between mb-2">
|
||||
<NuxtLink :to="`/news/${comment.newsSlug}`" class="text-sm font-semibold text-black hover:text-gray-600">
|
||||
{{ t(`news.items.${comment.newsSlug}.title`) }}
|
||||
</NuxtLink>
|
||||
<span class="text-xs text-gray-400">{{ formatDate(comment.createdAt) }}</span>
|
||||
</div>
|
||||
<p class="text-gray-700 text-sm break-words">{{ comment.content }}</p>
|
||||
</div>
|
||||
</section>
|
||||
|
||||
<!-- 管理面板 -->
|
||||
<section v-if="activeTab === 'admin'" class="max-w-4xl mx-auto space-y-12">
|
||||
<div>
|
||||
<h3 class="text-xl font-bold text-black mb-5">{{ t('account.admin.contacts') }}</h3>
|
||||
<p v-if="!adminData.contacts.length" class="text-gray-500 text-center py-8">{{ t('account.admin.emptyContacts') }}</p>
|
||||
<div v-else class="space-y-4">
|
||||
<div v-for="c in adminData.contacts" :key="c.id" class="p-5 rounded-2xl bg-white border border-gray-100 shadow-sm">
|
||||
<div class="flex items-center justify-between mb-2">
|
||||
<div class="flex items-center gap-3">
|
||||
<span class="font-semibold text-black">{{ c.name }}</span>
|
||||
<span class="text-sm text-gray-500">{{ c.email }}</span>
|
||||
</div>
|
||||
<span class="text-xs px-2 py-1 rounded-full" :class="c.delivered ? 'bg-green-50 text-green-700' : 'bg-amber-50 text-amber-700'">
|
||||
{{ c.delivered ? t('account.admin.delivered') : t('account.admin.notDelivered') }}
|
||||
</span>
|
||||
</div>
|
||||
<p class="text-sm font-semibold text-gray-700 mb-1">{{ c.subject }}</p>
|
||||
<p class="text-sm text-gray-600 whitespace-pre-line break-words mb-2">{{ c.message }}</p>
|
||||
<p class="text-xs text-gray-400">{{ formatDate(c.createdAt) }}</p>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<div>
|
||||
<h3 class="text-xl font-bold text-black mb-5">{{ t('account.admin.subscribers') }}</h3>
|
||||
<p v-if="!adminData.subscribers.length" class="text-gray-500 text-center py-8">{{ t('account.admin.emptySubscribers') }}</p>
|
||||
<div v-else class="rounded-2xl overflow-hidden border border-gray-100 shadow-sm bg-white">
|
||||
<div v-for="s in adminData.subscribers" :key="s.id" class="flex items-center justify-between px-5 py-3 border-b border-gray-100 last:border-b-0">
|
||||
<span class="text-sm font-medium text-gray-700">{{ s.email }}</span>
|
||||
<span class="text-xs text-gray-400">{{ formatDate(s.createdAt) }}</span>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
</section>
|
||||
</div>
|
||||
</main>
|
||||
</template>
|
||||
|
||||
<script setup lang="ts">
|
||||
import { nextTick, onBeforeUnmount, onMounted, reactive, ref, computed } from 'vue'
|
||||
import { useI18n } from 'vue-i18n'
|
||||
import { useSeoMeta } from '#imports'
|
||||
import gsap from 'gsap'
|
||||
import { useUserStore } from '~/stores/user'
|
||||
import { useAuthModalStore } from '~/stores/authModal'
|
||||
import { workBySlug } from '~/data/work'
|
||||
import { useApiError } from '~/composables/useApiError'
|
||||
|
||||
const { t, locale } = useI18n()
|
||||
const userStore = useUserStore()
|
||||
const authModal = useAuthModalStore()
|
||||
const apiError = useApiError()
|
||||
|
||||
useSeoMeta({
|
||||
title: () => t('account.title'),
|
||||
})
|
||||
|
||||
const tabs = computed(() => {
|
||||
const list: Array<{ key: string; label: string }> = [
|
||||
{ key: 'profile', label: t('account.profile') },
|
||||
{ key: 'favorites', label: t('account.favorites') },
|
||||
{ key: 'comments', label: t('account.comments') },
|
||||
]
|
||||
if (userStore.user?.role === 'admin') {
|
||||
list.push({ key: 'admin', label: t('account.adminTitle') })
|
||||
}
|
||||
return list
|
||||
})
|
||||
|
||||
const activeTab = ref('profile')
|
||||
const switchTab = (key: string) => {
|
||||
activeTab.value = key
|
||||
if (key === 'favorites') loadFavorites()
|
||||
if (key === 'comments') loadComments()
|
||||
if (key === 'admin') loadAdmin()
|
||||
}
|
||||
|
||||
const formatDate = (raw?: string) => {
|
||||
if (!raw) return ''
|
||||
const d = new Date(String(raw).replace(' ', 'T') + 'Z')
|
||||
if (Number.isNaN(d.getTime())) return raw
|
||||
return new Intl.DateTimeFormat(locale.value === 'zh' ? 'zh-CN' : 'en-US', {
|
||||
year: 'numeric',
|
||||
month: 'short',
|
||||
day: 'numeric',
|
||||
}).format(d)
|
||||
}
|
||||
|
||||
// ---- 个人资料 ----
|
||||
const profileForm = reactive({ username: '', phone: '' })
|
||||
const saving = ref(false)
|
||||
const saveMessage = ref('')
|
||||
const saveFailed = ref(false)
|
||||
|
||||
const initProfileForm = () => {
|
||||
profileForm.username = userStore.user?.username ?? ''
|
||||
profileForm.phone = userStore.user?.phone ?? ''
|
||||
}
|
||||
|
||||
const saveProfile = async () => {
|
||||
saving.value = true
|
||||
saveMessage.value = ''
|
||||
saveFailed.value = false
|
||||
const result = await userStore.updateProfile({
|
||||
username: profileForm.username,
|
||||
phone: profileForm.phone,
|
||||
})
|
||||
if (result.success) {
|
||||
saveMessage.value = t('account.saved')
|
||||
} else {
|
||||
saveFailed.value = true
|
||||
saveMessage.value = apiError({ data: { code: result.code } })
|
||||
}
|
||||
saving.value = false
|
||||
}
|
||||
|
||||
// ---- 收藏 ----
|
||||
const favorites = ref<string[]>([])
|
||||
const loadFavorites = async () => {
|
||||
try {
|
||||
const data = await $fetch<{ slugs: string[] }>('/api/favorites')
|
||||
favorites.value = data.slugs
|
||||
} catch (err) {
|
||||
console.error('load favorites error:', err)
|
||||
}
|
||||
}
|
||||
const removeFavorite = async (slug: string) => {
|
||||
try {
|
||||
await $fetch('/api/favorites', { method: 'DELETE', body: { workSlug: slug } })
|
||||
favorites.value = favorites.value.filter((s) => s !== slug)
|
||||
} catch (err) {
|
||||
console.error('remove favorite error:', err)
|
||||
}
|
||||
}
|
||||
|
||||
// ---- 我的评论 ----
|
||||
const myComments = ref<Array<{ id: number; newsSlug: string; content: string; createdAt: string }>>([])
|
||||
const loadComments = async () => {
|
||||
try {
|
||||
const data = await $fetch<{ comments: Array<{ id: number; newsSlug: string; content: string; createdAt: string }> }>('/api/account/comments')
|
||||
myComments.value = data.comments
|
||||
} catch (err) {
|
||||
console.error('load comments error:', err)
|
||||
}
|
||||
}
|
||||
|
||||
// ---- 管理面板 ----
|
||||
const adminData = reactive<{
|
||||
contacts: Array<{ id: number; name: string; email: string; subject: string; message: string; delivered: number; createdAt: string }>
|
||||
subscribers: Array<{ id: number; email: string; createdAt: string }>
|
||||
}>({ contacts: [], subscribers: [] })
|
||||
|
||||
const loadAdmin = async () => {
|
||||
try {
|
||||
const data = await $fetch<typeof adminData>('/api/account/admin')
|
||||
adminData.contacts = data.contacts
|
||||
adminData.subscribers = data.subscribers
|
||||
} catch (err) {
|
||||
console.error('load admin error:', err)
|
||||
}
|
||||
}
|
||||
|
||||
// ---- 页面进场动画 ----
|
||||
const mainRef = ref<HTMLElement | null>(null)
|
||||
let ctx: gsap.Context | null = null
|
||||
|
||||
onMounted(async () => {
|
||||
await nextTick()
|
||||
initProfileForm()
|
||||
ctx = gsap.context(() => {
|
||||
const targets = gsap.utils.toArray<HTMLElement>('[data-animate]', mainRef.value!)
|
||||
if (targets.length) {
|
||||
gsap.set(targets, { autoAlpha: 0, y: 24 })
|
||||
gsap.to(targets, { autoAlpha: 1, y: 0, duration: 0.6, ease: 'power3.out', stagger: 0.08 })
|
||||
}
|
||||
}, mainRef.value)
|
||||
})
|
||||
|
||||
onBeforeUnmount(() => {
|
||||
ctx?.revert()
|
||||
})
|
||||
</script>
|
||||
+10
-36
@@ -139,7 +139,7 @@
|
||||
</div>
|
||||
<div>
|
||||
<h3 class="text-base md:text-lg font-bold text-gray-900 mb-2">Email</h3>
|
||||
<a href="mailto:chenchun@virtheart.com" class="text-sm md:text-base text-gray-600 hover:text-black transition-colors duration-300">
|
||||
<a :href="`mailto:${siteConfig.email}`" class="text-sm md:text-base text-gray-600 hover:text-black transition-colors duration-300">
|
||||
{{ t('contact.info.email') }}
|
||||
</a>
|
||||
</div>
|
||||
@@ -198,6 +198,7 @@ import { useI18n } from 'vue-i18n'
|
||||
import { useSeoMeta } from '#imports'
|
||||
import gsap from 'gsap'
|
||||
import { useAppStore } from '~/stores/app'
|
||||
import { siteConfig } from '~/config/site'
|
||||
|
||||
const { t } = useI18n()
|
||||
const appStore = useAppStore()
|
||||
@@ -234,16 +235,8 @@ const handleSubmit = async () => {
|
||||
statusMessage.value = ''
|
||||
|
||||
try {
|
||||
// 模拟 API 调用 - 你需要替换为真实的邮件服务
|
||||
// 可选方案:
|
||||
// 1. 使用 Nuxt server API: await $fetch('/api/contact', { method: 'POST', body: form })
|
||||
// 2. 使用 Formspree: await fetch('https://formspree.io/f/YOUR_ID', { ... })
|
||||
// 3. 使用 EmailJS 等第三方服务
|
||||
|
||||
await new Promise(resolve => setTimeout(resolve, 1500)) // 模拟网络延迟
|
||||
|
||||
// 模拟成功
|
||||
console.log('Form submitted:', form)
|
||||
// 真实提交到后端(落库 + 尽力发送邮件)
|
||||
await $fetch('/api/contact', { method: 'POST', body: { ...form } })
|
||||
|
||||
submitStatus.value = 'success'
|
||||
statusMessage.value = t('contact.form.successMessage') || 'Message sent successfully! We will get back to you soon.'
|
||||
@@ -253,16 +246,17 @@ const handleSubmit = async () => {
|
||||
form[key as keyof typeof form] = ''
|
||||
})
|
||||
|
||||
// 3秒后重置状态
|
||||
// 4秒后重置状态
|
||||
setTimeout(() => {
|
||||
submitStatus.value = 'idle'
|
||||
statusMessage.value = ''
|
||||
}, 3000)
|
||||
}, 4000)
|
||||
|
||||
} catch (error) {
|
||||
console.error('Form submission error:', error)
|
||||
submitStatus.value = 'error'
|
||||
statusMessage.value = t('contact.form.errorMessage') || 'Failed to send message. Please try again or contact us directly.'
|
||||
// 如实展示后端错误
|
||||
statusMessage.value = (error as any)?.data?.message || t('contact.form.errorMessage') || 'Failed to send message. Please try again or contact us directly.'
|
||||
} finally {
|
||||
isSubmitting.value = false
|
||||
}
|
||||
@@ -362,28 +356,8 @@ interface SocialLink {
|
||||
url: string
|
||||
}
|
||||
|
||||
const socials: SocialLink[] = [
|
||||
{
|
||||
name: 'Twitter',
|
||||
icon: 'ph:x-logo',
|
||||
url: 'https://twitter.com'
|
||||
},
|
||||
{
|
||||
name: 'Instagram',
|
||||
icon: 'ph:instagram-logo',
|
||||
url: 'https://instagram.com'
|
||||
},
|
||||
{
|
||||
name: 'LinkedIn',
|
||||
icon: 'ph:linkedin-logo',
|
||||
url: 'https://linkedin.com'
|
||||
},
|
||||
{
|
||||
name: 'GitHub',
|
||||
icon: 'ph:github-logo',
|
||||
url: 'https://github.com'
|
||||
}
|
||||
]
|
||||
// 社交链接统一取自站点配置(单一事实源)
|
||||
const socials: SocialLink[] = siteConfig.socials
|
||||
</script>
|
||||
|
||||
<style scoped>
|
||||
|
||||
+72
-103
@@ -15,7 +15,7 @@
|
||||
<section class="relative h-[50vh] md:h-[60vh] overflow-hidden">
|
||||
<img
|
||||
:src="article.image"
|
||||
:alt="article.title"
|
||||
:alt="title"
|
||||
class="w-full h-full object-cover"
|
||||
/>
|
||||
<div class="absolute inset-0 bg-gradient-to-t from-black/80 via-black/40 to-transparent"></div>
|
||||
@@ -25,19 +25,19 @@
|
||||
class="inline-block px-3 py-1.5 text-xs md:text-sm font-semibold rounded-full mb-4"
|
||||
:class="article.badge"
|
||||
>
|
||||
{{ article.category }}
|
||||
{{ t(`news.categories.${article.category}`) }}
|
||||
</span>
|
||||
<h1 class="text-3xl md:text-5xl lg:text-6xl font-bold text-white mb-4 tracking-tight">
|
||||
{{ article.title }}
|
||||
{{ title }}
|
||||
</h1>
|
||||
<div class="flex items-center gap-4 text-white/80 text-sm md:text-base">
|
||||
<span class="flex items-center gap-1.5">
|
||||
<Icon name="ph:calendar-blank" class="w-4 h-4" />
|
||||
{{ article.date }}
|
||||
{{ formatNewsDate(article.date, locale) }}
|
||||
</span>
|
||||
<span class="flex items-center gap-1.5">
|
||||
<Icon name="ph:clock" class="w-4 h-4" />
|
||||
{{ article.readTime }}
|
||||
{{ article.readTime }} {{ t('news.minutes') }}
|
||||
</span>
|
||||
<span class="flex items-center gap-1.5">
|
||||
<Icon name="ph:user" class="w-4 h-4" />
|
||||
@@ -62,7 +62,6 @@
|
||||
{{ t(`news.detail.items.${slug}.section1Content`) }}
|
||||
</p>
|
||||
|
||||
<!-- 引用 -->
|
||||
<blockquote class="border-l-4 border-black pl-6 my-10 italic text-gray-600 text-lg">
|
||||
"{{ t(`news.detail.items.${slug}.quote`) }}"
|
||||
</blockquote>
|
||||
@@ -74,9 +73,8 @@
|
||||
{{ t(`news.detail.items.${slug}.section2Content`) }}
|
||||
</p>
|
||||
|
||||
<!-- 文章内图片 -->
|
||||
<div class="my-10 rounded-2xl overflow-hidden">
|
||||
<img :src="article.image" :alt="article.title" class="w-full h-auto" />
|
||||
<img :src="article.image" :alt="title" class="w-full h-auto" />
|
||||
</div>
|
||||
|
||||
<h2 class="text-2xl md:text-3xl font-bold text-black mb-6 mt-12">
|
||||
@@ -87,23 +85,42 @@
|
||||
</p>
|
||||
</article>
|
||||
|
||||
<!-- 分享按钮 -->
|
||||
<!-- 分享按钮(真实动作) -->
|
||||
<div class="mt-16 pt-8 border-t border-gray-200">
|
||||
<div class="flex items-center justify-between">
|
||||
<p class="text-sm text-gray-500">{{ t('news.detail.shareArticle') }}</p>
|
||||
<div class="flex items-center justify-between flex-wrap gap-4">
|
||||
<p class="text-sm text-gray-500">{{ t('share.article') }}</p>
|
||||
<div class="flex gap-3">
|
||||
<button class="w-10 h-10 rounded-full bg-gray-100 hover:bg-black hover:text-white flex items-center justify-center transition-all duration-300">
|
||||
<button
|
||||
@click="shareToX"
|
||||
class="w-10 h-10 rounded-full bg-gray-100 hover:bg-black hover:text-white flex items-center justify-center transition-all duration-300"
|
||||
:title="'X'"
|
||||
aria-label="Share on X"
|
||||
>
|
||||
<Icon name="ph:x-logo" class="w-5 h-5" />
|
||||
</button>
|
||||
<button class="w-10 h-10 rounded-full bg-gray-100 hover:bg-black hover:text-white flex items-center justify-center transition-all duration-300">
|
||||
<button
|
||||
@click="shareToLinkedIn"
|
||||
class="w-10 h-10 rounded-full bg-gray-100 hover:bg-black hover:text-white flex items-center justify-center transition-all duration-300"
|
||||
:title="'LinkedIn'"
|
||||
aria-label="Share on LinkedIn"
|
||||
>
|
||||
<Icon name="ph:linkedin-logo" class="w-5 h-5" />
|
||||
</button>
|
||||
<button class="w-10 h-10 rounded-full bg-gray-100 hover:bg-black hover:text-white flex items-center justify-center transition-all duration-300">
|
||||
<button
|
||||
@click="copyLink"
|
||||
class="w-10 h-10 rounded-full bg-gray-100 hover:bg-black hover:text-white flex items-center justify-center transition-all duration-300"
|
||||
:title="t('share.copy')"
|
||||
aria-label="Copy link"
|
||||
>
|
||||
<Icon name="ph:link" class="w-5 h-5" />
|
||||
</button>
|
||||
</div>
|
||||
</div>
|
||||
<p v-if="copyFeedback" class="text-sm mt-3 text-green-600">{{ copyFeedback }}</p>
|
||||
</div>
|
||||
|
||||
<!-- 评论区 -->
|
||||
<CommentSection :news-slug="slug" />
|
||||
</section>
|
||||
|
||||
<!-- 相关文章 -->
|
||||
@@ -113,17 +130,17 @@
|
||||
<div class="grid grid-cols-1 md:grid-cols-3 gap-6">
|
||||
<NuxtLink
|
||||
v-for="related in relatedArticles"
|
||||
:key="related.id"
|
||||
:to="`/news/${related.id}`"
|
||||
:key="related.slug"
|
||||
:to="`/news/${related.slug}`"
|
||||
class="group block rounded-2xl overflow-hidden bg-white shadow-lg hover:shadow-xl transition-all duration-300 hover:-translate-y-1"
|
||||
>
|
||||
<div class="relative aspect-[16/10] overflow-hidden">
|
||||
<img :src="related.image" :alt="related.title" class="w-full h-full object-cover transition-transform duration-500 group-hover:scale-105" />
|
||||
<img :src="related.image" :alt="t(`news.items.${related.slug}.title`)" class="w-full h-full object-cover transition-transform duration-500 group-hover:scale-105" />
|
||||
</div>
|
||||
<div class="p-5">
|
||||
<span class="text-xs text-gray-500">{{ related.date }}</span>
|
||||
<span class="text-xs text-gray-500">{{ formatNewsDate(related.date, locale) }}</span>
|
||||
<h3 class="text-lg font-bold text-black group-hover:text-gray-600 transition-colors mt-1 line-clamp-2">
|
||||
{{ related.title }}
|
||||
{{ t(`news.items.${related.slug}.title`) }}
|
||||
</h3>
|
||||
</div>
|
||||
</NuxtLink>
|
||||
@@ -134,103 +151,55 @@
|
||||
</template>
|
||||
|
||||
<script setup lang="ts">
|
||||
import { computed } from 'vue'
|
||||
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 } = useI18n()
|
||||
const { t, locale } = useI18n()
|
||||
const route = useRoute()
|
||||
const slug = route.params.slug as string
|
||||
|
||||
interface NewsItem {
|
||||
id: string
|
||||
title: string
|
||||
image: string
|
||||
category: string
|
||||
badge: string
|
||||
date: string
|
||||
readTime: string
|
||||
author: string
|
||||
}
|
||||
|
||||
const newsData: Record<string, NewsItem> = {
|
||||
'design-trends-2026': {
|
||||
id: 'design-trends-2026',
|
||||
title: 'Design Trends Shaping 2026',
|
||||
image: 'https://picsum.photos/id/1/1200/800',
|
||||
category: 'Insights',
|
||||
badge: 'bg-purple-100 text-purple-700',
|
||||
date: 'May 28, 2026',
|
||||
readTime: '5 min',
|
||||
author: 'ArcticNewOne Team'
|
||||
},
|
||||
'forma-digital-launch': {
|
||||
id: 'forma-digital-launch',
|
||||
title: 'Forma Digital Platform Launch',
|
||||
image: 'https://picsum.photos/id/201/1200/800',
|
||||
category: 'Projects',
|
||||
badge: 'bg-blue-100 text-blue-700',
|
||||
date: 'May 15, 2026',
|
||||
readTime: '3 min',
|
||||
author: 'ArcticNewOne Team'
|
||||
},
|
||||
'studio-expansion': {
|
||||
id: 'studio-expansion',
|
||||
title: 'Studio Expansion Announcement',
|
||||
image: 'https://picsum.photos/id/164/1200/800',
|
||||
category: 'Announcements',
|
||||
badge: 'bg-green-100 text-green-700',
|
||||
date: 'May 10, 2026',
|
||||
readTime: '2 min',
|
||||
author: 'ArcticNewOne Team'
|
||||
},
|
||||
'ux-research-methods': {
|
||||
id: 'ux-research-methods',
|
||||
title: 'Modern UX Research Methods',
|
||||
image: 'https://picsum.photos/id/180/1200/800',
|
||||
category: 'Insights',
|
||||
badge: 'bg-purple-100 text-purple-700',
|
||||
date: 'Apr 28, 2026',
|
||||
readTime: '7 min',
|
||||
author: 'ArcticNewOne Team'
|
||||
},
|
||||
'bold-moves-case-study': {
|
||||
id: 'bold-moves-case-study',
|
||||
title: 'Bold Moves: A Case Study',
|
||||
image: 'https://picsum.photos/id/119/1200/800',
|
||||
category: 'Projects',
|
||||
badge: 'bg-blue-100 text-blue-700',
|
||||
date: 'Apr 20, 2026',
|
||||
readTime: '6 min',
|
||||
author: 'ArcticNewOne Team'
|
||||
},
|
||||
'new-tools-integration': {
|
||||
id: 'new-tools-integration',
|
||||
title: 'New Tools Added to Our Platform',
|
||||
image: 'https://picsum.photos/id/326/1200/800',
|
||||
category: 'Announcements',
|
||||
badge: 'bg-green-100 text-green-700',
|
||||
date: 'Apr 12, 2026',
|
||||
readTime: '4 min',
|
||||
author: 'ArcticNewOne Team'
|
||||
}
|
||||
}
|
||||
|
||||
const article = newsData[slug]
|
||||
const article = newsBySlug[slug]
|
||||
|
||||
if (!article) {
|
||||
throw createError({ statusCode: 404, statusMessage: 'Article not found' })
|
||||
}
|
||||
|
||||
const relatedArticles = computed(() => {
|
||||
return Object.values(newsData)
|
||||
.filter(a => a.id !== slug)
|
||||
.slice(0, 3)
|
||||
})
|
||||
const title = computed(() => t(`news.items.${slug}.title`))
|
||||
|
||||
const relatedArticles = newsItems.filter((a) => a.slug !== slug).slice(0, 3)
|
||||
|
||||
useSeoMeta({
|
||||
title: () => `${article.title} - ${t('news.title')}`,
|
||||
description: () => article.title,
|
||||
title: () => `${title.value} - ${t('news.title')}`,
|
||||
description: () => t(`news.items.${slug}.excerpt`),
|
||||
})
|
||||
|
||||
// ---- 分享(真实动作) ----
|
||||
const copyFeedback = ref('')
|
||||
|
||||
const shareUrl = () => (typeof window !== 'undefined' ? window.location.href : '')
|
||||
const shareText = () => title.value
|
||||
|
||||
const shareToX = () => {
|
||||
const url = `https://twitter.com/intent/tweet?url=${encodeURIComponent(shareUrl())}&text=${encodeURIComponent(shareText())}`
|
||||
window.open(url, '_blank', 'noopener,noreferrer,width=600,height=480')
|
||||
}
|
||||
|
||||
const shareToLinkedIn = () => {
|
||||
const url = `https://www.linkedin.com/sharing/share-offsite/?url=${encodeURIComponent(shareUrl())}`
|
||||
window.open(url, '_blank', 'noopener,noreferrer,width=600,height=480')
|
||||
}
|
||||
|
||||
const copyLink = async () => {
|
||||
try {
|
||||
await navigator.clipboard.writeText(shareUrl())
|
||||
copyFeedback.value = t('share.copied')
|
||||
} catch {
|
||||
// 剪贴板不可用时回退到 prompt 复制
|
||||
window.prompt(t('share.copyFailed'), shareUrl())
|
||||
}
|
||||
setTimeout(() => (copyFeedback.value = ''), 3000)
|
||||
}
|
||||
</script>
|
||||
|
||||
+80
-96
@@ -8,6 +8,20 @@
|
||||
<p ref="descRef" class="text-base md:text-lg text-gray-600 max-w-2xl">{{ t('news.description') }}</p>
|
||||
</div>
|
||||
|
||||
<!-- 搜索框 -->
|
||||
<div ref="searchWrapRef" class="flex justify-center mb-8">
|
||||
<div class="relative w-full max-w-md">
|
||||
<Icon name="ph:magnifying-glass" class="w-5 h-5 text-gray-400 absolute left-4 top-1/2 -translate-y-1/2" />
|
||||
<input
|
||||
v-model="keyword"
|
||||
type="text"
|
||||
:placeholder="t('search.placeholder')"
|
||||
class="w-full pl-12 pr-4 py-3 rounded-full border border-gray-200 focus:border-black focus:ring-2 focus:ring-black/5 outline-none transition-all duration-300 text-sm md:text-base"
|
||||
/>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<!-- 分类筛选 -->
|
||||
<div
|
||||
ref="filterWrapRef"
|
||||
class="flex justify-center gap-3 md:gap-4 mb-10 md:mb-14 flex-wrap"
|
||||
@@ -15,7 +29,7 @@
|
||||
<button
|
||||
v-for="category in categories"
|
||||
:key="category"
|
||||
@click="activeCategory = category"
|
||||
@click="setCategory(category)"
|
||||
class="px-5 md:px-6 py-2 md:py-2.5 rounded-full text-sm md:text-base font-semibold transition-all duration-300"
|
||||
:class="activeCategory === category
|
||||
? 'bg-black text-white shadow-lg'
|
||||
@@ -25,20 +39,28 @@
|
||||
</button>
|
||||
</div>
|
||||
|
||||
<!-- 空结果 -->
|
||||
<p v-if="!visibleNews.length" class="text-center text-gray-500 py-16">
|
||||
{{ t('search.empty') }}
|
||||
</p>
|
||||
|
||||
<!-- 文章列表 -->
|
||||
<div
|
||||
v-else
|
||||
ref="articlesWrapRef"
|
||||
class="grid grid-cols-1 md:grid-cols-2 lg:grid-cols-3 gap-6 md:gap-8"
|
||||
>
|
||||
<NuxtLink
|
||||
v-for="article in filteredNewsData"
|
||||
:key="article.id"
|
||||
:to="`/news/${article.id}`"
|
||||
v-for="article in visibleNews"
|
||||
:key="article.slug"
|
||||
:to="`/news/${article.slug}`"
|
||||
class="news-card group relative flex flex-col rounded-2xl md:rounded-3xl overflow-hidden bg-white border border-gray-100 hover:shadow-xl transition-all duration-500 cursor-pointer hover:-translate-y-2"
|
||||
>
|
||||
<div class="relative aspect-[16/10] overflow-hidden bg-gray-100">
|
||||
<img
|
||||
:src="article.image"
|
||||
:alt="article.title"
|
||||
:alt="t(`news.items.${article.slug}.title`)"
|
||||
:loading="'lazy'"
|
||||
class="w-full h-full object-cover transition-transform duration-700 group-hover:scale-110"
|
||||
/>
|
||||
<div class="absolute top-4 left-4">
|
||||
@@ -46,7 +68,7 @@
|
||||
class="px-3 py-1.5 text-xs md:text-sm font-semibold rounded-full shadow-sm"
|
||||
:class="article.badge"
|
||||
>
|
||||
{{ article.category }}
|
||||
{{ t(`news.categories.${article.category}`) }}
|
||||
</span>
|
||||
</div>
|
||||
</div>
|
||||
@@ -55,20 +77,20 @@
|
||||
<div class="flex items-center gap-3 text-xs md:text-sm text-gray-500 mb-3">
|
||||
<span class="flex items-center gap-1.5">
|
||||
<Icon name="ph:calendar-blank" class="w-4 h-4" />
|
||||
{{ article.date }}
|
||||
{{ formatNewsDate(article.date, locale) }}
|
||||
</span>
|
||||
<span class="flex items-center gap-1.5">
|
||||
<Icon name="ph:clock" class="w-4 h-4" />
|
||||
{{ article.readTime }}
|
||||
{{ article.readTime }} {{ t('news.minutes') }}
|
||||
</span>
|
||||
</div>
|
||||
|
||||
<h3 class="text-lg md:text-xl font-bold text-black mb-3 group-hover:text-gray-700 transition-colors duration-300 line-clamp-2">
|
||||
{{ article.title }}
|
||||
{{ t(`news.items.${article.slug}.title`) }}
|
||||
</h3>
|
||||
|
||||
<p class="text-sm md:text-base text-gray-600 mb-4 flex-grow line-clamp-3">
|
||||
{{ article.excerpt }}
|
||||
{{ t(`news.items.${article.slug}.excerpt`) }}
|
||||
</p>
|
||||
|
||||
<div class="flex items-center justify-between pt-3 border-t border-gray-100">
|
||||
@@ -82,6 +104,20 @@
|
||||
</div>
|
||||
</NuxtLink>
|
||||
</div>
|
||||
|
||||
<!-- 加载更多 -->
|
||||
<div v-if="hasMore" class="flex justify-center mt-12">
|
||||
<button
|
||||
@click="loadMore"
|
||||
class="px-8 py-3.5 rounded-full bg-black text-white font-semibold hover:bg-gray-800 transition-all duration-300 flex items-center gap-2"
|
||||
>
|
||||
<Icon name="ph:plus" class="w-5 h-5" />
|
||||
{{ t('pagination.loadMore') }}
|
||||
</button>
|
||||
</div>
|
||||
<p v-else-if="filteredNews.length > PAGE_SIZE" class="text-center text-gray-400 text-sm mt-8">
|
||||
{{ t('pagination.noMore') }}
|
||||
</p>
|
||||
</main>
|
||||
</template>
|
||||
|
||||
@@ -91,25 +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 } = useI18n()
|
||||
const { t, locale } = useI18n()
|
||||
const appStore = useAppStore()
|
||||
|
||||
const headerWrapRef = ref<HTMLElement | null>(null)
|
||||
const titleRef = ref<HTMLElement | null>(null)
|
||||
const descRef = ref<HTMLElement | null>(null)
|
||||
const searchWrapRef = ref<HTMLElement | null>(null)
|
||||
const filterWrapRef = ref<HTMLElement | null>(null)
|
||||
const articlesWrapRef = ref<HTMLElement | null>(null)
|
||||
const activeCategory = ref('all')
|
||||
const keyword = ref('')
|
||||
const visibleCount = ref(0)
|
||||
|
||||
const categories = ['all', 'insights', 'projects', 'announcements']
|
||||
const PAGE_SIZE = 6
|
||||
|
||||
const filteredNewsData = computed(() => {
|
||||
if (activeCategory.value === 'all') {
|
||||
return newsData
|
||||
}
|
||||
return newsData.filter(item => item.category.toLowerCase() === activeCategory.value.toLowerCase())
|
||||
const categories = ['all', ...getNewsCategories()]
|
||||
|
||||
// 分类 + 搜索过滤(标题/摘要按当前语言文案匹配)
|
||||
const filteredNews = computed(() => {
|
||||
const kw = keyword.value.trim().toLowerCase()
|
||||
return newsItems.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()
|
||||
return title.includes(kw) || excerpt.includes(kw)
|
||||
})
|
||||
})
|
||||
|
||||
const visibleNews = computed(() => filteredNews.value.slice(0, visibleCount.value))
|
||||
const hasMore = computed(() => visibleCount.value < filteredNews.value.length)
|
||||
|
||||
const setCategory = (category: string) => {
|
||||
activeCategory.value = category
|
||||
visibleCount.value = PAGE_SIZE
|
||||
}
|
||||
|
||||
const loadMore = () => {
|
||||
visibleCount.value = Math.min(visibleCount.value + PAGE_SIZE, filteredNews.value.length)
|
||||
}
|
||||
|
||||
useSeoMeta({
|
||||
title: () => t('news.title'),
|
||||
@@ -123,101 +182,26 @@ const playPageIntro = async () => {
|
||||
const filterButtons = gsap.utils.toArray<HTMLElement>('button', filterWrapRef.value!)
|
||||
const newsCards = gsap.utils.toArray<HTMLElement>('.news-card', articlesWrapRef.value!)
|
||||
|
||||
// 先设置初始状态,防止闪现
|
||||
gsap.set([titleRef.value, descRef.value, ...filterButtons, ...newsCards], {
|
||||
autoAlpha: 0, y: 30
|
||||
gsap.set([titleRef.value, descRef.value, searchWrapRef.value, ...filterButtons, ...newsCards], {
|
||||
autoAlpha: 0, y: 30,
|
||||
})
|
||||
|
||||
// 然后播放动画
|
||||
const tl = gsap.timeline({ defaults: { ease: 'power2.out' } })
|
||||
|
||||
tl.to(titleRef.value, { autoAlpha: 1, y: 0, duration: 0.5 })
|
||||
tl.to(descRef.value, { autoAlpha: 1, y: 0, duration: 0.4 }, '-=0.3')
|
||||
tl.to(searchWrapRef.value, { autoAlpha: 1, y: 0, duration: 0.4 }, '-=0.2')
|
||||
tl.to(filterButtons, { autoAlpha: 1, y: 0, duration: 0.4, stagger: 0.05 }, '-=0.2')
|
||||
tl.to(newsCards, { autoAlpha: 1, y: 0, duration: 0.5, stagger: 0.08 }, '-=0.2')
|
||||
}
|
||||
|
||||
onMounted(() => {
|
||||
visibleCount.value = PAGE_SIZE
|
||||
if (!appStore.isAppLoading) {
|
||||
playPageIntro()
|
||||
} else {
|
||||
window.addEventListener('app-loading-done', playPageIntro, { once: true })
|
||||
}
|
||||
})
|
||||
|
||||
interface NewsItem {
|
||||
id: string
|
||||
title: string
|
||||
excerpt: string
|
||||
image: string
|
||||
category: string
|
||||
badge: string
|
||||
date: string
|
||||
readTime: string
|
||||
}
|
||||
|
||||
const newsData: NewsItem[] = [
|
||||
{
|
||||
id: 'design-trends-2026',
|
||||
title: 'Design Trends Shaping 2026',
|
||||
excerpt: 'Explore the emerging design trends that are defining digital experiences this year, from minimalism to bold typography.',
|
||||
image: 'https://picsum.photos/id/1/800/500',
|
||||
category: 'Insights',
|
||||
badge: 'bg-purple-100 text-purple-700',
|
||||
date: 'May 28, 2026',
|
||||
readTime: '5 min'
|
||||
},
|
||||
{
|
||||
id: '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.',
|
||||
image: 'https://picsum.photos/id/201/800/500',
|
||||
category: 'Projects',
|
||||
badge: 'bg-blue-100 text-blue-700',
|
||||
date: 'May 15, 2026',
|
||||
readTime: '3 min'
|
||||
},
|
||||
{
|
||||
id: 'studio-expansion',
|
||||
title: 'Studio Expansion Announcement',
|
||||
excerpt: 'ArcticNewOne is growing! We are expanding our team and capabilities to serve you better.',
|
||||
image: 'https://picsum.photos/id/164/800/500',
|
||||
category: 'Announcements',
|
||||
badge: 'bg-green-100 text-green-700',
|
||||
date: 'May 10, 2026',
|
||||
readTime: '2 min'
|
||||
},
|
||||
{
|
||||
id: 'ux-research-methods',
|
||||
title: 'Modern UX Research Methods',
|
||||
excerpt: 'Dive into the latest user experience research methodologies that inform our design decisions.',
|
||||
image: 'https://picsum.photos/id/180/800/500',
|
||||
category: 'Insights',
|
||||
badge: 'bg-purple-100 text-purple-700',
|
||||
date: 'Apr 28, 2026',
|
||||
readTime: '7 min'
|
||||
},
|
||||
{
|
||||
id: '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.',
|
||||
image: 'https://picsum.photos/id/119/800/500',
|
||||
category: 'Projects',
|
||||
badge: 'bg-blue-100 text-blue-700',
|
||||
date: 'Apr 20, 2026',
|
||||
readTime: '6 min'
|
||||
},
|
||||
{
|
||||
id: 'new-tools-integration',
|
||||
title: 'New Tools Added to Our Platform',
|
||||
excerpt: 'Check out the latest additions to our toolbox, designed to streamline your workflow and boost productivity.',
|
||||
image: 'https://picsum.photos/id/326/800/500',
|
||||
category: 'Announcements',
|
||||
badge: 'bg-green-100 text-green-700',
|
||||
date: 'Apr 12, 2026',
|
||||
readTime: '4 min'
|
||||
}
|
||||
]
|
||||
</script>
|
||||
|
||||
<style scoped>
|
||||
|
||||
+22
-124
@@ -15,7 +15,7 @@
|
||||
<section class="relative h-[60vh] md:h-[70vh] overflow-hidden">
|
||||
<img
|
||||
:src="project.image"
|
||||
:alt="project.title"
|
||||
:alt="title"
|
||||
class="w-full h-full object-cover"
|
||||
/>
|
||||
<div class="absolute inset-0 bg-gradient-to-t from-black/80 via-black/40 to-transparent"></div>
|
||||
@@ -31,10 +31,10 @@
|
||||
</span>
|
||||
</div>
|
||||
<h1 class="text-4xl md:text-6xl lg:text-7xl font-bold text-white mb-4 tracking-tight">
|
||||
{{ project.title }}
|
||||
{{ title }}
|
||||
</h1>
|
||||
<p class="text-lg md:text-xl text-white/80 max-w-2xl">
|
||||
{{ project.description }}
|
||||
{{ t(`work.items.${slug}.description`) }}
|
||||
</p>
|
||||
</div>
|
||||
</div>
|
||||
@@ -75,7 +75,7 @@
|
||||
:key="index"
|
||||
class="rounded-2xl overflow-hidden shadow-lg hover:shadow-2xl transition-shadow duration-300"
|
||||
>
|
||||
<img :src="img" :alt="`${project.title} screenshot ${index + 1}`" class="w-full h-auto" />
|
||||
<img :src="img" :alt="`${title} screenshot ${index + 1}`" class="w-full h-auto" />
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
@@ -113,17 +113,22 @@
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<!-- 访问项目按钮 -->
|
||||
<div class="mt-8 space-y-3">
|
||||
<!-- 访问项目(仅存在真实地址时渲染) -->
|
||||
<a
|
||||
v-if="project.url"
|
||||
:href="project.url"
|
||||
target="_blank"
|
||||
rel="noopener noreferrer"
|
||||
class="mt-8 w-full inline-flex items-center justify-center gap-2 px-6 py-3.5 rounded-full bg-black text-white font-semibold hover:bg-gray-800 transition-colors duration-300"
|
||||
class="w-full inline-flex items-center justify-center gap-2 px-6 py-3.5 rounded-full bg-black text-white font-semibold hover:bg-gray-800 transition-colors duration-300"
|
||||
>
|
||||
{{ t('work.detail.visitProject') }}
|
||||
<Icon name="ph:arrow-up-right" class="w-5 h-5" />
|
||||
</a>
|
||||
|
||||
<!-- 收藏 -->
|
||||
<FavoriteButton :work-slug="slug" />
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
@@ -136,15 +141,15 @@
|
||||
<div class="grid grid-cols-1 md:grid-cols-3 gap-6">
|
||||
<NuxtLink
|
||||
v-for="related in relatedProjects"
|
||||
:key="related.id"
|
||||
:to="`/work/${related.id}`"
|
||||
:key="related.slug"
|
||||
:to="`/work/${related.slug}`"
|
||||
class="group block rounded-2xl overflow-hidden bg-white shadow-lg hover:shadow-xl transition-all duration-300 hover:-translate-y-1"
|
||||
>
|
||||
<div class="relative aspect-[4/3] overflow-hidden">
|
||||
<img :src="related.image" :alt="related.title" class="w-full h-full object-cover transition-transform duration-500 group-hover:scale-105" />
|
||||
<img :src="related.image" :alt="t(`work.items.${related.slug}.title`)" class="w-full h-full object-cover transition-transform duration-500 group-hover:scale-105" />
|
||||
</div>
|
||||
<div class="p-5">
|
||||
<h3 class="text-lg font-bold text-black group-hover:text-gray-600 transition-colors">{{ related.title }}</h3>
|
||||
<h3 class="text-lg font-bold text-black group-hover:text-gray-600 transition-colors">{{ t(`work.items.${related.slug}.title`) }}</h3>
|
||||
<p class="text-sm text-gray-500 mt-1">{{ related.tags[0] }}</p>
|
||||
</div>
|
||||
</NuxtLink>
|
||||
@@ -159,131 +164,24 @@ 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 route = useRoute()
|
||||
const slug = route.params.slug as string
|
||||
|
||||
interface WorkItem {
|
||||
id: string
|
||||
title: string
|
||||
description: string
|
||||
image: string
|
||||
tags: string[]
|
||||
category: string
|
||||
year: string
|
||||
url?: string
|
||||
gallery: string[]
|
||||
}
|
||||
|
||||
const workData: Record<string, WorkItem> = {
|
||||
'forma-digital': {
|
||||
id: 'forma-digital',
|
||||
title: 'Forma Digital',
|
||||
description: 'A modern e-commerce platform with seamless user experience and dynamic product showcases.',
|
||||
image: 'https://picsum.photos/id/201/1200/800',
|
||||
tags: ['Web Design', 'E-commerce', 'React'],
|
||||
category: 'webDesign',
|
||||
year: '2026',
|
||||
url: '#',
|
||||
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',
|
||||
]
|
||||
},
|
||||
'one-step': {
|
||||
id: 'one-step',
|
||||
title: 'One Step',
|
||||
description: 'Brand identity and marketing campaign for a fitness app focused on sustainable habits.',
|
||||
image: 'https://picsum.photos/id/180/1200/800',
|
||||
tags: ['Branding', 'Marketing', 'UI/UX'],
|
||||
category: 'branding',
|
||||
year: '2024',
|
||||
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',
|
||||
]
|
||||
},
|
||||
'nero-vision': {
|
||||
id: 'nero-vision',
|
||||
title: 'Nero Vision',
|
||||
description: 'Full-stack web application for creative professionals to manage their portfolios.',
|
||||
image: 'https://picsum.photos/id/119/1200/800',
|
||||
tags: ['Development', 'Vue.js', 'Node.js'],
|
||||
category: 'development',
|
||||
year: '2025',
|
||||
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',
|
||||
]
|
||||
},
|
||||
'bold-moves': {
|
||||
id: 'bold-moves',
|
||||
title: 'Bold Moves',
|
||||
description: 'Interactive website showcasing innovative architectural designs with 3D visualizations.',
|
||||
image: 'https://picsum.photos/id/164/1200/800',
|
||||
tags: ['Web Design', '3D', 'Three.js'],
|
||||
category: 'webDesign',
|
||||
year: '2024',
|
||||
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',
|
||||
]
|
||||
},
|
||||
'echo-labs': {
|
||||
id: 'echo-labs',
|
||||
title: 'Echo Labs',
|
||||
description: 'Corporate branding and visual identity for a tech startup in the AI space.',
|
||||
image: 'https://picsum.photos/id/101/1200/800',
|
||||
tags: ['Branding', 'Visual Identity', 'Corporate'],
|
||||
category: 'branding',
|
||||
year: '2025',
|
||||
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',
|
||||
]
|
||||
},
|
||||
'flux-api': {
|
||||
id: 'flux-api',
|
||||
title: 'Flux API',
|
||||
description: 'Scalable REST API with comprehensive documentation and developer tools.',
|
||||
image: 'https://picsum.photos/id/326/1200/800',
|
||||
tags: ['Development', 'API', 'Python'],
|
||||
category: 'development',
|
||||
year: '2025',
|
||||
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',
|
||||
]
|
||||
}
|
||||
}
|
||||
|
||||
const project = workData[slug]
|
||||
const project = workBySlug[slug]
|
||||
|
||||
if (!project) {
|
||||
throw createError({ statusCode: 404, statusMessage: 'Project not found' })
|
||||
}
|
||||
|
||||
const relatedProjects = computed(() => {
|
||||
return Object.values(workData)
|
||||
.filter(p => p.id !== slug)
|
||||
.slice(0, 3)
|
||||
})
|
||||
const title = computed(() => t(`work.items.${slug}.title`))
|
||||
|
||||
const relatedProjects = workItems.filter((p) => p.slug !== slug).slice(0, 3)
|
||||
|
||||
useSeoMeta({
|
||||
title: () => `${project.title} - ${t('work.title')}`,
|
||||
description: () => project.description,
|
||||
title: () => `${title.value} - ${t('work.title')}`,
|
||||
description: () => t(`work.items.${slug}.description`),
|
||||
})
|
||||
</script>
|
||||
|
||||
+78
-78
@@ -8,6 +8,20 @@
|
||||
<p ref="descRef" class="text-base md:text-lg text-gray-600 max-w-2xl">{{ t('work.description') }}</p>
|
||||
</div>
|
||||
|
||||
<!-- 搜索框 -->
|
||||
<div ref="searchWrapRef" class="flex justify-center mb-8">
|
||||
<div class="relative w-full max-w-md">
|
||||
<Icon name="ph:magnifying-glass" class="w-5 h-5 text-gray-400 absolute left-4 top-1/2 -translate-y-1/2" />
|
||||
<input
|
||||
v-model="keyword"
|
||||
type="text"
|
||||
:placeholder="t('search.placeholder')"
|
||||
class="w-full pl-12 pr-4 py-3 rounded-full border border-gray-200 focus:border-black focus:ring-2 focus:ring-black/5 outline-none transition-all duration-300 text-sm md:text-base"
|
||||
/>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<!-- 分类筛选 -->
|
||||
<div
|
||||
ref="filterWrapRef"
|
||||
class="flex justify-center gap-3 md:gap-4 mb-10 md:mb-14 flex-wrap"
|
||||
@@ -15,7 +29,7 @@
|
||||
<button
|
||||
v-for="category in categories"
|
||||
:key="category"
|
||||
@click="activeCategory = category"
|
||||
@click="setCategory(category)"
|
||||
class="px-5 md:px-6 py-2 md:py-2.5 rounded-full text-sm md:text-base font-semibold transition-all duration-300"
|
||||
:class="activeCategory === category
|
||||
? 'bg-black text-white shadow-lg'
|
||||
@@ -25,20 +39,28 @@
|
||||
</button>
|
||||
</div>
|
||||
|
||||
<!-- 空结果 -->
|
||||
<p v-if="!visibleWork.length" class="text-center text-gray-500 py-16">
|
||||
{{ t('search.empty') }}
|
||||
</p>
|
||||
|
||||
<!-- 作品列表 -->
|
||||
<div
|
||||
v-else
|
||||
ref="projectsWrapRef"
|
||||
class="grid grid-cols-1 md:grid-cols-2 gap-6 md:gap-8"
|
||||
>
|
||||
<NuxtLink
|
||||
v-for="project in filteredWorkData"
|
||||
:key="project.id"
|
||||
:to="`/work/${project.id}`"
|
||||
v-for="project in visibleWork"
|
||||
:key="project.slug"
|
||||
:to="`/work/${project.slug}`"
|
||||
class="work-card group relative block rounded-2xl md:rounded-3xl overflow-hidden cursor-pointer hover:shadow-2xl transition-all duration-500"
|
||||
>
|
||||
<div class="relative aspect-[4/3] overflow-hidden bg-gray-100">
|
||||
<img
|
||||
:src="project.image"
|
||||
:alt="project.title"
|
||||
:alt="t(`work.items.${project.slug}.title`)"
|
||||
:loading="'lazy'"
|
||||
class="w-full h-full object-cover transition-transform duration-700 group-hover:scale-110"
|
||||
/>
|
||||
<div class="absolute inset-0 bg-gradient-to-t from-black/60 via-black/20 to-transparent opacity-0 group-hover:opacity-100 transition-opacity duration-500"></div>
|
||||
@@ -46,12 +68,14 @@
|
||||
|
||||
<div class="p-6 md:p-8 bg-white">
|
||||
<div class="flex items-start justify-between mb-3">
|
||||
<h3 class="text-xl md:text-2xl font-bold text-black group-hover:text-gray-700 transition-colors duration-300">{{ project.title }}</h3>
|
||||
<h3 class="text-xl md:text-2xl font-bold text-black group-hover:text-gray-700 transition-colors duration-300">
|
||||
{{ t(`work.items.${project.slug}.title`) }}
|
||||
</h3>
|
||||
<div class="w-9 h-9 md:w-10 md:h-10 rounded-full flex items-center justify-center bg-gray-50 text-gray-400 group-hover:bg-black group-hover:text-white transition-all duration-300 flex-shrink-0 ml-3">
|
||||
<Icon name="ph:arrow-up-right" class="w-4 h-4 md:w-5 md:h-5" />
|
||||
</div>
|
||||
</div>
|
||||
<p class="text-sm md:text-base text-gray-600 mb-4">{{ project.description }}</p>
|
||||
<p class="text-sm md:text-base text-gray-600 mb-4">{{ t(`work.items.${project.slug}.description`) }}</p>
|
||||
<div class="flex flex-wrap gap-2">
|
||||
<span
|
||||
v-for="tag in project.tags"
|
||||
@@ -64,6 +88,20 @@
|
||||
</div>
|
||||
</NuxtLink>
|
||||
</div>
|
||||
|
||||
<!-- 加载更多 -->
|
||||
<div v-if="hasMore" class="flex justify-center mt-12">
|
||||
<button
|
||||
@click="loadMore"
|
||||
class="px-8 py-3.5 rounded-full bg-black text-white font-semibold hover:bg-gray-800 transition-all duration-300 flex items-center gap-2"
|
||||
>
|
||||
<Icon name="ph:plus" class="w-5 h-5" />
|
||||
{{ t('pagination.loadMore') }}
|
||||
</button>
|
||||
</div>
|
||||
<p v-else-if="filteredWork.length > PAGE_SIZE" class="text-center text-gray-400 text-sm mt-8">
|
||||
{{ t('pagination.noMore') }}
|
||||
</p>
|
||||
</main>
|
||||
</template>
|
||||
|
||||
@@ -73,6 +111,7 @@ import { useI18n } from 'vue-i18n'
|
||||
import { useSeoMeta } from '#imports'
|
||||
import gsap from 'gsap'
|
||||
import { useAppStore } from '~/stores/app'
|
||||
import { workItems, getWorkCategories } from '~/data/work'
|
||||
|
||||
const { t } = useI18n()
|
||||
const appStore = useAppStore()
|
||||
@@ -80,18 +119,40 @@ const appStore = useAppStore()
|
||||
const headerWrapRef = ref<HTMLElement | null>(null)
|
||||
const titleRef = ref<HTMLElement | null>(null)
|
||||
const descRef = ref<HTMLElement | null>(null)
|
||||
const searchWrapRef = ref<HTMLElement | null>(null)
|
||||
const filterWrapRef = ref<HTMLElement | null>(null)
|
||||
const projectsWrapRef = ref<HTMLElement | null>(null)
|
||||
const activeCategory = ref('all')
|
||||
const keyword = ref('')
|
||||
const visibleCount = ref(0)
|
||||
|
||||
const categories = ['all', 'webDesign', 'branding', 'development']
|
||||
const PAGE_SIZE = 4
|
||||
|
||||
const filteredWorkData = computed(() => {
|
||||
if (activeCategory.value === 'all') {
|
||||
return workData
|
||||
}
|
||||
return workData.filter(item => item.category === activeCategory.value)
|
||||
const categories = ['all', ...getWorkCategories()]
|
||||
|
||||
// 分类 + 搜索过滤(标题/描述按当前语言文案匹配)
|
||||
const filteredWork = computed(() => {
|
||||
const kw = keyword.value.trim().toLowerCase()
|
||||
return workItems.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()
|
||||
return title.includes(kw) || desc.includes(kw)
|
||||
})
|
||||
})
|
||||
|
||||
const visibleWork = computed(() => filteredWork.value.slice(0, visibleCount.value))
|
||||
const hasMore = computed(() => visibleCount.value < filteredWork.value.length)
|
||||
|
||||
const setCategory = (category: string) => {
|
||||
activeCategory.value = category
|
||||
visibleCount.value = PAGE_SIZE
|
||||
}
|
||||
|
||||
const loadMore = () => {
|
||||
visibleCount.value = Math.min(visibleCount.value + PAGE_SIZE, filteredWork.value.length)
|
||||
}
|
||||
|
||||
useSeoMeta({
|
||||
title: () => t('work.title'),
|
||||
@@ -105,87 +166,26 @@ const playPageIntro = async () => {
|
||||
const filterButtons = gsap.utils.toArray<HTMLElement>('button', filterWrapRef.value!)
|
||||
const projectCards = gsap.utils.toArray<HTMLElement>('.work-card', projectsWrapRef.value!)
|
||||
|
||||
// 先设置初始状态,防止闪现
|
||||
gsap.set([titleRef.value, descRef.value, ...filterButtons, ...projectCards], {
|
||||
autoAlpha: 0, y: 30
|
||||
gsap.set([titleRef.value, descRef.value, searchWrapRef.value, ...filterButtons, ...projectCards], {
|
||||
autoAlpha: 0, y: 30,
|
||||
})
|
||||
|
||||
// 然后播放动画
|
||||
const tl = gsap.timeline({ defaults: { ease: 'power2.out' } })
|
||||
|
||||
tl.to(titleRef.value, { autoAlpha: 1, y: 0, duration: 0.5 })
|
||||
tl.to(descRef.value, { autoAlpha: 1, y: 0, duration: 0.4 }, '-=0.3')
|
||||
tl.to(searchWrapRef.value, { autoAlpha: 1, y: 0, duration: 0.4 }, '-=0.2')
|
||||
tl.to(filterButtons, { autoAlpha: 1, y: 0, duration: 0.4, stagger: 0.05 }, '-=0.2')
|
||||
tl.to(projectCards, { autoAlpha: 1, y: 0, duration: 0.5, stagger: 0.08 }, '-=0.2')
|
||||
}
|
||||
|
||||
onMounted(() => {
|
||||
visibleCount.value = PAGE_SIZE
|
||||
if (!appStore.isAppLoading) {
|
||||
playPageIntro()
|
||||
} else {
|
||||
window.addEventListener('app-loading-done', playPageIntro, { once: true })
|
||||
}
|
||||
})
|
||||
|
||||
interface WorkItem {
|
||||
id: string
|
||||
title: string
|
||||
description: string
|
||||
image: string
|
||||
tags: string[]
|
||||
category: string
|
||||
}
|
||||
|
||||
const workData: WorkItem[] = [
|
||||
{
|
||||
id: 'forma-digital',
|
||||
title: 'Forma Digital',
|
||||
description: 'A modern e-commerce platform with seamless user experience and dynamic product showcases.',
|
||||
image: 'https://picsum.photos/id/201/800/600',
|
||||
tags: ['Web Design', 'E-commerce', 'React'],
|
||||
category: 'webDesign'
|
||||
},
|
||||
{
|
||||
id: 'one-step',
|
||||
title: 'One Step',
|
||||
description: 'Brand identity and marketing campaign for a fitness app focused on sustainable habits.',
|
||||
image: 'https://picsum.photos/id/180/800/600',
|
||||
tags: ['Branding', 'Marketing', 'UI/UX'],
|
||||
category: 'branding'
|
||||
},
|
||||
{
|
||||
id: 'nero-vision',
|
||||
title: 'Nero Vision',
|
||||
description: 'Full-stack web application for creative professionals to manage their portfolios.',
|
||||
image: 'https://picsum.photos/id/119/800/600',
|
||||
tags: ['Development', 'Vue.js', 'Node.js'],
|
||||
category: 'development'
|
||||
},
|
||||
{
|
||||
id: 'bold-moves',
|
||||
title: 'Bold Moves',
|
||||
description: 'Interactive website showcasing innovative architectural designs with 3D visualizations.',
|
||||
image: 'https://picsum.photos/id/164/800/600',
|
||||
tags: ['Web Design', '3D', 'Three.js'],
|
||||
category: 'webDesign'
|
||||
},
|
||||
{
|
||||
id: 'echo-labs',
|
||||
title: 'Echo Labs',
|
||||
description: 'Corporate branding and visual identity for a tech startup in the AI space.',
|
||||
image: 'https://picsum.photos/id/101/800/600',
|
||||
tags: ['Branding', 'Visual Identity', 'Corporate'],
|
||||
category: 'branding'
|
||||
},
|
||||
{
|
||||
id: 'flux-api',
|
||||
title: 'Flux API',
|
||||
description: 'Scalable REST API with comprehensive documentation and developer tools.',
|
||||
image: 'https://picsum.photos/id/326/800/600',
|
||||
tags: ['Development', 'API', 'Python'],
|
||||
category: 'development'
|
||||
}
|
||||
]
|
||||
</script>
|
||||
|
||||
<style scoped>
|
||||
|
||||
@@ -0,0 +1,56 @@
|
||||
import { defineStore } from 'pinia'
|
||||
import { ref, watch } from 'vue'
|
||||
|
||||
/**
|
||||
* 登录/注册弹窗全局状态。
|
||||
* Header、个人中心、收藏/评论组件等都可直接 openLogin() 唤起登录弹窗,
|
||||
* 避免层层 prop/事件传递。
|
||||
*/
|
||||
export const useAuthModalStore = defineStore('authModal', () => {
|
||||
const isLoginOpen = ref(false)
|
||||
const isRegisterOpen = ref(false)
|
||||
|
||||
// 任一弹窗打开时锁定背景滚动
|
||||
watch(
|
||||
() => [isLoginOpen.value, isRegisterOpen.value],
|
||||
([login, register]) => {
|
||||
if (typeof document === 'undefined') return
|
||||
document.body.style.overflow = login || register ? 'hidden' : ''
|
||||
},
|
||||
)
|
||||
|
||||
const openLogin = () => {
|
||||
isRegisterOpen.value = false
|
||||
isLoginOpen.value = true
|
||||
}
|
||||
|
||||
const openRegister = () => {
|
||||
isLoginOpen.value = false
|
||||
isRegisterOpen.value = true
|
||||
}
|
||||
|
||||
const closeAll = () => {
|
||||
isLoginOpen.value = false
|
||||
isRegisterOpen.value = false
|
||||
}
|
||||
|
||||
const switchToRegister = () => {
|
||||
isLoginOpen.value = false
|
||||
isRegisterOpen.value = true
|
||||
}
|
||||
|
||||
const switchToLogin = () => {
|
||||
isRegisterOpen.value = false
|
||||
isLoginOpen.value = true
|
||||
}
|
||||
|
||||
return {
|
||||
isLoginOpen,
|
||||
isRegisterOpen,
|
||||
openLogin,
|
||||
openRegister,
|
||||
closeAll,
|
||||
switchToRegister,
|
||||
switchToLogin,
|
||||
}
|
||||
})
|
||||
+69
-84
@@ -2,120 +2,105 @@ import { defineStore } from 'pinia'
|
||||
import { ref, computed } from 'vue'
|
||||
|
||||
export interface User {
|
||||
id: string
|
||||
name: string
|
||||
id: number
|
||||
username: string
|
||||
email: string
|
||||
avatar?: string
|
||||
phone: string | null
|
||||
role: 'user' | 'admin'
|
||||
createdAt: string
|
||||
}
|
||||
|
||||
export interface ApiResult {
|
||||
success: boolean
|
||||
/** 后端错误码(供 useApiError 翻译),成功时为 null */
|
||||
code?: string | null
|
||||
}
|
||||
|
||||
const AVATAR_URL = (name: string) =>
|
||||
`https://ui-avatars.com/api/?name=${encodeURIComponent(name)}&background=000&color=fff&size=128`
|
||||
|
||||
/**
|
||||
* 用户会话状态(真实后端:httpOnly Cookie 会话)。
|
||||
*/
|
||||
export const useUserStore = defineStore('user', () => {
|
||||
const user = ref<User | null>(null)
|
||||
const isAuthenticated = computed(() => user.value !== null)
|
||||
|
||||
// 登录
|
||||
const login = async (account: string, password: string) => {
|
||||
const login = async (account: string, password: string): Promise<ApiResult> => {
|
||||
try {
|
||||
// 模拟 API 调用 - 你需要替换为真实的登录 API
|
||||
// const response = await $fetch('/api/auth/login', {
|
||||
// method: 'POST',
|
||||
// body: { account, password }
|
||||
// })
|
||||
|
||||
// 模拟延迟
|
||||
await new Promise(resolve => setTimeout(resolve, 1000))
|
||||
|
||||
// 判断账号类型并提取用户名
|
||||
let username = account
|
||||
if (account.includes('@')) {
|
||||
// 邮箱:使用 @ 前面的部分
|
||||
username = account.split('@')[0]
|
||||
} else if (/^1[3-9]\d{9}$/.test(account)) {
|
||||
// 手机号:使用后4位
|
||||
username = 'User_' + account.slice(-4)
|
||||
}
|
||||
// 其他情况:直接使用账号作为用户名
|
||||
|
||||
// 模拟成功登录
|
||||
user.value = {
|
||||
id: '1',
|
||||
name: username,
|
||||
email: account.includes('@') ? account : `${account}@example.com`,
|
||||
avatar: `https://ui-avatars.com/api/?name=${encodeURIComponent(username)}&background=000&color=fff&size=128`
|
||||
}
|
||||
|
||||
// 保存到 localStorage
|
||||
if (typeof window !== 'undefined') {
|
||||
localStorage.setItem('user', JSON.stringify(user.value))
|
||||
}
|
||||
|
||||
const data = await $fetch<{ user: User }>('/api/auth/login', {
|
||||
method: 'POST',
|
||||
body: { account, password },
|
||||
})
|
||||
user.value = data.user
|
||||
return { success: true }
|
||||
} catch (error) {
|
||||
console.error('Login error:', error)
|
||||
return { success: false, error: 'Login failed' }
|
||||
} catch (err) {
|
||||
return { success: false, code: (err as any)?.data?.code || 'SERVER_ERROR' }
|
||||
}
|
||||
}
|
||||
|
||||
// 注册(成功即自动登录)
|
||||
const register = async (data: {
|
||||
username: string
|
||||
email: string
|
||||
phone?: string
|
||||
password: string
|
||||
}): Promise<ApiResult> => {
|
||||
try {
|
||||
const res = await $fetch<{ user: User }>('/api/auth/register', {
|
||||
method: 'POST',
|
||||
body: data,
|
||||
})
|
||||
user.value = res.user
|
||||
return { success: true }
|
||||
} catch (err) {
|
||||
return { success: false, code: (err as any)?.data?.code || 'SERVER_ERROR' }
|
||||
}
|
||||
}
|
||||
|
||||
// 登出
|
||||
const logout = () => {
|
||||
const logout = async (): Promise<void> => {
|
||||
try {
|
||||
await $fetch('/api/auth/logout', { method: 'POST' })
|
||||
} catch (err) {
|
||||
console.error('logout error:', err)
|
||||
}
|
||||
user.value = null
|
||||
if (typeof window !== 'undefined') {
|
||||
localStorage.removeItem('user')
|
||||
}
|
||||
}
|
||||
|
||||
// 注册
|
||||
const register = async (data: { username: string; email: string; phone?: string; password: string }) => {
|
||||
// 从服务端会话恢复用户(应用启动时调用)
|
||||
const restoreUser = async (): Promise<void> => {
|
||||
try {
|
||||
// 模拟 API 调用 - 你需要替换为真实的注册 API
|
||||
// const response = await $fetch('/api/auth/register', {
|
||||
// method: 'POST',
|
||||
// body: data
|
||||
// })
|
||||
|
||||
// 模拟延迟
|
||||
await new Promise(resolve => setTimeout(resolve, 1000))
|
||||
|
||||
// 模拟成功注册并自动登录
|
||||
user.value = {
|
||||
id: Date.now().toString(),
|
||||
name: data.username,
|
||||
email: data.email,
|
||||
avatar: `https://ui-avatars.com/api/?name=${encodeURIComponent(data.username)}&background=000&color=fff&size=128`
|
||||
}
|
||||
|
||||
// 保存到 localStorage
|
||||
if (typeof window !== 'undefined') {
|
||||
localStorage.setItem('user', JSON.stringify(user.value))
|
||||
const data = await $fetch<{ user: User }>('/api/auth/me')
|
||||
user.value = data.user
|
||||
} catch (err) {
|
||||
user.value = null
|
||||
}
|
||||
}
|
||||
|
||||
// 更新资料
|
||||
const updateProfile = async (patch: { username?: string; phone?: string }): Promise<ApiResult> => {
|
||||
try {
|
||||
const data = await $fetch<{ user: User }>('/api/auth/me', { method: 'PATCH', body: patch })
|
||||
user.value = data.user
|
||||
return { success: true }
|
||||
} catch (error) {
|
||||
console.error('Register error:', error)
|
||||
return { success: false, error: 'Registration failed' }
|
||||
} catch (err) {
|
||||
return { success: false, code: (err as any)?.data?.code || 'SERVER_ERROR' }
|
||||
}
|
||||
}
|
||||
|
||||
// 从 localStorage 恢复用户状态
|
||||
const restoreUser = () => {
|
||||
if (typeof window !== 'undefined') {
|
||||
const savedUser = localStorage.getItem('user')
|
||||
if (savedUser) {
|
||||
try {
|
||||
user.value = JSON.parse(savedUser)
|
||||
} catch (error) {
|
||||
console.error('Failed to restore user:', error)
|
||||
localStorage.removeItem('user')
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
// 头像(按用户名生成,无后端存储)
|
||||
const avatar = computed(() => (user.value ? AVATAR_URL(user.value.username) : ''))
|
||||
|
||||
return {
|
||||
user,
|
||||
isAuthenticated,
|
||||
avatar,
|
||||
login,
|
||||
logout,
|
||||
register,
|
||||
logout,
|
||||
restoreUser,
|
||||
updateProfile,
|
||||
}
|
||||
})
|
||||
|
||||
+56
-27
@@ -1,13 +1,20 @@
|
||||
#!/usr/bin/env bash
|
||||
# =========================================================
|
||||
# Arcticnewone 镜像构建与推送脚本(本地 / 部署服务器手动执行)
|
||||
# Arcticnewone 镜像构建与推送脚本(版本化)
|
||||
#
|
||||
# 遵循团队部署规范:
|
||||
# - 镜像推送到华为云 SWR,tag 固定为 latest
|
||||
# - 多架构:linux/amd64 + linux/arm64
|
||||
# - 分架构推送(latest-amd64 / latest-arm64),再用 docker manifest
|
||||
# 合并为 latest(标准 Docker manifest list,SWR 可正常解析)
|
||||
# - --provenance=false 禁用 SLSA 证明,避免额外 manifest
|
||||
# 用法:
|
||||
# ./build-and-push.sh # 版本取最新 git tag(无 tag 时取短 commit)
|
||||
# ./build-and-push.sh 0.0.1-dev # 显式指定版本
|
||||
#
|
||||
# 版本与镜像 tag 对应:
|
||||
# git tag = 0.0.1-dev => 推送 arcticnewone:0.0.1-dev(amd64 单 manifest)
|
||||
# 同时更新 arcticnewone:latest(amd64 单 manifest)
|
||||
#
|
||||
# SWR 兼容性说明:
|
||||
# - SWR 无法解析 Docker manifest list(报 "Invalid image, fail to parse manifest.json"),
|
||||
# 因此版本 tag 与 latest 采用 **amd64 单架构 manifest**(生产集群为 amd64);
|
||||
# - 同时仍分架构推送 <tag>-amd64 / <tag>-arm64 与 latest-amd64 / latest-arm64,
|
||||
# 便于 arm64 环境按需使用。
|
||||
# - 登录凭据一律从环境变量读取,绝不写入仓库
|
||||
#
|
||||
# 使用前先设置环境变量(示例):
|
||||
@@ -15,8 +22,6 @@
|
||||
# export SWR_NAMESPACE="virtheart"
|
||||
# export SWR_USERNAME="<SWR 用户名>"
|
||||
# export SWR_PASSWORD="<SWR 密码>"
|
||||
# 然后执行:
|
||||
# ./build-and-push.sh
|
||||
# =========================================================
|
||||
set -euo pipefail
|
||||
|
||||
@@ -27,12 +32,34 @@ set -euo pipefail
|
||||
: "${SWR_PASSWORD:?请先设置环境变量 SWR_PASSWORD(SWR 登录密码)}"
|
||||
|
||||
IMAGE_NAME="arcticnewone"
|
||||
IMAGE_TAG="latest"
|
||||
FULL_IMAGE="${SWR_REGISTRY}/${SWR_NAMESPACE}/${IMAGE_NAME}:${IMAGE_TAG}"
|
||||
ARCHS="amd64 arm64"
|
||||
BUILDER_NAME="multiarch-builder"
|
||||
# 生产集群架构(作为版本 tag / latest 的单架构 manifest)
|
||||
PRIMARY_ARCH="amd64"
|
||||
|
||||
# 前置检查:docker / buildx / manifest
|
||||
# ---------- 版本解析 ----------
|
||||
# 优先级: 命令行参数 > 最新 git tag > 短 commit
|
||||
VERSION="${1:-}"
|
||||
if [ -z "${VERSION}" ]; then
|
||||
VERSION="$(git describe --tags --abbrev=0 2>/dev/null || true)"
|
||||
fi
|
||||
if [ -z "${VERSION}" ]; then
|
||||
VERSION="$(git rev-parse --short HEAD)"
|
||||
fi
|
||||
# 合法化 docker tag 字符集 [A-Za-z0-9_.-]
|
||||
VERSION="${VERSION//[^A-Za-z0-9_.-]/-}"
|
||||
|
||||
FULL_IMAGE="${SWR_REGISTRY}/${SWR_NAMESPACE}/${IMAGE_NAME}"
|
||||
VERSION_IMAGE="${FULL_IMAGE}:${VERSION}"
|
||||
LATEST_IMAGE="${FULL_IMAGE}:latest"
|
||||
|
||||
echo "=========================================================="
|
||||
echo " 版本: ${VERSION}"
|
||||
echo " 目标: ${VERSION_IMAGE} (latest 同步更新为 ${LATEST_IMAGE})"
|
||||
echo " 架构: 分架构 ${ARCHS// /, };版本/latest 以 ${PRIMARY_ARCH} 单 manifest 输出(SWR 兼容)"
|
||||
echo "=========================================================="
|
||||
|
||||
# 前置检查:docker / buildx
|
||||
if ! command -v docker >/dev/null 2>&1; then
|
||||
echo "错误: 未找到 docker 命令,请先安装 Docker" >&2
|
||||
exit 1
|
||||
@@ -41,37 +68,39 @@ if ! docker buildx version >/dev/null 2>&1; then
|
||||
echo "错误: 未找到 docker buildx,请启用 Buildx(Docker 20.10+ 默认内置)" >&2
|
||||
exit 1
|
||||
fi
|
||||
if ! docker manifest --help >/dev/null 2>&1; then
|
||||
echo "错误: 当前 Docker 不支持 docker manifest 命令" >&2
|
||||
exit 1
|
||||
fi
|
||||
|
||||
# 1. 登录 SWR(凭据来自环境变量,不写入仓库)
|
||||
echo ">>> [1/4] 登录 SWR: ${SWR_REGISTRY}"
|
||||
echo ">>> [1/5] 登录 SWR: ${SWR_REGISTRY}"
|
||||
echo "${SWR_PASSWORD}" | docker login "${SWR_REGISTRY}" -u "${SWR_USERNAME}" --password-stdin
|
||||
|
||||
# 2. 确保支持多架构的 builder 存在
|
||||
echo ">>> [2/4] 准备多架构 builder: ${BUILDER_NAME}"
|
||||
echo ">>> [2/5] 准备多架构 builder: ${BUILDER_NAME}"
|
||||
if ! docker buildx inspect "${BUILDER_NAME}" >/dev/null 2>&1; then
|
||||
docker buildx create --name "${BUILDER_NAME}"
|
||||
fi
|
||||
|
||||
# 3. 分别构建并推送各架构镜像(禁用 provenance,产物为单一 manifest)
|
||||
for ARCH in ${ARCHS}; do
|
||||
echo ">>> [3/4] 构建并推送 linux/${ARCH}: ${FULL_IMAGE}-${ARCH}"
|
||||
echo ">>> [3/5] 构建并推送 linux/${ARCH}: ${VERSION_IMAGE}-${ARCH} 与 ${LATEST_IMAGE}-${ARCH}"
|
||||
docker buildx build \
|
||||
--builder "${BUILDER_NAME}" \
|
||||
--platform "linux/${ARCH}" \
|
||||
--provenance=false \
|
||||
--push \
|
||||
-t "${FULL_IMAGE}-${ARCH}" \
|
||||
-t "${VERSION_IMAGE}-${ARCH}" \
|
||||
-t "${LATEST_IMAGE}-${ARCH}" \
|
||||
.
|
||||
done
|
||||
|
||||
# 4. 合并为多架构 manifest list 并推送(标准 Docker manifest list)
|
||||
echo ">>> [4/4] 合并并推送多架构 manifest: ${FULL_IMAGE}"
|
||||
docker manifest create "${FULL_IMAGE}" \
|
||||
--amend "${FULL_IMAGE}-amd64" \
|
||||
--amend "${FULL_IMAGE}-arm64"
|
||||
docker manifest push "${FULL_IMAGE}"
|
||||
echo ">>> 推送完成: ${FULL_IMAGE} (linux/amd64 + linux/arm64)"
|
||||
# 4. 将主架构(amd64)单 manifest 推送为版本 tag 与 latest(SWR 兼容)
|
||||
echo ">>> [4/5] 以 ${PRIMARY_ARCH} 单 manifest 推送版本 tag 与 latest(SWR 兼容)"
|
||||
docker pull "${VERSION_IMAGE}-${PRIMARY_ARCH}"
|
||||
docker tag "${VERSION_IMAGE}-${PRIMARY_ARCH}" "${VERSION_IMAGE}"
|
||||
docker push "${VERSION_IMAGE}"
|
||||
docker tag "${VERSION_IMAGE}-${PRIMARY_ARCH}" "${LATEST_IMAGE}"
|
||||
docker push "${LATEST_IMAGE}"
|
||||
|
||||
# 5. 完成
|
||||
echo ">>> [5/5] 推送完成: ${VERSION_IMAGE}(${PRIMARY_ARCH})"
|
||||
echo ">>> 同步更新: ${LATEST_IMAGE}(${PRIMARY_ARCH})"
|
||||
echo ">>> 分架构可用: ${VERSION_IMAGE}-{amd64,arm64} 与 ${LATEST_IMAGE}-{amd64,arm64}"
|
||||
|
||||
@@ -0,0 +1,108 @@
|
||||
#!/usr/bin/env bash
|
||||
# =========================================================
|
||||
# Arcticnewone 一条命令部署 / 升级脚本
|
||||
#
|
||||
# 用法:
|
||||
# ./deploy.sh # 版本取最新 git tag(无 tag 时取短 commit)
|
||||
# ./deploy.sh 0.0.1-dev # 显式指定版本(须与镜像 tag 一致)
|
||||
# SKIP_BUILD=1 ./deploy.sh ... # 跳过构建推送,仅更新集群(镜像须已存在)
|
||||
#
|
||||
# 流程: 构建并推送镜像(版本化) -> 注入 Secret/ConfigMap -> kubectl apply
|
||||
# -> 等待滚动更新 -> 健康检查。全程一条命令完成部署与升级。
|
||||
#
|
||||
# 必填环境变量(与 build-and-push.sh 一致):
|
||||
# SWR_REGISTRY / SWR_NAMESPACE / SWR_USERNAME / SWR_PASSWORD
|
||||
# 可选(不设则取默认/自动生成):
|
||||
# SESSION_SECRET 会话密钥(缺省复用已有或自动生成)
|
||||
# SMTP_HOST/PORT/USER/PASS/FROM 邮件
|
||||
# CONTACT_TO 联系表单收件邮箱
|
||||
# ADMIN_EMAILS 管理员邮箱(逗号分隔)
|
||||
# SITE_URL 站点公开地址(默认 https://personal.virtheart.com)
|
||||
# =========================================================
|
||||
set -euo pipefail
|
||||
|
||||
NAMESPACE="arcticnewone"
|
||||
REGISTRY="${SWR_REGISTRY:?请先设置环境变量 SWR_REGISTRY}"
|
||||
REPO_NAMESPACE="${SWR_NAMESPACE:?请先设置环境变量 SWR_NAMESPACE}"
|
||||
IMAGE_NAME="arcticnewone"
|
||||
|
||||
# ---------- 版本解析 ----------
|
||||
VERSION="${1:-}"
|
||||
if [ -z "${VERSION}" ]; then
|
||||
VERSION="$(git describe --tags --abbrev=0 2>/dev/null || true)"
|
||||
fi
|
||||
if [ -z "${VERSION}" ]; then
|
||||
VERSION="$(git rev-parse --short HEAD)"
|
||||
fi
|
||||
VERSION="${VERSION//[^A-Za-z0-9_.-]/-}"
|
||||
IMAGE="${REGISTRY}/${REPO_NAMESPACE}/${IMAGE_NAME}:${VERSION}"
|
||||
|
||||
echo "=========================================================="
|
||||
echo " 目标版本: ${VERSION}"
|
||||
echo " 镜像: ${IMAGE}"
|
||||
echo " 命名空间: ${NAMESPACE}"
|
||||
echo "=========================================================="
|
||||
|
||||
# ---------- 1. 构建并推送镜像(可跳过) ----------
|
||||
if [ "${SKIP_BUILD:-0}" != "1" ]; then
|
||||
echo ">>> [1/6] 构建并推送镜像(${VERSION} + latest)"
|
||||
./build-and-push.sh "${VERSION}"
|
||||
else
|
||||
echo ">>> [1/6] SKIP_BUILD=1,跳过构建推送(要求 ${IMAGE} 已存在)"
|
||||
fi
|
||||
|
||||
# ---------- 2. 镜像拉取 Secret(SWR 凭据,不写入仓库) ----------
|
||||
echo ">>> [2/6] 确保镜像拉取 Secret: huawei-swr-secret"
|
||||
kubectl create secret docker-registry huawei-swr-secret -n "${NAMESPACE}" \
|
||||
--docker-server="${REGISTRY}" \
|
||||
--docker-username="${SWR_USERNAME:?请先设置环境变量 SWR_USERNAME}" \
|
||||
--docker-password="${SWR_PASSWORD:?请先设置环境变量 SWR_PASSWORD}" \
|
||||
--dry-run=client -o yaml | kubectl apply -f - >/dev/null
|
||||
|
||||
# ---------- 3. 应用 Secret / ConfigMap ----------
|
||||
echo ">>> [3/6] 注入 Secret: app-secrets / ConfigMap: app-config"
|
||||
|
||||
SESSION_SECRET="${SESSION_SECRET:-}"
|
||||
if [ -z "${SESSION_SECRET}" ]; then
|
||||
SESSION_SECRET="$(kubectl get secret app-secrets -n "${NAMESPACE}" -o jsonpath='{.data.NUXT_SESSION_SECRET}' 2>/dev/null | base64 -d 2>/dev/null || true)"
|
||||
fi
|
||||
if [ -z "${SESSION_SECRET}" ]; then
|
||||
SESSION_SECRET="$(node -e "console.log(require('crypto').randomBytes(48).toString('hex'))")"
|
||||
echo " (未设置 SESSION_SECRET,已自动生成;如需固定请设置环境变量)"
|
||||
fi
|
||||
|
||||
# 注意:Nuxt runtimeConfig 的环境变量一律使用 NUXT_ 前缀
|
||||
kubectl create secret generic app-secrets -n "${NAMESPACE}" \
|
||||
--from-literal="NUXT_SESSION_SECRET=${SESSION_SECRET}" \
|
||||
--from-literal="NUXT_SMTP_HOST=${SMTP_HOST:-}" \
|
||||
--from-literal="NUXT_SMTP_PORT=${SMTP_PORT:-587}" \
|
||||
--from-literal="NUXT_SMTP_USER=${SMTP_USER:-}" \
|
||||
--from-literal="NUXT_SMTP_PASS=${SMTP_PASS:-}" \
|
||||
--from-literal="NUXT_SMTP_FROM=${SMTP_FROM:-}" \
|
||||
--from-literal="NUXT_CONTACT_TO=${CONTACT_TO:-}" \
|
||||
--from-literal="NUXT_ADMIN_EMAILS=${ADMIN_EMAILS:-}" \
|
||||
--dry-run=client -o yaml | kubectl apply -f - >/dev/null
|
||||
|
||||
kubectl create configmap app-config -n "${NAMESPACE}" \
|
||||
--from-literal="NUXT_PUBLIC_SITE_URL=${SITE_URL:-https://personal.virtheart.com}" \
|
||||
--from-literal="NUXT_DB_PATH=/data/arcticnewone.db" \
|
||||
--dry-run=client -o yaml | kubectl apply -f - >/dev/null
|
||||
|
||||
# ---------- 4. 应用全部资源 ----------
|
||||
echo ">>> [4/6] 应用 K8s 资源(namespace/pvc/deployment/service/ingress)"
|
||||
kubectl apply -f deploy/namespace.yaml >/dev/null
|
||||
sed "s|__IMAGE__|${IMAGE}|g" deploy/deployment.yaml | kubectl apply -f -
|
||||
kubectl apply -f deploy/pvc.yaml
|
||||
kubectl apply -f deploy/service.yaml
|
||||
kubectl apply -f deploy/ingress.yaml
|
||||
|
||||
# ---------- 5. 等待滚动更新 ----------
|
||||
echo ">>> [5/6] 等待滚动更新完成..."
|
||||
kubectl rollout status deployment/arcticnewone -n "${NAMESPACE}" --timeout=300s
|
||||
|
||||
# ---------- 6. 健康检查 ----------
|
||||
echo ">>> [6/6] 部署完成,当前状态:"
|
||||
kubectl get pods -n "${NAMESPACE}" -l app=arcticnewone
|
||||
echo
|
||||
echo "部署成功: ${IMAGE}"
|
||||
echo "访问: ${SITE_URL:-https://personal.virtheart.com}"
|
||||
+48
-41
@@ -7,15 +7,14 @@
|
||||
| 文件 | 说明 |
|
||||
| --- | --- |
|
||||
| `namespace.yaml` | Namespace:项目专属命名空间 `arcticnewone` |
|
||||
| `deployment.yaml` | Deployment:SWR 镜像、副本数 1、私有镜像拉取 secrets |
|
||||
| `deployment.yaml` | Deployment:镜像占位 `__IMAGE__`(由 deploy.sh 渲染为版本化地址)、副本数 1、PVC 持久化、Secret/ConfigMap 注入 |
|
||||
| `pvc.yaml` | PersistentVolumeClaim:SQLite 数据持久化(挂载 `/data`,Pod 升级不丢数据) |
|
||||
| `service.yaml` | Service:ClusterIP,80 端口转发到容器 3000 端口 |
|
||||
| `ingress.yaml` | Ingress:域名 `personal.virtheart.com`,Traefik + cert-manager 自动签发证书 |
|
||||
|
||||
`namespace.yaml` 负责创建 `arcticnewone` 命名空间;deployment/service/ingress 三个 YAML 的 `metadata` 均已指定 `namespace: arcticnewone`。
|
||||
> 不建议手工 apply 上述清单;请使用项目根目录的 `./deploy.sh` 一条命令完成构建/推送/更新/升级(详见下方「一条命令部署」)。
|
||||
|
||||
## 镜像构建与推送
|
||||
|
||||
镜像由项目根目录的 `build-and-push.sh` 构建并推送到华为云 SWR(多架构 `linux/amd64,linux/arm64`,tag 统一为 `latest`):
|
||||
## 一条命令部署 / 升级(推荐)
|
||||
|
||||
```bash
|
||||
# 1. 设置环境变量(凭据绝不写入仓库)
|
||||
@@ -23,59 +22,67 @@ export SWR_REGISTRY="swr.cn-north-4.myhuaweicloud.com"
|
||||
export SWR_NAMESPACE="virtheart"
|
||||
export SWR_USERNAME="<用户名>"
|
||||
export SWR_PASSWORD="<密码>"
|
||||
# 可选:SESSION_SECRET / SMTP_* / CONTACT_TO / ADMIN_EMAILS / SITE_URL
|
||||
|
||||
# 2. 执行构建与推送
|
||||
./build-and-push.sh
|
||||
# 2. 打版本标签(版本号即镜像 tag)
|
||||
git tag 0.0.1-dev
|
||||
|
||||
# 3. 一条命令:构建镜像 -> 推送 SWR -> 注入 Secret/ConfigMap -> kubectl apply -> 滚动升级
|
||||
./deploy.sh 0.0.1-dev
|
||||
# 或
|
||||
./deploy.sh # 自动取最新 git tag
|
||||
```
|
||||
|
||||
推送完成后镜像地址:`swr.cn-north-4.myhuaweicloud.com/virtheart/arcticnewone:latest`。
|
||||
`deploy.sh` 依次完成:
|
||||
1. 调用 `build-and-push.sh` 构建并推送版本化镜像(`:0.0.1-dev` + `:latest`)
|
||||
2. 创建/更新镜像拉取 Secret(`huawei-swr-secret`)
|
||||
3. 创建/更新 `app-secrets`(SESSION_SECRET/SMTP/CONTACT_TO/ADMIN_EMAILS)与 `app-config`(站点地址/DB 路径)
|
||||
4. `kubectl apply`:namespace / pvc / deployment(镜像渲染为版本化地址)/ service / ingress
|
||||
5. `kubectl rollout status` 等待滚动更新
|
||||
6. 输出 Pod 状态与访问地址
|
||||
|
||||
说明:SWR 不支持 buildx 多架构一步推送产生的 OCI manifest 格式。脚本改为分架构推送(`latest-amd64` / `latest-arm64`),再用 `docker manifest create` + `docker manifest push` 合并为标准的 Docker manifest list(`latest`),并禁用 provenance(`--provenance=false`),保证 SWR 可正常解析。
|
||||
## 仅构建镜像
|
||||
|
||||
```bash
|
||||
./build-and-push.sh # 版本取最新 git tag
|
||||
./build-and-push.sh 0.0.1-dev # 显式指定版本
|
||||
```
|
||||
|
||||
分架构构建(`linux/amd64,linux/arm64`)并推送 `-amd64` / `-arm64` 标签;
|
||||
版本 tag 与 `latest` 以 **amd64 单架构 manifest** 输出(华为云 SWR 无法解析 Docker manifest list,多架构合并会报 `Invalid image`;生产集群为 amd64),并禁用 provenance(`--provenance=false`)。
|
||||
|
||||
## 部署前置条件
|
||||
|
||||
1. 镜像已构建并推送到华为云 SWR(通过项目根目录 `./build-and-push.sh` 执行,见上方「镜像构建与推送」)
|
||||
2. 集群已安装 Traefik Ingress 与 cert-manager(ClusterIssuer 名称为 `lets-encrypt`)
|
||||
3. 域名 `personal.virtheart.com` 的 DNS 已解析到集群入口
|
||||
4. 创建私有镜像拉取 Secret(凭据从环境变量读取,绝不写入仓库;命名空间由 `namespace.yaml` 创建):
|
||||
1. 集群已安装 Traefik Ingress 与 cert-manager(ClusterIssuer 名称为 `lets-encrypt`)
|
||||
2. 域名 `personal.virtheart.com` 的 DNS 已解析到集群入口
|
||||
3. 具备 `arcticnewone` 命名空间的 kubectl 权限(`./deploy.sh` 会自动创建命名空间与全部资源)
|
||||
|
||||
## 部署后验证
|
||||
|
||||
```bash
|
||||
kubectl create secret docker-registry huawei-swr-secret -n arcticnewone \
|
||||
--docker-server="$SWR_REGISTRY" \
|
||||
--docker-username="$SWR_USERNAME" \
|
||||
--docker-password="$SWR_PASSWORD" \
|
||||
--dry-run=client -o yaml | kubectl apply -f -
|
||||
```
|
||||
|
||||
## 部署步骤
|
||||
|
||||
```bash
|
||||
kubectl apply -f deploy/namespace.yaml
|
||||
kubectl apply -f deploy/deployment.yaml
|
||||
kubectl apply -f deploy/service.yaml
|
||||
kubectl apply -f deploy/ingress.yaml
|
||||
```
|
||||
|
||||
`namespace.yaml` 需最先应用;其余三个 YAML 自带 `namespace: arcticnewone`,`kubectl apply` 时无需额外指定。
|
||||
|
||||
部署后验证:
|
||||
|
||||
```bash
|
||||
kubectl get deploy,svc,ingress -n arcticnewone
|
||||
kubectl get deploy,svc,pvc,ingress -n arcticnewone
|
||||
kubectl rollout status deployment/arcticnewone -n arcticnewone
|
||||
curl -I https://personal.virtheart.com
|
||||
curl https://personal.virtheart.com/sitemap.xml
|
||||
curl https://personal.virtheart.com/robots.txt
|
||||
```
|
||||
|
||||
## 回滚方案
|
||||
|
||||
镜像 tag 固定为 `latest`,回滚前先确认 SWR 上 `latest` 对应可回滚的版本(或先推送目标版本镜像),再执行:
|
||||
镜像使用版本化 tag,回滚即切回上一版本镜像:
|
||||
|
||||
```bash
|
||||
# 回滚到上一版本镜像
|
||||
# 方式一:回滚到 Deployment 上一版本
|
||||
kubectl rollout undo deployment/arcticnewone -n arcticnewone
|
||||
|
||||
# 或整体移除本次部署的资源
|
||||
kubectl delete -f deploy/ingress.yaml -n arcticnewone
|
||||
kubectl delete -f deploy/service.yaml -n arcticnewone
|
||||
kubectl delete -f deploy/deployment.yaml -n arcticnewone
|
||||
# 方式二:显式部署旧版本镜像(旧镜像需已在 SWR)
|
||||
IMAGE="swr.cn-north-4.myhuaweicloud.com/virtheart/arcticnewone:<旧版本>"
|
||||
sed "s|__IMAGE__|${IMAGE}|g" deploy/deployment.yaml | kubectl apply -f - && \
|
||||
kubectl rollout status deployment/arcticnewone -n arcticnewone
|
||||
```
|
||||
|
||||
## 数据持久化
|
||||
|
||||
- SQLite 数据库位于容器 `/data/arcticnewone.db`,由 PVC `arcticnewone-data`(RWO,1Gi)持久化
|
||||
- Pod 升级、重启、回滚均不丢失用户/留言/订阅/收藏/评论数据
|
||||
- 备份:对 PVC 挂载目录执行 `sqlite3 arcticnewone.db ".backup 'backup.db'"` 或整卷快照
|
||||
|
||||
+22
-11
@@ -1,17 +1,13 @@
|
||||
# =========================================================
|
||||
# Arcticnewone 生产部署 - Deployment
|
||||
#
|
||||
# 镜像: 华为云 SWR swr.cn-north-4.myhuaweicloud.com/virtheart/arcticnewone:latest
|
||||
# 镜像: 由 deploy.sh 渲染,占位 __IMAGE__ 替换为
|
||||
# swr.cn-north-4.myhuaweicloud.com/virtheart/arcticnewone:<版本号>
|
||||
# 副本数: 1(团队规范)
|
||||
#
|
||||
# 私有镜像拉取说明:
|
||||
# 集群中需预先创建 docker-registry 类型的 Secret(凭据从环境变量读取,不写入仓库):
|
||||
# kubectl create secret docker-registry huawei-swr-secret \
|
||||
# --docker-server="$SWR_REGISTRY" \
|
||||
# --docker-username="$SWR_USERNAME" \
|
||||
# --docker-password="$SWR_PASSWORD" \
|
||||
# --dry-run=client -o yaml | kubectl apply -f -
|
||||
# 详见 deploy/README.md
|
||||
# 敏感配置(SESSION_SECRET / SMTP_* / CONTACT_TO / ADMIN_EMAILS)
|
||||
# 由 deploy.sh 以 Secret `app-secrets` 注入;公开配置(站点地址/DB 路径)
|
||||
# 以 ConfigMap `app-config` 注入。数据库持久化到 PVC `arcticnewone-data`(/data)。
|
||||
# =========================================================
|
||||
apiVersion: apps/v1
|
||||
kind: Deployment
|
||||
@@ -21,6 +17,9 @@ metadata:
|
||||
labels:
|
||||
app: arcticnewone
|
||||
spec:
|
||||
# RWO PVC 单副本场景:Recreate 策略避免滚动更新时新旧 Pod 争用卷导致死锁
|
||||
strategy:
|
||||
type: Recreate
|
||||
replicas: 1
|
||||
selector:
|
||||
matchLabels:
|
||||
@@ -34,8 +33,8 @@ spec:
|
||||
- name: huawei-swr-secret
|
||||
containers:
|
||||
- name: arcticnewone
|
||||
image: swr.cn-north-4.myhuaweicloud.com/virtheart/arcticnewone:latest
|
||||
imagePullPolicy: Always
|
||||
image: __IMAGE__
|
||||
imagePullPolicy: IfNotPresent
|
||||
ports:
|
||||
- name: http
|
||||
containerPort: 3000
|
||||
@@ -46,6 +45,14 @@ spec:
|
||||
value: "0.0.0.0"
|
||||
- name: PORT
|
||||
value: "3000"
|
||||
envFrom:
|
||||
- configMapRef:
|
||||
name: app-config
|
||||
- secretRef:
|
||||
name: app-secrets
|
||||
volumeMounts:
|
||||
- name: data
|
||||
mountPath: /data
|
||||
resources:
|
||||
requests:
|
||||
cpu: 100m
|
||||
@@ -69,3 +76,7 @@ spec:
|
||||
periodSeconds: 20
|
||||
timeoutSeconds: 3
|
||||
failureThreshold: 3
|
||||
volumes:
|
||||
- name: data
|
||||
persistentVolumeClaim:
|
||||
claimName: arcticnewone-data
|
||||
|
||||
@@ -0,0 +1,19 @@
|
||||
# =========================================================
|
||||
# Arcticnewone 生产部署 - 持久化卷
|
||||
#
|
||||
# SQLite 数据(/data/arcticnewone.db)持久化,Pod 重启/升级不丢数据。
|
||||
# microk8s 默认提供 hostpath 存储类;生产可按需替换为云盘存储类。
|
||||
# =========================================================
|
||||
apiVersion: v1
|
||||
kind: PersistentVolumeClaim
|
||||
metadata:
|
||||
name: arcticnewone-data
|
||||
namespace: arcticnewone
|
||||
labels:
|
||||
app: arcticnewone
|
||||
spec:
|
||||
accessModes:
|
||||
- ReadWriteOnce
|
||||
resources:
|
||||
requests:
|
||||
storage: 1Gi
|
||||
+135
-36
@@ -32,13 +32,7 @@
|
||||
"work": {
|
||||
"label": "Portfolio 26©",
|
||||
"title": "Work",
|
||||
"viewAll": "View all work",
|
||||
"items": {
|
||||
"forma": "Forma Digital",
|
||||
"oneStep": "One Step",
|
||||
"neroVision": "Nero Vision",
|
||||
"boldMoves": "Bold Moves"
|
||||
}
|
||||
"viewAll": "View all work"
|
||||
},
|
||||
"services": {
|
||||
"title": "Our Services",
|
||||
@@ -239,34 +233,7 @@
|
||||
"updates": {
|
||||
"title": "Latest Updates",
|
||||
"subtitle": "Explore our latest projects, blog posts, and industry insights",
|
||||
"viewAll": "View All Updates",
|
||||
"categories": {
|
||||
"project": "Project",
|
||||
"blog": "Blog",
|
||||
"news": "News"
|
||||
},
|
||||
"items": {
|
||||
"project1": {
|
||||
"title": "Brand Redesign: Modern E-commerce Platform",
|
||||
"description": "Created a new brand identity and user experience for a leading e-commerce platform, boosting conversion by 45%."
|
||||
},
|
||||
"blog1": {
|
||||
"title": "Web Design Trends in 2026"
|
||||
},
|
||||
"news1": {
|
||||
"title": "Awarded Best Design Studio"
|
||||
},
|
||||
"project2": {
|
||||
"title": "AI-Powered Recommendation System",
|
||||
"description": "Developed an innovative AI recommendation engine for personalized experiences."
|
||||
},
|
||||
"blog2": {
|
||||
"title": "How to Boost Website Performance"
|
||||
},
|
||||
"news2": {
|
||||
"title": "Team Expands to 50 Members"
|
||||
}
|
||||
}
|
||||
"viewAll": "View All Updates"
|
||||
},
|
||||
"cta": {
|
||||
"titleLine1": "Ready to Start",
|
||||
@@ -310,6 +277,32 @@
|
||||
},
|
||||
"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",
|
||||
@@ -425,6 +418,33 @@
|
||||
"projects": "Projects",
|
||||
"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",
|
||||
@@ -523,6 +543,85 @@
|
||||
"passwordMismatch": "Passwords do not match",
|
||||
"invalidPhone": "Invalid phone number format",
|
||||
"alreadyHaveAccount": "Already have an account?",
|
||||
"backToLogin": "Back to Login"
|
||||
"backToLogin": "Back to Login",
|
||||
"usernameTaken": "Username is already taken",
|
||||
"emailTaken": "This email is already registered",
|
||||
"invalidCredentials": "Incorrect account or password",
|
||||
"passwordTooShort": "Password must be at least 8 characters",
|
||||
"invalidUsername": "Username must be 2-20 characters (letters, digits, underscores, Chinese)",
|
||||
"invalidEmail": "Invalid email address",
|
||||
"loginRequired": "Please sign in first",
|
||||
"serverError": "Server error. Please try again later."
|
||||
},
|
||||
"account": {
|
||||
"title": "My Account",
|
||||
"profile": "Profile",
|
||||
"favorites": "Favorites",
|
||||
"comments": "My Comments",
|
||||
"adminTitle": "Admin",
|
||||
"username": "Username",
|
||||
"email": "Email",
|
||||
"phone": "Phone",
|
||||
"joinedAt": "Joined",
|
||||
"role": "Role",
|
||||
"roleAdmin": "Admin",
|
||||
"roleUser": "User",
|
||||
"save": "Save Changes",
|
||||
"saving": "Saving...",
|
||||
"saved": "Saved",
|
||||
"saveFailed": "Failed to save. Please try again.",
|
||||
"emptyFavorites": "No favorites yet. Go to the Work page to explore.",
|
||||
"emptyComments": "No comments posted yet",
|
||||
"admin": {
|
||||
"contacts": "Contact Messages",
|
||||
"subscribers": "Newsletter Subscribers",
|
||||
"emptyContacts": "No contact messages",
|
||||
"emptySubscribers": "No subscribers yet",
|
||||
"name": "Name",
|
||||
"email": "Email",
|
||||
"subject": "Subject",
|
||||
"message": "Message",
|
||||
"date": "Date",
|
||||
"delivered": "Delivered to inbox",
|
||||
"notDelivered": "Not delivered (SMTP not configured)"
|
||||
}
|
||||
},
|
||||
"comments": {
|
||||
"title": "Comments",
|
||||
"placeholder": "Share your thoughts...",
|
||||
"submit": "Post Comment",
|
||||
"submitting": "Posting...",
|
||||
"empty": "No comments yet. Be the first to comment.",
|
||||
"loginToComment": "Sign in to join the discussion",
|
||||
"commentError": "Failed to post comment. Please try again."
|
||||
},
|
||||
"favorites": {
|
||||
"add": "Favorite",
|
||||
"remove": "Unfavorite",
|
||||
"added": "Favorited",
|
||||
"loginToFavorite": "Sign in to favorite this project"
|
||||
},
|
||||
"search": {
|
||||
"placeholder": "Search...",
|
||||
"empty": "No matching results"
|
||||
},
|
||||
"pagination": {
|
||||
"loadMore": "Load More",
|
||||
"noMore": "All loaded"
|
||||
},
|
||||
"share": {
|
||||
"article": "Share this article",
|
||||
"copy": "Copy link",
|
||||
"copied": "Link copied",
|
||||
"copyFailed": "Copy failed. Please copy the URL from the address bar."
|
||||
},
|
||||
"lang": {
|
||||
"toEnglish": "English",
|
||||
"toChinese": "中文"
|
||||
},
|
||||
"newsletter": {
|
||||
"subscribed": "Subscribed! Thank you for joining.",
|
||||
"alreadySubscribed": "You are already subscribed",
|
||||
"error": "Subscription failed. Please try again."
|
||||
}
|
||||
}
|
||||
|
||||
+135
-36
@@ -32,13 +32,7 @@
|
||||
"work": {
|
||||
"label": "作品集 26©",
|
||||
"title": "Work",
|
||||
"viewAll": "查看全部作品",
|
||||
"items": {
|
||||
"forma": "Forma Digital",
|
||||
"oneStep": "One Step",
|
||||
"neroVision": "Nero Vision",
|
||||
"boldMoves": "Bold Moves"
|
||||
}
|
||||
"viewAll": "查看全部作品"
|
||||
},
|
||||
"services": {
|
||||
"title": "我们的服务",
|
||||
@@ -239,34 +233,7 @@
|
||||
"updates": {
|
||||
"title": "最新动态",
|
||||
"subtitle": "探索我们最新的项目、博客文章和行业洞察",
|
||||
"viewAll": "查看全部动态",
|
||||
"categories": {
|
||||
"project": "项目",
|
||||
"blog": "博客",
|
||||
"news": "新闻"
|
||||
},
|
||||
"items": {
|
||||
"project1": {
|
||||
"title": "品牌重塑:现代电商平台设计",
|
||||
"description": "为领先的电商平台打造全新品牌形象和用户体验,提升转化率 45%。"
|
||||
},
|
||||
"blog1": {
|
||||
"title": "2026 年 Web 设计趋势"
|
||||
},
|
||||
"news1": {
|
||||
"title": "公司荣获最佳设计奖"
|
||||
},
|
||||
"project2": {
|
||||
"title": "AI 驱动的智能推荐系统",
|
||||
"description": "开发创新的 AI 推荐引擎,个性化用户体验。"
|
||||
},
|
||||
"blog2": {
|
||||
"title": "如何提升网站性能"
|
||||
},
|
||||
"news2": {
|
||||
"title": "团队规模扩大至 50 人"
|
||||
}
|
||||
}
|
||||
"viewAll": "查看全部动态"
|
||||
},
|
||||
"cta": {
|
||||
"titleLine1": "准备好开始",
|
||||
@@ -310,6 +277,32 @@
|
||||
},
|
||||
"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": "项目挑战",
|
||||
@@ -425,6 +418,33 @@
|
||||
"projects": "项目动态",
|
||||
"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": "相关文章",
|
||||
@@ -523,6 +543,85 @@
|
||||
"passwordMismatch": "两次输入的密码不一致",
|
||||
"invalidPhone": "手机号格式不正确",
|
||||
"alreadyHaveAccount": "已有账号?",
|
||||
"backToLogin": "返回登录"
|
||||
"backToLogin": "返回登录",
|
||||
"usernameTaken": "用户名已被使用",
|
||||
"emailTaken": "该邮箱已被注册",
|
||||
"invalidCredentials": "账号或密码错误",
|
||||
"passwordTooShort": "密码至少需要 8 位",
|
||||
"invalidUsername": "用户名需为 2-20 位字符(字母、数字、下划线、中文)",
|
||||
"invalidEmail": "邮箱格式不正确",
|
||||
"loginRequired": "请先登录后操作",
|
||||
"serverError": "服务器开小差了,请稍后再试"
|
||||
},
|
||||
"account": {
|
||||
"title": "个人中心",
|
||||
"profile": "个人资料",
|
||||
"favorites": "我的收藏",
|
||||
"comments": "我的评论",
|
||||
"adminTitle": "管理面板",
|
||||
"username": "用户名",
|
||||
"email": "邮箱",
|
||||
"phone": "手机号",
|
||||
"joinedAt": "注册时间",
|
||||
"role": "角色",
|
||||
"roleAdmin": "管理员",
|
||||
"roleUser": "普通用户",
|
||||
"save": "保存修改",
|
||||
"saving": "保存中...",
|
||||
"saved": "已保存",
|
||||
"saveFailed": "保存失败,请重试",
|
||||
"emptyFavorites": "还没有收藏任何作品,去「作品」页看看吧",
|
||||
"emptyComments": "还没有发表过评论",
|
||||
"admin": {
|
||||
"contacts": "联系消息",
|
||||
"subscribers": "邮箱订阅",
|
||||
"emptyContacts": "暂无联系消息",
|
||||
"emptySubscribers": "暂无订阅用户",
|
||||
"name": "姓名",
|
||||
"email": "邮箱",
|
||||
"subject": "主题",
|
||||
"message": "留言内容",
|
||||
"date": "时间",
|
||||
"delivered": "已送达邮箱",
|
||||
"notDelivered": "未送达(SMTP 未配置)"
|
||||
}
|
||||
},
|
||||
"comments": {
|
||||
"title": "评论",
|
||||
"placeholder": "写下你的想法…",
|
||||
"submit": "发表评论",
|
||||
"submitting": "发表中…",
|
||||
"empty": "还没有评论,来说两句吧",
|
||||
"loginToComment": "登录后参与评论",
|
||||
"commentError": "评论发表失败,请重试"
|
||||
},
|
||||
"favorites": {
|
||||
"add": "收藏",
|
||||
"remove": "取消收藏",
|
||||
"added": "已收藏",
|
||||
"loginToFavorite": "登录后收藏作品"
|
||||
},
|
||||
"search": {
|
||||
"placeholder": "搜索…",
|
||||
"empty": "未找到相关内容"
|
||||
},
|
||||
"pagination": {
|
||||
"loadMore": "加载更多",
|
||||
"noMore": "已加载全部"
|
||||
},
|
||||
"share": {
|
||||
"article": "分享文章",
|
||||
"copy": "复制链接",
|
||||
"copied": "链接已复制",
|
||||
"copyFailed": "复制失败,请手动复制地址栏链接"
|
||||
},
|
||||
"lang": {
|
||||
"toEnglish": "English",
|
||||
"toChinese": "中文"
|
||||
},
|
||||
"newsletter": {
|
||||
"subscribed": "订阅成功,感谢关注!",
|
||||
"alreadySubscribed": "您已在订阅列表中",
|
||||
"error": "订阅失败,请稍后再试"
|
||||
}
|
||||
}
|
||||
|
||||
@@ -18,6 +18,25 @@ export default defineNuxtConfig({
|
||||
compatibilityDate: '2025-07-15',
|
||||
devtools: { enabled: true },
|
||||
css: ['~/assets/css/tailwind.css'],
|
||||
// 组件注册去掉目录前缀(common/home/layouts 子目录不生成 Common*/Home* 前缀),
|
||||
// 与全站 `<AppLoader>`/`<CommentSection>` 等无前缀引用保持一致
|
||||
components: [{ path: '~/components', pathPrefix: false }],
|
||||
runtimeConfig: {
|
||||
// 服务端私有配置(环境变量自动映射:SESSION_SECRET / DB_PATH / SMTP_* / CONTACT_TO / ADMIN_EMAILS)
|
||||
sessionSecret: '',
|
||||
dbPath: process.env.DB_PATH || (process.env.NODE_ENV === 'production' ? '/data/arcticnewone.db' : '.data/arcticnewone.db'),
|
||||
smtpHost: '',
|
||||
smtpPort: 587,
|
||||
smtpUser: '',
|
||||
smtpPass: '',
|
||||
smtpFrom: '',
|
||||
contactTo: '',
|
||||
adminEmails: '',
|
||||
public: {
|
||||
// 客户端可见(环境变量:NUXT_PUBLIC_SITE_URL),用于 sitemap/robots/og 等绝对链接
|
||||
siteUrl: '',
|
||||
},
|
||||
},
|
||||
modules: [
|
||||
'@nuxtjs/i18n',
|
||||
'@nuxt/hints',
|
||||
|
||||
+5
-1
@@ -15,8 +15,10 @@
|
||||
"@nuxt/icon": "2.2.1",
|
||||
"@nuxtjs/i18n": "10.3.0",
|
||||
"@pinia/nuxt": "0.11.3",
|
||||
"better-sqlite3": "^13.0.2",
|
||||
"gsap": "^3.15.0",
|
||||
"lenis": "^1.3.23",
|
||||
"nodemailer": "^9.0.4",
|
||||
"nuxt": "^4.4.2",
|
||||
"pinia": "^3.0.4",
|
||||
"vue": "^3.5.32",
|
||||
@@ -24,6 +26,8 @@
|
||||
},
|
||||
"devDependencies": {
|
||||
"@iconify-json/ph": "1.2.2",
|
||||
"@nuxtjs/tailwindcss": "6.14.0"
|
||||
"@nuxtjs/tailwindcss": "6.14.0",
|
||||
"@types/better-sqlite3": "^7.6.13",
|
||||
"@types/nodemailer": "^6.4.17"
|
||||
}
|
||||
}
|
||||
|
||||
Generated
+323
-212
File diff suppressed because it is too large
Load Diff
@@ -1,3 +1,4 @@
|
||||
allowBuilds:
|
||||
"@parcel/watcher": true
|
||||
better-sqlite3: true
|
||||
esbuild: true
|
||||
|
||||
Binary file not shown.
|
After Width: | Height: | Size: 81 KiB |
@@ -1,2 +0,0 @@
|
||||
User-Agent: *
|
||||
Disallow:
|
||||
@@ -0,0 +1,139 @@
|
||||
/**
|
||||
* 生成站点 Open Graph 分享图 public/og-image.png(1200x630)。
|
||||
*
|
||||
* 手写 PNG 编码器(node:zlib deflateSync),零第三方依赖、确定性可复现:
|
||||
* - 深蓝渐变背景 + 中央白色菱形 logo 母题 + 星点(固定种子伪随机)
|
||||
*
|
||||
* 用法: node scripts/generate-og.mjs
|
||||
*/
|
||||
import { deflateSync } from 'node:zlib'
|
||||
import { writeFileSync } from 'node:fs'
|
||||
|
||||
const W = 1200
|
||||
const H = 630
|
||||
|
||||
// ---------- PNG 编码工具 ----------
|
||||
let crcTable = null
|
||||
function crc32(buf) {
|
||||
if (!crcTable) {
|
||||
crcTable = new Int32Array(256)
|
||||
for (let n = 0; n < 256; n++) {
|
||||
let c = n
|
||||
for (let k = 0; k < 8; k++) c = c & 1 ? 0xedb88320 ^ (c >>> 1) : c >>> 1
|
||||
crcTable[n] = c
|
||||
}
|
||||
}
|
||||
let c = 0xffffffff
|
||||
for (let i = 0; i < buf.length; i++) c = crcTable[(c ^ buf[i]) & 0xff] ^ (c >>> 8)
|
||||
return (c ^ 0xffffffff) >>> 0
|
||||
}
|
||||
|
||||
function chunk(type, data) {
|
||||
const len = Buffer.alloc(4)
|
||||
len.writeUInt32BE(data.length)
|
||||
const typeBuf = Buffer.from(type, 'ascii')
|
||||
const crcBuf = Buffer.alloc(4)
|
||||
crcBuf.writeUInt32BE(crc32(Buffer.concat([typeBuf, data])))
|
||||
return Buffer.concat([len, typeBuf, data, crcBuf])
|
||||
}
|
||||
|
||||
// ---------- 确定性伪随机(mulberry32)----------
|
||||
let seed = 20260806
|
||||
function rand() {
|
||||
seed = (seed + 0x6d2b79f5) | 0
|
||||
let t = seed
|
||||
t = Math.imul(t ^ (t >>> 15), t | 1)
|
||||
t ^= t + Math.imul(t ^ (t >>> 7), t | 61)
|
||||
return ((t ^ (t >>> 14)) >>> 0) / 4294967296
|
||||
}
|
||||
|
||||
// ---------- 像素绘制 ----------
|
||||
const raw = Buffer.alloc(H * (1 + W * 4))
|
||||
|
||||
const lerp = (a, b, t) => Math.round(a + (b - a) * t)
|
||||
const clamp255 = (v) => Math.max(0, Math.min(255, v))
|
||||
|
||||
const cTop = [15, 23, 42] // #0f172a
|
||||
const cBottom = [30, 41, 59] // #1e293b
|
||||
const cAccent = [99, 102, 241] // indigo
|
||||
const cx = W / 2
|
||||
const cy = H / 2
|
||||
const diamondHalf = 132 // 菱形对角线半长(L1 度量)
|
||||
const diamondEdge = 16 // 菱形边缘柔和过渡像素
|
||||
|
||||
// 基础渐变 + 中央径向光晕 + 菱形
|
||||
for (let y = 0; y < H; y++) {
|
||||
const rowStart = y * (1 + W * 4)
|
||||
raw[rowStart] = 0 // filter: none
|
||||
const t = y / (H - 1)
|
||||
let r = lerp(cTop[0], cBottom[0], t)
|
||||
let g = lerp(cTop[1], cBottom[1], t)
|
||||
let b = lerp(cTop[2], cBottom[2], t)
|
||||
|
||||
for (let x = 0; x < W; x++) {
|
||||
const dx = x - cx
|
||||
const dy = y - cy
|
||||
const dist = Math.sqrt(dx * dx + dy * dy)
|
||||
const glow = Math.max(0, 1 - dist / 520)
|
||||
let pr = lerp(r, cAccent[0], glow * 0.45)
|
||||
let pg = lerp(g, cAccent[1], glow * 0.45)
|
||||
let pb = lerp(b, cAccent[2], glow * 0.45)
|
||||
|
||||
const l1 = Math.abs(dx) + Math.abs(dy)
|
||||
if (l1 <= diamondHalf) {
|
||||
const edge = clamp255(Math.max(0, diamondHalf - l1) / diamondEdge)
|
||||
pr = lerp(pr, 255, edge * 0.94)
|
||||
pg = lerp(pg, 255, edge * 0.94)
|
||||
pb = lerp(pb, 255, edge * 0.94)
|
||||
}
|
||||
|
||||
const off = rowStart + 1 + x * 4
|
||||
raw[off] = clamp255(pr)
|
||||
raw[off + 1] = clamp255(pg)
|
||||
raw[off + 2] = clamp255(pb)
|
||||
raw[off + 3] = 255
|
||||
}
|
||||
}
|
||||
|
||||
// 星点(后画,覆盖在基色上)
|
||||
const stars = []
|
||||
for (let i = 0; i < 180; i++) {
|
||||
stars.push({ x: rand() * W, y: rand() * H, r: 0.5 + rand() * 2.2, a: 0.12 + rand() * 0.35 })
|
||||
}
|
||||
for (const s of stars) {
|
||||
const r = s.r + 1
|
||||
const x0 = Math.max(0, Math.floor(s.x - r))
|
||||
const x1 = Math.min(W - 1, Math.ceil(s.x + r))
|
||||
const y0 = Math.max(0, Math.floor(s.y - r))
|
||||
const y1 = Math.min(H - 1, Math.ceil(s.y + r))
|
||||
for (let y = y0; y <= y1; y++) {
|
||||
const rowStart = y * (1 + W * 4)
|
||||
for (let x = x0; x <= x1; x++) {
|
||||
if (Math.hypot(s.x - x, s.y - y) > s.r) continue
|
||||
const off = rowStart + 1 + x * 4
|
||||
raw[off] = clamp255(lerp(raw[off], 255, s.a))
|
||||
raw[off + 1] = clamp255(lerp(raw[off + 1], 255, s.a))
|
||||
raw[off + 2] = clamp255(lerp(raw[off + 2], 255, s.a))
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// ---------- 组装 PNG ----------
|
||||
const ihdr = Buffer.alloc(13)
|
||||
ihdr.writeUInt32BE(W, 0)
|
||||
ihdr.writeUInt32BE(H, 4)
|
||||
ihdr[8] = 8 // bit depth
|
||||
ihdr[9] = 6 // color type: RGBA
|
||||
ihdr[10] = 0 // compression
|
||||
ihdr[11] = 0 // filter
|
||||
ihdr[12] = 0 // interlace
|
||||
|
||||
const png = Buffer.concat([
|
||||
Buffer.from([0x89, 0x50, 0x4e, 0x47, 0x0d, 0x0a, 0x1a, 0x0a]),
|
||||
chunk('IHDR', ihdr),
|
||||
chunk('IDAT', deflateSync(raw, { level: 9 })),
|
||||
chunk('IEND', Buffer.alloc(0)),
|
||||
])
|
||||
|
||||
writeFileSync('public/og-image.png', png)
|
||||
console.log(`og-image.png generated: ${W}x${H}, ${png.length} bytes`)
|
||||
@@ -0,0 +1,30 @@
|
||||
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 }
|
||||
})
|
||||
@@ -0,0 +1,15 @@
|
||||
import { requireUser } from '../../utils/auth'
|
||||
import { getDb } from '../../utils/db'
|
||||
|
||||
/**
|
||||
* 当前用户的全部评论(个人中心「我的评论」)
|
||||
*/
|
||||
export default defineEventHandler((event) => {
|
||||
const user = requireUser(event)
|
||||
const rows = getDb()
|
||||
.prepare(
|
||||
'SELECT id, news_slug AS newsSlug, content, created_at AS createdAt FROM comments WHERE user_id = ? ORDER BY created_at DESC',
|
||||
)
|
||||
.all(user.id)
|
||||
return { comments: rows }
|
||||
})
|
||||
@@ -0,0 +1,30 @@
|
||||
import { readBody, createError } from 'h3'
|
||||
import { getDb } from '../../utils/db'
|
||||
import { verifyPassword, createSession, setSessionCookie, toPublicUser, type UserRow } from '../../utils/auth'
|
||||
|
||||
/**
|
||||
* 登录:账号(用户名或邮箱)+ 密码 -> 校验 -> 建立会话
|
||||
*/
|
||||
export default defineEventHandler(async (event) => {
|
||||
const body = await readBody(event)
|
||||
const account = String(body?.account ?? '').trim()
|
||||
const password = String(body?.password ?? '')
|
||||
|
||||
if (!account || !password) {
|
||||
throw createError({ statusCode: 400, message: '请输入账号与密码', data: { code: 'VALIDATION_ERROR' } })
|
||||
}
|
||||
|
||||
const db = getDb()
|
||||
const user = db
|
||||
.prepare('SELECT * FROM users WHERE username = ? OR email = ?')
|
||||
.get(account, account.toLowerCase()) as (UserRow & { password_hash: string }) | undefined
|
||||
|
||||
if (!user || !(await verifyPassword(password, user.password_hash))) {
|
||||
throw createError({ statusCode: 401, message: '账号或密码错误', data: { code: 'INVALID_CREDENTIALS' } })
|
||||
}
|
||||
|
||||
const token = createSession(user.id)
|
||||
setSessionCookie(event, token)
|
||||
|
||||
return { user: toPublicUser(user) }
|
||||
})
|
||||
@@ -0,0 +1,14 @@
|
||||
import { getCookie } from 'h3'
|
||||
import { SESSION_COOKIE, destroySession, clearSessionCookie } from '../../utils/auth'
|
||||
|
||||
/**
|
||||
* 登出:销毁会话并清除 Cookie
|
||||
*/
|
||||
export default defineEventHandler((event) => {
|
||||
const token = getCookie(event, SESSION_COOKIE)
|
||||
if (token) {
|
||||
destroySession(token)
|
||||
}
|
||||
clearSessionCookie(event)
|
||||
return { ok: true }
|
||||
})
|
||||
@@ -0,0 +1,13 @@
|
||||
import { createError } from 'h3'
|
||||
import { getCurrentUser, toPublicUser } from '../../utils/auth'
|
||||
|
||||
/**
|
||||
* 当前登录用户
|
||||
*/
|
||||
export default defineEventHandler((event) => {
|
||||
const user = getCurrentUser(event)
|
||||
if (!user) {
|
||||
throw createError({ statusCode: 401, message: '未登录', data: { code: 'UNAUTHORIZED' } })
|
||||
}
|
||||
return { user: toPublicUser(user) }
|
||||
})
|
||||
@@ -0,0 +1,41 @@
|
||||
import { readBody, createError } from 'h3'
|
||||
import { getDb } from '../../utils/db'
|
||||
import { requireUser, toPublicUser, type UserRow } from '../../utils/auth'
|
||||
import { isValidUsername, isValidPhone } from '../../utils/validation'
|
||||
|
||||
/**
|
||||
* 更新当前用户资料(用户名/手机号)
|
||||
*/
|
||||
export default defineEventHandler(async (event) => {
|
||||
const user = requireUser(event)
|
||||
const body = await readBody(event)
|
||||
const db = getDb()
|
||||
|
||||
if (body?.username !== undefined) {
|
||||
const username = String(body.username).trim()
|
||||
if (!isValidUsername(username)) {
|
||||
throw createError({ statusCode: 400, message: '用户名需为 2-20 位字符', data: { code: 'VALIDATION_ERROR' } })
|
||||
}
|
||||
const taken = db
|
||||
.prepare('SELECT id FROM users WHERE username = ? AND id != ?')
|
||||
.get(username, user.id)
|
||||
if (taken) {
|
||||
throw createError({ statusCode: 400, message: '用户名已被使用', data: { code: 'USERNAME_TAKEN' } })
|
||||
}
|
||||
db.prepare('UPDATE users SET username = ? WHERE id = ?').run(username, user.id)
|
||||
}
|
||||
|
||||
if (body?.phone !== undefined) {
|
||||
const phone = String(body.phone).trim()
|
||||
if (!isValidPhone(phone)) {
|
||||
throw createError({ statusCode: 400, message: '手机号格式不正确', data: { code: 'VALIDATION_ERROR' } })
|
||||
}
|
||||
db.prepare('UPDATE users SET phone = ? WHERE id = ?').run(phone || null, user.id)
|
||||
}
|
||||
|
||||
const updated = db
|
||||
.prepare('SELECT id, username, email, phone, role, created_at FROM users WHERE id = ?')
|
||||
.get(user.id) as UserRow
|
||||
|
||||
return { user: toPublicUser(updated) }
|
||||
})
|
||||
@@ -0,0 +1,54 @@
|
||||
import { readBody, createError } from 'h3'
|
||||
import { getDb } from '../../utils/db'
|
||||
import { hashPassword, createSession, setSessionCookie, toPublicUser, type UserRow } from '../../utils/auth'
|
||||
import { isValidUsername, isValidEmail, isValidPassword, isValidPhone } from '../../utils/validation'
|
||||
|
||||
/**
|
||||
* 注册:校验 -> scrypt 哈希 -> 落库 -> 建立会话
|
||||
*/
|
||||
export default defineEventHandler(async (event) => {
|
||||
const body = await readBody(event)
|
||||
const username = String(body?.username ?? '').trim()
|
||||
const email = String(body?.email ?? '').trim().toLowerCase()
|
||||
const phone = String(body?.phone ?? '').trim()
|
||||
const password = String(body?.password ?? '')
|
||||
|
||||
if (!isValidUsername(username)) {
|
||||
throw createError({ statusCode: 400, message: '用户名需为 2-20 位字符', data: { code: 'VALIDATION_ERROR' } })
|
||||
}
|
||||
if (!isValidEmail(email)) {
|
||||
throw createError({ statusCode: 400, message: '邮箱格式不正确', data: { code: 'VALIDATION_ERROR' } })
|
||||
}
|
||||
if (!isValidPassword(password)) {
|
||||
throw createError({ statusCode: 400, message: '密码至少需要 8 位', data: { code: 'VALIDATION_ERROR' } })
|
||||
}
|
||||
if (phone && !isValidPhone(phone)) {
|
||||
throw createError({ statusCode: 400, message: '手机号格式不正确', data: { code: 'VALIDATION_ERROR' } })
|
||||
}
|
||||
|
||||
const db = getDb()
|
||||
const existing = db
|
||||
.prepare('SELECT username, email FROM users WHERE username = ? OR email = ?')
|
||||
.get(username, email) as { username: string; email: string } | undefined
|
||||
|
||||
if (existing) {
|
||||
if (existing.username === username) {
|
||||
throw createError({ statusCode: 400, message: '用户名已被使用', data: { code: 'USERNAME_TAKEN' } })
|
||||
}
|
||||
throw createError({ statusCode: 400, message: '该邮箱已被注册', data: { code: 'EMAIL_TAKEN' } })
|
||||
}
|
||||
|
||||
const passwordHash = await hashPassword(password)
|
||||
const info = db
|
||||
.prepare('INSERT INTO users (username, email, phone, password_hash) VALUES (?, ?, ?, ?)')
|
||||
.run(username, email, phone || null, passwordHash)
|
||||
|
||||
const user = db
|
||||
.prepare('SELECT id, username, email, phone, role, created_at FROM users WHERE id = ?')
|
||||
.get(info.lastInsertRowid) as UserRow
|
||||
|
||||
const token = createSession(user.id)
|
||||
setSessionCookie(event, token)
|
||||
|
||||
return { user: toPublicUser(user) }
|
||||
})
|
||||
@@ -0,0 +1,34 @@
|
||||
import { getQuery, createError } from 'h3'
|
||||
import { getDb } from '../utils/db'
|
||||
import { newsBySlug } from '../../app/data/news'
|
||||
|
||||
/**
|
||||
* 指定新闻的评论列表(公开)
|
||||
*/
|
||||
export default defineEventHandler((event) => {
|
||||
const query = getQuery(event)
|
||||
const newsSlug = String(query?.newsSlug ?? '')
|
||||
|
||||
if (!newsBySlug[newsSlug]) {
|
||||
throw createError({ statusCode: 404, message: '文章不存在', data: { code: 'NOT_FOUND' } })
|
||||
}
|
||||
|
||||
const rows = getDb()
|
||||
.prepare(
|
||||
`SELECT c.id, c.content, c.created_at AS createdAt, u.username
|
||||
FROM comments c
|
||||
JOIN users u ON u.id = c.user_id
|
||||
WHERE c.news_slug = ?
|
||||
ORDER BY c.created_at ASC`,
|
||||
)
|
||||
.all(newsSlug) as Array<{ id: number; content: string; createdAt: string; username: string }>
|
||||
|
||||
return {
|
||||
comments: rows.map((r) => ({
|
||||
id: r.id,
|
||||
content: r.content,
|
||||
createdAt: r.createdAt,
|
||||
author: { username: r.username },
|
||||
})),
|
||||
}
|
||||
})
|
||||
@@ -0,0 +1,41 @@
|
||||
import { readBody, createError } from 'h3'
|
||||
import { requireUser } from '../utils/auth'
|
||||
import { getDb } from '../utils/db'
|
||||
import { newsBySlug } from '../../app/data/news'
|
||||
|
||||
/**
|
||||
* 发表评论(需登录)
|
||||
*/
|
||||
export default defineEventHandler(async (event) => {
|
||||
const user = requireUser(event)
|
||||
const body = await readBody(event)
|
||||
const newsSlug = String(body?.newsSlug ?? '')
|
||||
const content = String(body?.content ?? '').trim()
|
||||
|
||||
if (!newsBySlug[newsSlug]) {
|
||||
throw createError({ statusCode: 400, message: '未知的文章', data: { code: 'VALIDATION_ERROR' } })
|
||||
}
|
||||
if (!content) {
|
||||
throw createError({ statusCode: 400, message: '评论内容不能为空', data: { code: 'VALIDATION_ERROR' } })
|
||||
}
|
||||
if (content.length > 2000) {
|
||||
throw createError({ statusCode: 400, message: '评论内容过长(最多 2000 字)', data: { code: 'VALIDATION_ERROR' } })
|
||||
}
|
||||
|
||||
const info = getDb()
|
||||
.prepare('INSERT INTO comments (news_slug, user_id, content) VALUES (?, ?, ?)')
|
||||
.run(newsSlug, user.id, content)
|
||||
|
||||
const row = getDb()
|
||||
.prepare('SELECT id, content, created_at AS createdAt FROM comments WHERE id = ?')
|
||||
.get(info.lastInsertRowid) as { id: number; content: string; createdAt: string }
|
||||
|
||||
return {
|
||||
comment: {
|
||||
id: row.id,
|
||||
content: row.content,
|
||||
createdAt: row.createdAt,
|
||||
author: { username: user.username },
|
||||
},
|
||||
}
|
||||
})
|
||||
@@ -0,0 +1,43 @@
|
||||
import { readBody, createError } from 'h3'
|
||||
import { getDb } from '../utils/db'
|
||||
import { getConfig } from '../utils/config'
|
||||
import { sendMail } from '../utils/email'
|
||||
import { isValidEmail } from '../utils/validation'
|
||||
|
||||
/**
|
||||
* 联系表单:真实落库 + 尽力发送邮件(SMTP 未配置时 delivered=false,但数据不丢)
|
||||
*/
|
||||
export default defineEventHandler(async (event) => {
|
||||
const body = await readBody(event)
|
||||
const name = String(body?.name ?? '').trim()
|
||||
const email = String(body?.email ?? '').trim().toLowerCase()
|
||||
const subject = String(body?.subject ?? '').trim()
|
||||
const message = String(body?.message ?? '').trim()
|
||||
|
||||
if (!name || !subject || !message) {
|
||||
throw createError({ statusCode: 400, message: '请完整填写姓名、主题与留言内容', data: { code: 'VALIDATION_ERROR' } })
|
||||
}
|
||||
if (!isValidEmail(email)) {
|
||||
throw createError({ statusCode: 400, message: '邮箱格式不正确', data: { code: 'VALIDATION_ERROR' } })
|
||||
}
|
||||
|
||||
const { contactTo } = getConfig()
|
||||
const result = contactTo
|
||||
? await sendMail(
|
||||
contactTo,
|
||||
`[站点联系] ${subject}`,
|
||||
`姓名: ${name}\n邮箱: ${email}\n主题: ${subject}\n\n${message}`,
|
||||
)
|
||||
: { sent: false, skipped: true }
|
||||
|
||||
const db = getDb()
|
||||
db.prepare('INSERT INTO contacts (name, email, subject, message, delivered) VALUES (?, ?, ?, ?, ?)').run(
|
||||
name,
|
||||
email,
|
||||
subject,
|
||||
message,
|
||||
result.sent ? 1 : 0,
|
||||
)
|
||||
|
||||
return { ok: true, delivered: result.sent }
|
||||
})
|
||||
@@ -0,0 +1,16 @@
|
||||
import { readBody } from 'h3'
|
||||
import { requireUser } from '../utils/auth'
|
||||
import { getDb } from '../utils/db'
|
||||
|
||||
/**
|
||||
* 取消收藏
|
||||
*/
|
||||
export default defineEventHandler(async (event) => {
|
||||
const user = requireUser(event)
|
||||
const body = await readBody(event)
|
||||
const workSlug = String(body?.workSlug ?? '')
|
||||
|
||||
getDb().prepare('DELETE FROM favorites WHERE user_id = ? AND work_slug = ?').run(user.id, workSlug)
|
||||
|
||||
return { ok: true }
|
||||
})
|
||||
@@ -0,0 +1,13 @@
|
||||
import { requireUser } from '../utils/auth'
|
||||
import { getDb } from '../utils/db'
|
||||
|
||||
/**
|
||||
* 当前用户收藏的作品 slug 列表
|
||||
*/
|
||||
export default defineEventHandler((event) => {
|
||||
const user = requireUser(event)
|
||||
const rows = getDb()
|
||||
.prepare('SELECT work_slug FROM favorites WHERE user_id = ? ORDER BY created_at DESC')
|
||||
.all(user.id) as Array<{ work_slug: string }>
|
||||
return { slugs: rows.map((r) => r.work_slug) }
|
||||
})
|
||||
@@ -0,0 +1,23 @@
|
||||
import { readBody, createError } from 'h3'
|
||||
import { requireUser } from '../utils/auth'
|
||||
import { getDb } from '../utils/db'
|
||||
import { workBySlug } from '../../app/data/work'
|
||||
|
||||
/**
|
||||
* 收藏作品(幂等)
|
||||
*/
|
||||
export default defineEventHandler(async (event) => {
|
||||
const user = requireUser(event)
|
||||
const body = await readBody(event)
|
||||
const workSlug = String(body?.workSlug ?? '')
|
||||
|
||||
if (!workBySlug[workSlug]) {
|
||||
throw createError({ statusCode: 400, message: '未知的作品', data: { code: 'VALIDATION_ERROR' } })
|
||||
}
|
||||
|
||||
getDb()
|
||||
.prepare('INSERT OR IGNORE INTO favorites (user_id, work_slug) VALUES (?, ?)')
|
||||
.run(user.id, workSlug)
|
||||
|
||||
return { ok: true }
|
||||
})
|
||||
@@ -0,0 +1,32 @@
|
||||
import { readBody, createError } from 'h3'
|
||||
import { getDb } from '../utils/db'
|
||||
import { sendMail } from '../utils/email'
|
||||
import { isValidEmail } from '../utils/validation'
|
||||
|
||||
/**
|
||||
* 邮箱订阅:去重落库 + 尽力发送欢迎邮件
|
||||
*/
|
||||
export default defineEventHandler(async (event) => {
|
||||
const body = await readBody(event)
|
||||
const email = String(body?.email ?? '').trim().toLowerCase()
|
||||
|
||||
if (!isValidEmail(email)) {
|
||||
throw createError({ statusCode: 400, message: '邮箱格式不正确', data: { code: 'VALIDATION_ERROR' } })
|
||||
}
|
||||
|
||||
const db = getDb()
|
||||
const existing = db.prepare('SELECT id FROM subscribers WHERE email = ?').get(email)
|
||||
if (existing) {
|
||||
throw createError({ statusCode: 400, message: '您已在订阅列表中', data: { code: 'ALREADY_SUBSCRIBED' } })
|
||||
}
|
||||
|
||||
db.prepare('INSERT INTO subscribers (email) VALUES (?)').run(email)
|
||||
|
||||
await sendMail(
|
||||
email,
|
||||
'欢迎订阅 ArcticNewOne 资讯',
|
||||
'感谢订阅 ArcticNewOne!我们会不定期发送精选更新,助您把握设计、开发与行业动态。',
|
||||
)
|
||||
|
||||
return { ok: true }
|
||||
})
|
||||
@@ -0,0 +1,18 @@
|
||||
import { getConfig } from '../utils/config'
|
||||
|
||||
/**
|
||||
* 动态 robots.txt(/robots.txt)。
|
||||
* 提示搜索引擎可抓取,并指向动态 sitemap。
|
||||
*/
|
||||
export default defineEventHandler(() => {
|
||||
const { siteUrl } = getConfig()
|
||||
const sitemapLine = siteUrl ? `${siteUrl}/sitemap.xml` : '/sitemap.xml'
|
||||
const body = `User-agent: *
|
||||
Allow: /
|
||||
|
||||
Sitemap: ${sitemapLine}
|
||||
`
|
||||
return new Response(body, {
|
||||
headers: { 'Content-Type': 'text/plain; charset=utf-8' },
|
||||
})
|
||||
})
|
||||
@@ -0,0 +1,44 @@
|
||||
import { getConfig } from '../utils/config'
|
||||
import { newsItems } from '../../app/data/news'
|
||||
import { workItems } from '../../app/data/work'
|
||||
|
||||
/**
|
||||
* 动态站点地图 /sitemap.xml。
|
||||
* 路由与数据均来自单一事实源(app/data/*),内容更新无需手工同步。
|
||||
*/
|
||||
export default defineEventHandler(() => {
|
||||
const { siteUrl } = getConfig()
|
||||
|
||||
const urls: Array<{ loc: string; changefreq: string; priority: string }> = [
|
||||
{ loc: '/', changefreq: 'weekly', priority: '1.0' },
|
||||
{ loc: '/studio', changefreq: 'monthly', priority: '0.8' },
|
||||
{ loc: '/work', changefreq: 'weekly', priority: '0.8' },
|
||||
{ loc: '/news', changefreq: 'weekly', priority: '0.8' },
|
||||
{ loc: '/tools', changefreq: 'monthly', priority: '0.6' },
|
||||
{ loc: '/contact', changefreq: 'monthly', priority: '0.6' },
|
||||
]
|
||||
|
||||
for (const item of workItems) {
|
||||
urls.push({ loc: `/work/${item.slug}`, changefreq: 'monthly', priority: '0.7' })
|
||||
}
|
||||
for (const item of newsItems) {
|
||||
urls.push({ loc: `/news/${item.slug}`, changefreq: 'weekly', priority: '0.7' })
|
||||
}
|
||||
|
||||
const xml = `<?xml version="1.0" encoding="UTF-8"?>
|
||||
<urlset xmlns="http://www.sitemaps.org/schemas/sitemap/0.9">
|
||||
${urls
|
||||
.map(
|
||||
(u) => ` <url>
|
||||
<loc>${siteUrl}${u.loc}</loc>
|
||||
<changefreq>${u.changefreq}</changefreq>
|
||||
<priority>${u.priority}</priority>
|
||||
</url>`,
|
||||
)
|
||||
.join('\n')}
|
||||
</urlset>`
|
||||
|
||||
return new Response(xml, {
|
||||
headers: { 'Content-Type': 'text/xml; charset=utf-8' },
|
||||
})
|
||||
})
|
||||
@@ -0,0 +1,134 @@
|
||||
import { randomBytes, scrypt, timingSafeEqual } from 'node:crypto'
|
||||
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,
|
||||
salt: string,
|
||||
keylen: number,
|
||||
) => Promise<Buffer>
|
||||
|
||||
export interface UserRow {
|
||||
id: number
|
||||
username: string
|
||||
email: string
|
||||
phone: string | null
|
||||
role: 'user' | 'admin'
|
||||
created_at: string
|
||||
}
|
||||
|
||||
export const SESSION_COOKIE = 'an_session'
|
||||
const SESSION_TTL_SECONDS = 30 * 24 * 60 * 60 // 30 天
|
||||
|
||||
// ---------- 密码哈希(scrypt,盐 + 哈希以冒号分隔存储) ----------
|
||||
|
||||
export async function hashPassword(password: string): Promise<string> {
|
||||
const salt = randomBytes(16).toString('hex')
|
||||
const key = await scryptAsync(password, salt, 64)
|
||||
return `${salt}:${key.toString('hex')}`
|
||||
}
|
||||
|
||||
export async function verifyPassword(password: string, stored: string): Promise<boolean> {
|
||||
const [salt, hash] = stored.split(':')
|
||||
if (!salt || !hash) return false
|
||||
const key = await scryptAsync(password, salt, 64)
|
||||
const expected = Buffer.from(hash, 'hex')
|
||||
return key.length === expected.length && timingSafeEqual(key, expected)
|
||||
}
|
||||
|
||||
// ---------- 会话 ----------
|
||||
|
||||
export function createSession(userId: number): string {
|
||||
const token = randomBytes(32).toString('hex')
|
||||
const expiresAt = new Date(Date.now() + SESSION_TTL_SECONDS * 1000).toISOString()
|
||||
getDb()
|
||||
.prepare('INSERT INTO sessions (token, user_id, expires_at) VALUES (?, ?, ?)')
|
||||
.run(token, userId, expiresAt)
|
||||
return token
|
||||
}
|
||||
|
||||
export function destroySession(token: string): void {
|
||||
getDb().prepare('DELETE FROM sessions WHERE token = ?').run(token)
|
||||
}
|
||||
|
||||
/** 根据 token 返回有效用户(过期会话返回 null);role 随 ADMIN_EMAILS 实时判定 */
|
||||
export function getSessionUser(token: string | null): UserRow | null {
|
||||
if (!token) return null
|
||||
const row = getDb()
|
||||
.prepare(
|
||||
`SELECT u.id, u.username, u.email, u.phone, u.role, u.created_at
|
||||
FROM sessions s
|
||||
JOIN users u ON u.id = s.user_id
|
||||
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
|
||||
}
|
||||
|
||||
/** 从请求 Cookie 中解析当前登录用户 */
|
||||
export function getCurrentUser(event: H3Event): UserRow | null {
|
||||
const token = getCookie(event, SESSION_COOKIE)
|
||||
return getSessionUser(token)
|
||||
}
|
||||
|
||||
/** 需要登录的接口守卫;未登录抛出 401 */
|
||||
export function requireUser(event: H3Event): UserRow {
|
||||
const user = getCurrentUser(event)
|
||||
if (!user) {
|
||||
throw createError({ statusCode: 401, statusMessage: '未登录', message: '未登录', data: { code: 'UNAUTHORIZED' } })
|
||||
}
|
||||
return user
|
||||
}
|
||||
|
||||
/** 需要管理员权限的接口守卫;非管理员抛出 403 */
|
||||
export function requireAdmin(event: H3Event): UserRow {
|
||||
const user = requireUser(event)
|
||||
if (user.role !== 'admin') {
|
||||
throw createError({ statusCode: 403, statusMessage: '无权限', message: '无权限', data: { code: 'FORBIDDEN' } })
|
||||
}
|
||||
return user
|
||||
}
|
||||
|
||||
/** 登录成功后写入会话 Cookie */
|
||||
export function setSessionCookie(event: H3Event, token: string): void {
|
||||
const secure = process.env.NODE_ENV === 'production'
|
||||
setCookie(event, SESSION_COOKIE, token, {
|
||||
httpOnly: true,
|
||||
sameSite: 'lax',
|
||||
secure,
|
||||
path: '/',
|
||||
maxAge: SESSION_TTL_SECONDS,
|
||||
})
|
||||
}
|
||||
|
||||
/** 登出时清除会话 Cookie */
|
||||
export function clearSessionCookie(event: H3Event): void {
|
||||
deleteCookie(event, SESSION_COOKIE, { path: '/' })
|
||||
}
|
||||
|
||||
/** 返回给前端的脱敏用户对象(含 admin 角色,供个人中心展示) */
|
||||
export function toPublicUser(user: UserRow): {
|
||||
id: number
|
||||
username: string
|
||||
email: string
|
||||
phone: string | null
|
||||
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,
|
||||
createdAt: user.created_at,
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,56 @@
|
||||
import { useRuntimeConfig } from '#imports'
|
||||
|
||||
/**
|
||||
* 统一的应用配置读取。
|
||||
*
|
||||
* 所有配置均来自 Nuxt runtimeConfig(生产环境由 K8s 环境变量注入,
|
||||
* 本地开发由 .env 注入),避免散落的 process.env 读取。
|
||||
*
|
||||
* 环境变量映射:
|
||||
* SESSION_SECRET -> sessionSecret
|
||||
* DB_PATH -> dbPath(默认 生产 /data/arcticnewone.db,开发 .data/arcticnewone.db)
|
||||
* SMTP_HOST/PORT/USER/PASS/FROM -> smtp.*
|
||||
* CONTACT_TO -> contactTo
|
||||
* ADMIN_EMAILS -> adminEmails(逗号分隔)
|
||||
* NUXT_PUBLIC_SITE_URL -> public.siteUrl
|
||||
*/
|
||||
export interface AppConfig {
|
||||
dbPath: string
|
||||
sessionSecret: string
|
||||
smtp: {
|
||||
host: string
|
||||
port: number
|
||||
user: string
|
||||
pass: string
|
||||
from: string
|
||||
}
|
||||
contactTo: string
|
||||
adminEmails: string[]
|
||||
siteUrl: string
|
||||
}
|
||||
|
||||
export function getConfig(): AppConfig {
|
||||
const c = useRuntimeConfig()
|
||||
return {
|
||||
dbPath: (c.dbPath as string) || '.data/arcticnewone.db',
|
||||
sessionSecret: (c.sessionSecret as string) || '',
|
||||
smtp: {
|
||||
host: (c.smtpHost as string) || '',
|
||||
port: Number(c.smtpPort) || 587,
|
||||
user: (c.smtpUser as string) || '',
|
||||
pass: (c.smtpPass as string) || '',
|
||||
from: (c.smtpFrom as string) || '',
|
||||
},
|
||||
contactTo: (c.contactTo as string) || '',
|
||||
adminEmails: String(c.adminEmails || '')
|
||||
.split(',')
|
||||
.map((s) => s.trim().toLowerCase())
|
||||
.filter(Boolean),
|
||||
siteUrl: String((c.public as { siteUrl?: string })?.siteUrl || '').replace(/\/$/, ''),
|
||||
}
|
||||
}
|
||||
|
||||
/** 判断某邮箱是否在管理员白名单中 */
|
||||
export function isAdminEmail(email: string): boolean {
|
||||
return getConfig().adminEmails.includes(email.toLowerCase())
|
||||
}
|
||||
@@ -0,0 +1,101 @@
|
||||
import Database from 'better-sqlite3'
|
||||
import { mkdirSync } from 'node:fs'
|
||||
import { dirname } from 'node:path'
|
||||
import { getConfig } from './config'
|
||||
|
||||
/**
|
||||
* SQLite 数据层单例。
|
||||
*
|
||||
* - 数据库文件路径来自 getConfig().dbPath(生产挂载 /data 下的 PVC,开发在 .data/)
|
||||
* - 惰性初始化 + 幂等建表(CREATE TABLE IF NOT EXISTS),首次使用自动创建
|
||||
* - WAL 模式提升并发读写可靠性;外键开启
|
||||
*
|
||||
* 表结构:
|
||||
* users 用户(注册/登录)
|
||||
* sessions 会话(httpOnly Cookie token)
|
||||
* contacts 联系表单留言
|
||||
* subscribers 邮箱订阅
|
||||
* favorites 作品收藏
|
||||
* comments 新闻评论
|
||||
*/
|
||||
let _db: Database.Database | null = null
|
||||
|
||||
export function getDb(): Database.Database {
|
||||
if (_db) return _db
|
||||
|
||||
const { dbPath } = getConfig()
|
||||
mkdirSync(dirname(dbPath), { recursive: true })
|
||||
|
||||
_db = new Database(dbPath)
|
||||
_db.pragma('journal_mode = WAL')
|
||||
_db.pragma('foreign_keys = ON')
|
||||
migrate(_db)
|
||||
return _db
|
||||
}
|
||||
|
||||
function migrate(db: Database.Database): void {
|
||||
db.exec(`
|
||||
CREATE TABLE IF NOT EXISTS users (
|
||||
id INTEGER PRIMARY KEY AUTOINCREMENT,
|
||||
username TEXT NOT NULL UNIQUE,
|
||||
email TEXT NOT NULL UNIQUE,
|
||||
phone TEXT,
|
||||
password_hash TEXT NOT NULL,
|
||||
role TEXT NOT NULL DEFAULT 'user',
|
||||
created_at TEXT NOT NULL DEFAULT (datetime('now'))
|
||||
);
|
||||
|
||||
CREATE TABLE IF NOT EXISTS sessions (
|
||||
token TEXT PRIMARY KEY,
|
||||
user_id INTEGER NOT NULL REFERENCES users(id) ON DELETE CASCADE,
|
||||
created_at TEXT NOT NULL DEFAULT (datetime('now')),
|
||||
expires_at TEXT NOT NULL
|
||||
);
|
||||
|
||||
CREATE INDEX IF NOT EXISTS idx_sessions_user ON sessions(user_id);
|
||||
|
||||
CREATE TABLE IF NOT EXISTS contacts (
|
||||
id INTEGER PRIMARY KEY AUTOINCREMENT,
|
||||
name TEXT NOT NULL,
|
||||
email TEXT NOT NULL,
|
||||
subject TEXT NOT NULL,
|
||||
message TEXT NOT NULL,
|
||||
delivered INTEGER NOT NULL DEFAULT 0,
|
||||
created_at TEXT NOT NULL DEFAULT (datetime('now'))
|
||||
);
|
||||
|
||||
CREATE TABLE IF NOT EXISTS subscribers (
|
||||
id INTEGER PRIMARY KEY AUTOINCREMENT,
|
||||
email TEXT NOT NULL UNIQUE,
|
||||
created_at TEXT NOT NULL DEFAULT (datetime('now'))
|
||||
);
|
||||
|
||||
CREATE TABLE IF NOT EXISTS favorites (
|
||||
id INTEGER PRIMARY KEY AUTOINCREMENT,
|
||||
user_id INTEGER NOT NULL REFERENCES users(id) ON DELETE CASCADE,
|
||||
work_slug TEXT NOT NULL,
|
||||
created_at TEXT NOT NULL DEFAULT (datetime('now')),
|
||||
UNIQUE (user_id, work_slug)
|
||||
);
|
||||
|
||||
CREATE INDEX IF NOT EXISTS idx_favorites_user ON favorites(user_id);
|
||||
|
||||
CREATE TABLE IF NOT EXISTS comments (
|
||||
id INTEGER PRIMARY KEY AUTOINCREMENT,
|
||||
news_slug TEXT NOT NULL,
|
||||
user_id INTEGER NOT NULL REFERENCES users(id) ON DELETE CASCADE,
|
||||
content TEXT NOT NULL,
|
||||
created_at TEXT NOT NULL DEFAULT (datetime('now'))
|
||||
);
|
||||
|
||||
CREATE INDEX IF NOT EXISTS idx_comments_news ON comments(news_slug);
|
||||
`)
|
||||
}
|
||||
|
||||
/** 供服务端任意位置安全关闭数据库(测试/热更新用) */
|
||||
export function closeDb(): void {
|
||||
if (_db) {
|
||||
_db.close()
|
||||
_db = null
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,52 @@
|
||||
import nodemailer from 'nodemailer'
|
||||
import type { Transporter } from 'nodemailer'
|
||||
import { getConfig } from './config'
|
||||
|
||||
/**
|
||||
* 邮件发送(nodemailer + SMTP)。
|
||||
*
|
||||
* 设计原则:
|
||||
* - **真实优先**:所有业务数据(联系留言、订阅)一律先落库,邮件为送达手段;
|
||||
* - **配置缺席不造假**:SMTP 未配置时返回 `{ sent: false, skipped: true }`,
|
||||
* 由调用方如实记录(如 contacts.delivered=0),绝不假装发送成功。
|
||||
*/
|
||||
let transporter: Transporter | null = null
|
||||
|
||||
function getTransporter(): Transporter | null {
|
||||
const { smtp } = getConfig()
|
||||
if (!smtp.host) return null
|
||||
if (transporter) return transporter
|
||||
|
||||
transporter = nodemailer.createTransport({
|
||||
host: smtp.host,
|
||||
port: smtp.port,
|
||||
secure: smtp.port === 465,
|
||||
auth: smtp.user ? { user: smtp.user, pass: smtp.pass } : undefined,
|
||||
})
|
||||
return transporter
|
||||
}
|
||||
|
||||
export interface MailResult {
|
||||
sent: boolean
|
||||
/** SMTP 未配置时 true */
|
||||
skipped?: boolean
|
||||
error?: string
|
||||
}
|
||||
|
||||
/** 发送邮件;SMTP 未配置或发送失败时不会抛出,调用方自行处理 */
|
||||
export async function sendMail(to: string, subject: string, text: string, html?: string): Promise<MailResult> {
|
||||
const transport = getTransporter()
|
||||
const { smtp } = getConfig()
|
||||
|
||||
if (!transport || !smtp.from) {
|
||||
return { sent: false, skipped: true }
|
||||
}
|
||||
|
||||
try {
|
||||
await transport.sendMail({ from: smtp.from, to, subject, text, html })
|
||||
return { sent: true }
|
||||
} catch (err) {
|
||||
console.error('[email] send failed:', err)
|
||||
return { sent: false, error: err instanceof Error ? err.message : String(err) }
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,25 @@
|
||||
/**
|
||||
* 输入校验(供后端 API 复用,避免各路由重复)。
|
||||
*/
|
||||
export const usernameRe = /^[\w一-龥]{2,20}$/
|
||||
export const emailRe = /^[^\s@]+@[^\s@]+\.[^\s@]+$/
|
||||
export const phoneRe = /^1[3-9]\d{9}$/
|
||||
|
||||
export function isValidUsername(value: unknown): value is string {
|
||||
return typeof value === 'string' && usernameRe.test(value)
|
||||
}
|
||||
|
||||
export function isValidEmail(value: unknown): value is string {
|
||||
return typeof value === 'string' && emailRe.test(value)
|
||||
}
|
||||
|
||||
/** 密码至少 8 位 */
|
||||
export function isValidPassword(value: unknown): value is string {
|
||||
return typeof value === 'string' && value.length >= 8
|
||||
}
|
||||
|
||||
/** 手机号可空;填写时必须符合中国手机号格式 */
|
||||
export function isValidPhone(value: unknown): value is string {
|
||||
if (typeof value !== 'string') return false
|
||||
return value === '' || phoneRe.test(value)
|
||||
}
|
||||
Reference in New Issue
Block a user