Commit d925be74 authored by xuchentao's avatar xuchentao

feat: add article CMS with safe deployment locking

parent 8c1711c1
...@@ -2,4 +2,10 @@ node_modules/ ...@@ -2,4 +2,10 @@ node_modules/
dist/ dist/
.astro/ .astro/
.codex-tmp/ .codex-tmp/
.runtime/
.env
src/content/articles/
src/content/published/
src/content/categories.json
public/uploads/
.DS_Store .DS_Store
# 塑美俏健康资讯后台
本项目采用与官网同端口的 Astro 文章后台:Markdown 文件负责内容存储,Astro 同时提供后台 API 和静态页面生成。文章列表、分类页和详情页全部预渲染为 HTML,便于 SEO 与 GEO 搜索。
## 本地启动
开发模式(Astro 默认端口,支持页面热更新与同端口后台):
```bash
npm run dev
```
- 官网:终端显示的开发地址(通常为 `http://localhost:4321/`
- 文章后台:在同一地址后添加 `/admin`(通常为 `http://localhost:4321/admin`
生产模式预览:
```bash
npm run build
npm start
```
- 官网:`http://localhost:8789/`
- 文章后台:`http://localhost:8789/admin`
- 健康资讯:`http://localhost:8789/articles/`
启动命令会自动读取项目根目录的 `.env`,其中包含:
- `CMS_PORT`:官网与后台共用的服务端口,默认 `8789`(斯嘉丽项目端口 `8788` + 1)
- `CMS_PASSWORD`:后台登录密码
- `CMS_SECRET`:后台会话签名密钥
- `CMS_API_KEY`:外部程序调用管理 API 时使用的 Bearer Token
- `CMS_DATA_DIR`:生产环境的用户数据目录,建议设置为仓库外的绝对路径
- `CMS_BUILD_LOCK`:代码部署与文章发布共用的锁文件,生产环境各个 release 必须配置成同一路径
## 后台 API
所有管理接口统一使用 `/api/cms` 前缀:
| 分组 | 方法与地址 | 用途 |
| --- | --- | --- |
| 会话 | `GET /api/cms/session` | 查询登录状态 |
| 会话 | `POST /api/cms/session` | 登录后台 |
| 会话 | `DELETE /api/cms/session` | 退出登录 |
| 分类 | `GET /api/cms/categories` | 分类列表与文章数量 |
| 分类 | `POST /api/cms/categories` | 新建分类 |
| 分类 | `PATCH /api/cms/categories` | 重命名分类 |
| 分类 | `DELETE /api/cms/categories` | 删除分类并迁移文章 |
| 文章 | `GET /api/cms/articles` | 文章列表 |
| 文章 | `POST /api/cms/articles` | 新建草稿 |
| 文章 | `GET /api/cms/articles/:slug` | 读取文章 |
| 文章 | `PUT /api/cms/articles/:slug` | 保存文章 |
| 文章 | `DELETE /api/cms/articles/:slug` | 删除文章 |
| 文章 | `DELETE /api/cms/articles/:slug/draft` | 放弃未发布修改 |
| 发布 | `POST /api/cms/articles/:slug/publish` | 发布并生成静态页面 |
| 发布 | `POST /api/cms/articles/:slug/unpublish` | 下架并生成静态页面 |
| 工具 | `POST /api/cms/preview` | Markdown 预览 |
| 工具 | `POST /api/cms/uploads` | 上传文章图片 |
| 构建 | `GET /api/cms/build` | 查询静态构建状态 |
除会话登录接口外,外部程序可通过 `Authorization: Bearer <CMS_API_KEY>` 调用这些地址。
## 内容目录
- `src/content/articles/`:后台工作稿,包括草稿、待发布和已发布文章
- `src/content/published/`:Astro 实际构建的已发布文章
- `src/content/categories.json`:后台用户维护的文章分类
- `public/uploads/`:后台上传的文章图片
以上目录均属于运行时用户数据,已在 `.gitignore` 中排除,不随 Git 提交或 CI/CD 部署覆盖。部署时应由服务器持久化并单独备份。
后台始终维护两个版本:
- `articles/` 是当前编辑稿;新建文章和已上线文章的未发布修改都保存在这里。
- `published/` 是官网当前使用的线上稿;保存草稿不会改动它。
- 点击“发布到官网”后,编辑稿才会覆盖线上稿,并重新执行 `npm run build`
- 点击“下架文章”后,线上稿会移除,编辑稿继续保留为未发布草稿。
- 点击“删除文章”会同时删除编辑稿和线上稿;若官网构建失败,系统会自动恢复删除前的版本。
文章状态分为“新建未发布”“修改未发布”和“已上线”。文章网址、摘要、作者及 SEO 时间信息均由程序自动生成,编辑人员只需填写标题、分类和正文。
## 两条部署流水线
### 用户提交文章
1. 保存草稿只写入 `articles/`,不影响官网。
2. 发布、下架、删除文章或修改已使用的分类时,后台先取得共享构建锁。
如果代码部署或其他构建已持有锁,本次操作直接返回冲突且不会排队受理,编辑人员稍后重试即可,避免服务重启导致已受理任务丢失。
3. 系统备份用户内容,修改 `published/`,在临时目录执行 Astro 静态构建。
4. 构建成功后原子替换 `dist/`;构建失败则恢复文章和分类数据,旧的 `dist/` 保持不变。
### Git 代码部署
生产环境必须把用户数据放在仓库外,例如:
```env
CMS_DATA_DIR=/srv/sumeiqiao/shared/cms-data
CMS_BUILD_LOCK=/srv/sumeiqiao/shared/site-build.lock
```
CI/CD 应在新的 release 目录检出代码,不要在正在运行的目录执行 `git clean`。安装依赖后,让“构建、切换 current 软链接、重启服务”整个过程持有同一把锁:
```bash
node scripts/run-with-site-lock.mjs -- ./deploy-release.sh
```
其中 `deploy-release.sh` 在锁内执行:
```bash
npm ci
npm run build:inside-lock
# 原子切换 /srv/sumeiqiao/current 软链接
# 重启 systemd/pm2 服务
```
普通本地构建或不包含 release 切换的 CI 可以直接运行 `npm run build`,它会自行取得同一把锁。这样两条流水线不会同时读取或覆盖文章数据,也不会同时替换静态网站。
import { defineConfig } from "astro/config"; import { defineConfig } from "astro/config";
import sitemap from "@astrojs/sitemap"; import sitemap from "@astrojs/sitemap";
import node from "@astrojs/node";
import path from "node:path";
const customOutDir = process.env.SUMEIQIAO_BUILD_OUT_DIR;
export default defineConfig({ export default defineConfig({
site: "https://www.sumeiqiao.com", site: "https://www.sumeiqiao.com",
integrations: [sitemap()], integrations: [sitemap()],
adapter: node({ mode: "standalone" }),
...(customOutDir ? { outDir: path.resolve(customOutDir) } : {}),
build: { format: "directory" }, build: { format: "directory" },
trailingSlash: "always", trailingSlash: "ignore",
}); });
...@@ -8,8 +8,11 @@ ...@@ -8,8 +8,11 @@
"name": "sumeiqiao-official-site", "name": "sumeiqiao-official-site",
"version": "1.0.0", "version": "1.0.0",
"dependencies": { "dependencies": {
"@astrojs/node": "^11.0.2",
"@astrojs/sitemap": "^3.7.3", "@astrojs/sitemap": "^3.7.3",
"astro": "^7.1.3" "astro": "^7.1.3",
"gray-matter": "^4.0.3",
"marked": "^14.1.4"
}, },
"devDependencies": { "devDependencies": {
"@astrojs/check": "^0.9.6", "@astrojs/check": "^0.9.6",
...@@ -301,6 +304,20 @@ ...@@ -301,6 +304,20 @@
"satteri": "^0.9.1" "satteri": "^0.9.1"
} }
}, },
"node_modules/@astrojs/node": {
"version": "11.0.2",
"resolved": "https://registry.npmjs.org/@astrojs/node/-/node-11.0.2.tgz",
"integrity": "sha512-/ijULxT+A5Cm8wSwWZ2vgqfim1b05D6B8n/a9l6MMA4FCotIH73g7fL7y76XojKXpTe75FVvQH92OxsMqea9kQ==",
"license": "MIT",
"dependencies": {
"@astrojs/internal-helpers": "0.10.1",
"send": "^1.2.1",
"server-destroy": "^1.0.1"
},
"peerDependencies": {
"astro": "^7.0.0"
}
},
"node_modules/@astrojs/prism": { "node_modules/@astrojs/prism": {
"version": "4.0.2", "version": "4.0.2",
"resolved": "https://registry.npmjs.org/@astrojs/prism/-/prism-4.0.2.tgz", "resolved": "https://registry.npmjs.org/@astrojs/prism/-/prism-4.0.2.tgz",
...@@ -2760,6 +2777,15 @@ ...@@ -2760,6 +2777,15 @@
"integrity": "sha512-7z22QmUWiQ/2d0KkdYmANbRUVABpZ9SNYyH5vx6PZ+nE5bcC0l7uFvEfHlyld/HcGBFTL536ClDt3DEcSlEJAQ==", "integrity": "sha512-7z22QmUWiQ/2d0KkdYmANbRUVABpZ9SNYyH5vx6PZ+nE5bcC0l7uFvEfHlyld/HcGBFTL536ClDt3DEcSlEJAQ==",
"license": "MIT" "license": "MIT"
}, },
"node_modules/depd": {
"version": "2.0.0",
"resolved": "https://registry.npmjs.org/depd/-/depd-2.0.0.tgz",
"integrity": "sha512-g7nH6P6dyDioJogAAGprGpCtVImJhpPk/roCzdb3fIh61/s/nPsfR6onyMwkCAR/OlC3yBC0lESvUoQEAssIrw==",
"license": "MIT",
"engines": {
"node": ">= 0.8"
}
},
"node_modules/dequal": { "node_modules/dequal": {
"version": "2.0.3", "version": "2.0.3",
"resolved": "https://registry.npmjs.org/dequal/-/dequal-2.0.3.tgz", "resolved": "https://registry.npmjs.org/dequal/-/dequal-2.0.3.tgz",
...@@ -2888,6 +2914,12 @@ ...@@ -2888,6 +2914,12 @@
"node": ">=4" "node": ">=4"
} }
}, },
"node_modules/ee-first": {
"version": "1.1.1",
"resolved": "https://registry.npmjs.org/ee-first/-/ee-first-1.1.1.tgz",
"integrity": "sha512-WMwm9LhRUo+WUaRN+vRuETqG89IgZphVSNkdFgeb6sS/E4OrDIN7t48CAewSHXc6C8lefD8KKfr5vY61brQlow==",
"license": "MIT"
},
"node_modules/emmet": { "node_modules/emmet": {
"version": "2.4.11", "version": "2.4.11",
"resolved": "https://registry.npmjs.org/emmet/-/emmet-2.4.11.tgz", "resolved": "https://registry.npmjs.org/emmet/-/emmet-2.4.11.tgz",
...@@ -2912,6 +2944,15 @@ ...@@ -2912,6 +2944,15 @@
"dev": true, "dev": true,
"license": "MIT" "license": "MIT"
}, },
"node_modules/encodeurl": {
"version": "2.0.0",
"resolved": "https://registry.npmjs.org/encodeurl/-/encodeurl-2.0.0.tgz",
"integrity": "sha512-Q0n9HRi4m6JuGIV1eFlmvJB7ZEVxu93IrMyiMsGC0lrMJMWzRgx6WGquyfQgZVb31vhGgXnfmPNNXmxnOkRBrg==",
"license": "MIT",
"engines": {
"node": ">= 0.8"
}
},
"node_modules/entities": { "node_modules/entities": {
"version": "6.0.1", "version": "6.0.1",
"resolved": "https://registry.npmjs.org/entities/-/entities-6.0.1.tgz", "resolved": "https://registry.npmjs.org/entities/-/entities-6.0.1.tgz",
...@@ -2981,12 +3022,40 @@ ...@@ -2981,12 +3022,40 @@
"node": ">=6" "node": ">=6"
} }
}, },
"node_modules/escape-html": {
"version": "1.0.3",
"resolved": "https://registry.npmjs.org/escape-html/-/escape-html-1.0.3.tgz",
"integrity": "sha512-NiSupZ4OeuGwr68lGIeym/ksIZMJodUGOSCZ/FSnTxcrekbvqrgdUxlJOMpijaKZVjAJrWrGs/6Jy8OMuyj9ow==",
"license": "MIT"
},
"node_modules/esprima": {
"version": "4.0.1",
"resolved": "https://registry.npmjs.org/esprima/-/esprima-4.0.1.tgz",
"integrity": "sha512-eGuFFw7Upda+g4p+QHvnW0RyTX/SVeJBDM/gCtMARO0cLuT2HcEKnTPvhjV6aGeqrCB/sbNop0Kszm0jsaWU4A==",
"license": "BSD-2-Clause",
"bin": {
"esparse": "bin/esparse.js",
"esvalidate": "bin/esvalidate.js"
},
"engines": {
"node": ">=4"
}
},
"node_modules/estree-walker": { "node_modules/estree-walker": {
"version": "2.0.2", "version": "2.0.2",
"resolved": "https://registry.npmjs.org/estree-walker/-/estree-walker-2.0.2.tgz", "resolved": "https://registry.npmjs.org/estree-walker/-/estree-walker-2.0.2.tgz",
"integrity": "sha512-Rfkk/Mp/DL7JVje3u18FxFujQlTNR2q6QfMSMB7AvCBx91NGj/ba3kCfza0f6dVDbw7YlRf/nDrn7pQrCCyQ/w==", "integrity": "sha512-Rfkk/Mp/DL7JVje3u18FxFujQlTNR2q6QfMSMB7AvCBx91NGj/ba3kCfza0f6dVDbw7YlRf/nDrn7pQrCCyQ/w==",
"license": "MIT" "license": "MIT"
}, },
"node_modules/etag": {
"version": "1.8.1",
"resolved": "https://registry.npmjs.org/etag/-/etag-1.8.1.tgz",
"integrity": "sha512-aIL5Fx7mawVa300al2BnEE4iNvo1qETxLrPI/o05L7z6go7fCw1J6EQmbK4FmJ2AS7kgVF/KEZWufBfdClMcPg==",
"license": "MIT",
"engines": {
"node": ">= 0.6"
}
},
"node_modules/eventemitter3": { "node_modules/eventemitter3": {
"version": "5.0.4", "version": "5.0.4",
"resolved": "https://registry.npmjs.org/eventemitter3/-/eventemitter3-5.0.4.tgz", "resolved": "https://registry.npmjs.org/eventemitter3/-/eventemitter3-5.0.4.tgz",
...@@ -2999,6 +3068,18 @@ ...@@ -2999,6 +3068,18 @@
"integrity": "sha512-fjquC59cD7CyW6urNXK0FBufkZcoiGG80wTuPujX590cB5Ttln20E2UB4S/WARVqhXffZl2LNgS+gQdPIIim/g==", "integrity": "sha512-fjquC59cD7CyW6urNXK0FBufkZcoiGG80wTuPujX590cB5Ttln20E2UB4S/WARVqhXffZl2LNgS+gQdPIIim/g==",
"license": "MIT" "license": "MIT"
}, },
"node_modules/extend-shallow": {
"version": "2.0.1",
"resolved": "https://registry.npmjs.org/extend-shallow/-/extend-shallow-2.0.1.tgz",
"integrity": "sha512-zCnTtlxNoAiDc3gqY2aYAWFx7XWWiasuF2K8Me5WbN8otHKTUKBwjPtNpRs/rbUZm7KxWAaNj7P1a/p52GbVug==",
"license": "MIT",
"dependencies": {
"is-extendable": "^0.1.0"
},
"engines": {
"node": ">=0.10.0"
}
},
"node_modules/fast-deep-equal": { "node_modules/fast-deep-equal": {
"version": "3.1.3", "version": "3.1.3",
"resolved": "https://registry.npmjs.org/fast-deep-equal/-/fast-deep-equal-3.1.3.tgz", "resolved": "https://registry.npmjs.org/fast-deep-equal/-/fast-deep-equal-3.1.3.tgz",
...@@ -3139,6 +3220,43 @@ ...@@ -3139,6 +3220,43 @@
"integrity": "sha512-IaOQ9puYtjrkq7Y0Ygl9KDZnrf/aiUJYUpVf89y8kyaxbRG7Y1SrX/jaumrv81vc61+kiMempujsM3Yw7w5qcw==", "integrity": "sha512-IaOQ9puYtjrkq7Y0Ygl9KDZnrf/aiUJYUpVf89y8kyaxbRG7Y1SrX/jaumrv81vc61+kiMempujsM3Yw7w5qcw==",
"license": "ISC" "license": "ISC"
}, },
"node_modules/gray-matter": {
"version": "4.0.3",
"resolved": "https://registry.npmjs.org/gray-matter/-/gray-matter-4.0.3.tgz",
"integrity": "sha512-5v6yZd4JK3eMI3FqqCouswVqwugaA9r4dNZB1wwcmrD02QkV5H0y7XBQW8QwQqEaZY1pM9aqORSORhJRdNK44Q==",
"license": "MIT",
"dependencies": {
"js-yaml": "^3.13.1",
"kind-of": "^6.0.2",
"section-matter": "^1.0.0",
"strip-bom-string": "^1.0.0"
},
"engines": {
"node": ">=6.0"
}
},
"node_modules/gray-matter/node_modules/argparse": {
"version": "1.0.10",
"resolved": "https://registry.npmjs.org/argparse/-/argparse-1.0.10.tgz",
"integrity": "sha512-o5Roy6tNG4SL/FOkCAN6RzjiakZS25RLYFrcMttJqbdd8BWrnA+fGz57iN5Pb06pvBGvl5gQ0B48dJlslXvoTg==",
"license": "MIT",
"dependencies": {
"sprintf-js": "~1.0.2"
}
},
"node_modules/gray-matter/node_modules/js-yaml": {
"version": "3.15.0",
"resolved": "https://registry.npmjs.org/js-yaml/-/js-yaml-3.15.0.tgz",
"integrity": "sha512-ttBQIIQPDeLjpPOohtUdXuXUVoA2uIB6fEH9HyJ7234s5mBJ5wTx20njxplLZQgLaOfpmPQA7X2t5AX6tIPbog==",
"license": "MIT",
"dependencies": {
"argparse": "^1.0.7",
"esprima": "^4.0.0"
},
"bin": {
"js-yaml": "bin/js-yaml.js"
}
},
"node_modules/h3": { "node_modules/h3": {
"version": "1.15.11", "version": "1.15.11",
"resolved": "https://registry.npmjs.org/h3/-/h3-1.15.11.tgz", "resolved": "https://registry.npmjs.org/h3/-/h3-1.15.11.tgz",
...@@ -3282,6 +3400,32 @@ ...@@ -3282,6 +3400,32 @@
"integrity": "sha512-dTxcvPXqPvXBQpq5dUr6mEMJX4oIEFv6bwom3FDwKRDsuIjjJGANqhBuoAn9c1RQJIdAKav33ED65E2ys+87QQ==", "integrity": "sha512-dTxcvPXqPvXBQpq5dUr6mEMJX4oIEFv6bwom3FDwKRDsuIjjJGANqhBuoAn9c1RQJIdAKav33ED65E2ys+87QQ==",
"license": "BSD-2-Clause" "license": "BSD-2-Clause"
}, },
"node_modules/http-errors": {
"version": "2.0.1",
"resolved": "https://registry.npmjs.org/http-errors/-/http-errors-2.0.1.tgz",
"integrity": "sha512-4FbRdAX+bSdmo4AUFuS0WNiPz8NgFt+r8ThgNWmlrjQjt1Q7ZR9+zTlce2859x4KSXrwIsaeTqDoKQmtP8pLmQ==",
"license": "MIT",
"dependencies": {
"depd": "~2.0.0",
"inherits": "~2.0.4",
"setprototypeof": "~1.2.0",
"statuses": "~2.0.2",
"toidentifier": "~1.0.1"
},
"engines": {
"node": ">= 0.8"
},
"funding": {
"type": "opencollective",
"url": "https://opencollective.com/express"
}
},
"node_modules/inherits": {
"version": "2.0.4",
"resolved": "https://registry.npmjs.org/inherits/-/inherits-2.0.4.tgz",
"integrity": "sha512-k/vGaX4/Yla3WzyMCvTQOXYeIHvqOKtnqBduzTHpzpQZzAskKMhZ2K+EnBiSM9zGSoIFeMpXKxa4dYeZIQqewQ==",
"license": "ISC"
},
"node_modules/iron-webcrypto": { "node_modules/iron-webcrypto": {
"version": "1.2.1", "version": "1.2.1",
"resolved": "https://registry.npmjs.org/iron-webcrypto/-/iron-webcrypto-1.2.1.tgz", "resolved": "https://registry.npmjs.org/iron-webcrypto/-/iron-webcrypto-1.2.1.tgz",
...@@ -3306,6 +3450,15 @@ ...@@ -3306,6 +3450,15 @@
"url": "https://github.com/sponsors/sindresorhus" "url": "https://github.com/sponsors/sindresorhus"
} }
}, },
"node_modules/is-extendable": {
"version": "0.1.1",
"resolved": "https://registry.npmjs.org/is-extendable/-/is-extendable-0.1.1.tgz",
"integrity": "sha512-5BMULNob1vgFX6EjQw5izWDxrecWK9AM72rugNr0TFldMOi0fj6Jk+zeKIt0xGj4cEfQIJth4w3OKWOJ4f+AFw==",
"license": "MIT",
"engines": {
"node": ">=0.10.0"
}
},
"node_modules/is-fullwidth-code-point": { "node_modules/is-fullwidth-code-point": {
"version": "3.0.0", "version": "3.0.0",
"resolved": "https://registry.npmjs.org/is-fullwidth-code-point/-/is-fullwidth-code-point-3.0.0.tgz", "resolved": "https://registry.npmjs.org/is-fullwidth-code-point/-/is-fullwidth-code-point-3.0.0.tgz",
...@@ -3363,6 +3516,15 @@ ...@@ -3363,6 +3516,15 @@
"integrity": "sha512-HUgH65KyejrUFPvHFPbqOY0rsFip3Bo5wb4ngvdi1EpCYWUQDC5V+Y7mZws+DLkr4M//zQJoanu1SP+87Dv1oQ==", "integrity": "sha512-HUgH65KyejrUFPvHFPbqOY0rsFip3Bo5wb4ngvdi1EpCYWUQDC5V+Y7mZws+DLkr4M//zQJoanu1SP+87Dv1oQ==",
"license": "MIT" "license": "MIT"
}, },
"node_modules/kind-of": {
"version": "6.0.3",
"resolved": "https://registry.npmjs.org/kind-of/-/kind-of-6.0.3.tgz",
"integrity": "sha512-dcS1ul+9tmeD95T+x28/ehLgd9mENa3LsvDTtzm3vyBEO7RPptvAD+t44WVXaUjTBRcrpFeFlC8WCruUR456hw==",
"license": "MIT",
"engines": {
"node": ">=0.10.0"
}
},
"node_modules/kleur": { "node_modules/kleur": {
"version": "4.1.5", "version": "4.1.5",
"resolved": "https://registry.npmjs.org/kleur/-/kleur-4.1.5.tgz", "resolved": "https://registry.npmjs.org/kleur/-/kleur-4.1.5.tgz",
...@@ -3663,6 +3825,18 @@ ...@@ -3663,6 +3825,18 @@
"source-map-js": "^1.2.1" "source-map-js": "^1.2.1"
} }
}, },
"node_modules/marked": {
"version": "14.1.4",
"resolved": "https://registry.npmjs.org/marked/-/marked-14.1.4.tgz",
"integrity": "sha512-vkVZ8ONmUdPnjCKc5uTRvmkRbx4EAi2OkTOXmfTDhZz3OFqMNBM1oTTWwTr4HY4uAEojhzPf+Fy8F1DWa3Sndg==",
"license": "MIT",
"bin": {
"marked": "bin/marked.js"
},
"engines": {
"node": ">= 18"
}
},
"node_modules/mdast-util-to-hast": { "node_modules/mdast-util-to-hast": {
"version": "13.2.1", "version": "13.2.1",
"resolved": "https://registry.npmjs.org/mdast-util-to-hast/-/mdast-util-to-hast-13.2.1.tgz", "resolved": "https://registry.npmjs.org/mdast-util-to-hast/-/mdast-util-to-hast-13.2.1.tgz",
...@@ -3898,6 +4072,18 @@ ...@@ -3898,6 +4072,18 @@
"integrity": "sha512-RdR9FQrFwNBNXAr4GixM8YaRZRJ5PUWbKYbE5eOsrwAjJW0q2REGcf79oYPsLyskQCZG1PLN+S/K1V00joZAoQ==", "integrity": "sha512-RdR9FQrFwNBNXAr4GixM8YaRZRJ5PUWbKYbE5eOsrwAjJW0q2REGcf79oYPsLyskQCZG1PLN+S/K1V00joZAoQ==",
"license": "MIT" "license": "MIT"
}, },
"node_modules/on-finished": {
"version": "2.4.1",
"resolved": "https://registry.npmjs.org/on-finished/-/on-finished-2.4.1.tgz",
"integrity": "sha512-oVlzkg3ENAhCk2zdv7IJwd/QUD4z2RxRwpkcGY8psCVcCYZNq4wYnVWALHM+brtuJjePWiYF/ClmuDr8Ch5+kg==",
"license": "MIT",
"dependencies": {
"ee-first": "1.1.1"
},
"engines": {
"node": ">= 0.8"
}
},
"node_modules/oniguruma-parser": { "node_modules/oniguruma-parser": {
"version": "0.12.2", "version": "0.12.2",
"resolved": "https://registry.npmjs.org/oniguruma-parser/-/oniguruma-parser-0.12.2.tgz", "resolved": "https://registry.npmjs.org/oniguruma-parser/-/oniguruma-parser-0.12.2.tgz",
...@@ -4085,6 +4271,15 @@ ...@@ -4085,6 +4271,15 @@
"integrity": "sha512-b484I/7b8rDEdSDKckSSBA8knMpcdsXudlE/LNL639wFoHKwLbEkQFZHWEYwDC0wa0FKUcCY+GAF73Z7wxNVFA==", "integrity": "sha512-b484I/7b8rDEdSDKckSSBA8knMpcdsXudlE/LNL639wFoHKwLbEkQFZHWEYwDC0wa0FKUcCY+GAF73Z7wxNVFA==",
"license": "MIT" "license": "MIT"
}, },
"node_modules/range-parser": {
"version": "1.2.1",
"resolved": "https://registry.npmjs.org/range-parser/-/range-parser-1.2.1.tgz",
"integrity": "sha512-Hrgsx+orqoygnmhFbKaHE6c296J+HTAQXoxEF6gNupROmmGJRoyzfG3ccAveqCBrwr/2yxQ5BVd/GTl5agOwSg==",
"license": "MIT",
"engines": {
"node": ">= 0.6"
}
},
"node_modules/readdirp": { "node_modules/readdirp": {
"version": "4.1.2", "version": "4.1.2",
"resolved": "https://registry.npmjs.org/readdirp/-/readdirp-4.1.2.tgz", "resolved": "https://registry.npmjs.org/readdirp/-/readdirp-4.1.2.tgz",
...@@ -4239,6 +4434,19 @@ ...@@ -4239,6 +4434,19 @@
"node": ">=11.0.0" "node": ">=11.0.0"
} }
}, },
"node_modules/section-matter": {
"version": "1.0.0",
"resolved": "https://registry.npmjs.org/section-matter/-/section-matter-1.0.0.tgz",
"integrity": "sha512-vfD3pmTzGpufjScBh50YHKzEu2lxBWhVEHsNGoEXmCmn2hKGfeNLYMzCJpe8cD7gqX7TJluOVpBkAequ6dgMmA==",
"license": "MIT",
"dependencies": {
"extend-shallow": "^2.0.1",
"kind-of": "^6.0.0"
},
"engines": {
"node": ">=4"
}
},
"node_modules/semver": { "node_modules/semver": {
"version": "7.8.5", "version": "7.8.5",
"resolved": "https://registry.npmjs.org/semver/-/semver-7.8.5.tgz", "resolved": "https://registry.npmjs.org/semver/-/semver-7.8.5.tgz",
...@@ -4251,6 +4459,101 @@ ...@@ -4251,6 +4459,101 @@
"node": ">=10" "node": ">=10"
} }
}, },
"node_modules/send": {
"version": "1.2.1",
"resolved": "https://registry.npmjs.org/send/-/send-1.2.1.tgz",
"integrity": "sha512-1gnZf7DFcoIcajTjTwjwuDjzuz4PPcY2StKPlsGAQ1+YH20IRVrBaXSWmdjowTJ6u8Rc01PoYOGHXfP1mYcZNQ==",
"license": "MIT",
"dependencies": {
"debug": "^4.4.3",
"encodeurl": "^2.0.0",
"escape-html": "^1.0.3",
"etag": "^1.8.1",
"fresh": "^2.0.0",
"http-errors": "^2.0.1",
"mime-types": "^3.0.2",
"ms": "^2.1.3",
"on-finished": "^2.4.1",
"range-parser": "^1.2.1",
"statuses": "^2.0.2"
},
"engines": {
"node": ">= 18"
},
"funding": {
"type": "opencollective",
"url": "https://opencollective.com/express"
}
},
"node_modules/send/node_modules/debug": {
"version": "4.4.3",
"resolved": "https://registry.npmjs.org/debug/-/debug-4.4.3.tgz",
"integrity": "sha512-RGwwWnwQvkVfavKVt22FGLw+xYSdzARwm0ru6DhTVA3umU5hZc28V3kO4stgYryrTlLpuvgI9GiijltAjNbcqA==",
"license": "MIT",
"dependencies": {
"ms": "^2.1.3"
},
"engines": {
"node": ">=6.0"
},
"peerDependenciesMeta": {
"supports-color": {
"optional": true
}
}
},
"node_modules/send/node_modules/fresh": {
"version": "2.0.0",
"resolved": "https://registry.npmjs.org/fresh/-/fresh-2.0.0.tgz",
"integrity": "sha512-Rx/WycZ60HOaqLKAi6cHRKKI7zxWbJ31MhntmtwMoaTeF7XFH9hhBp8vITaMidfljRQ6eYWCKkaTK+ykVJHP2A==",
"license": "MIT",
"engines": {
"node": ">= 0.8"
}
},
"node_modules/send/node_modules/mime-db": {
"version": "1.54.0",
"resolved": "https://registry.npmjs.org/mime-db/-/mime-db-1.54.0.tgz",
"integrity": "sha512-aU5EJuIN2WDemCcAp2vFBfp/m4EAhWJnUNSSw0ixs7/kXbd6Pg64EmwJkNdFhB8aWt1sH2CTXrLxo/iAGV3oPQ==",
"license": "MIT",
"engines": {
"node": ">= 0.6"
}
},
"node_modules/send/node_modules/mime-types": {
"version": "3.0.2",
"resolved": "https://registry.npmjs.org/mime-types/-/mime-types-3.0.2.tgz",
"integrity": "sha512-Lbgzdk0h4juoQ9fCKXW4by0UJqj+nOOrI9MJ1sSj4nI8aI2eo1qmvQEie4VD1glsS250n15LsWsYtCugiStS5A==",
"license": "MIT",
"dependencies": {
"mime-db": "^1.54.0"
},
"engines": {
"node": ">=18"
},
"funding": {
"type": "opencollective",
"url": "https://opencollective.com/express"
}
},
"node_modules/send/node_modules/ms": {
"version": "2.1.3",
"resolved": "https://registry.npmjs.org/ms/-/ms-2.1.3.tgz",
"integrity": "sha512-6FlzubTLZG3J2a/NVCAleEhjzq5oxgHyaCU9yYXvcLsvoVaHJq/s5xXI6/XXP6tz7R9xAOtHnSO/tXtF3WRTlA==",
"license": "MIT"
},
"node_modules/server-destroy": {
"version": "1.0.1",
"resolved": "https://registry.npmjs.org/server-destroy/-/server-destroy-1.0.1.tgz",
"integrity": "sha512-rb+9B5YBIEzYcD6x2VKidaa+cqYBJQKnU4oe4E3ANwRRN56yk/ua1YCJT1n21NTS8w6CcOclAKNP3PhdCXKYtQ==",
"license": "ISC"
},
"node_modules/setprototypeof": {
"version": "1.2.0",
"resolved": "https://registry.npmjs.org/setprototypeof/-/setprototypeof-1.2.0.tgz",
"integrity": "sha512-E5LDX7Wrp85Kil5bhZv46j8jOeboKq5JMmYM3gVGdGH8xFpPWXUMsNrlODCrkoxMEeNi/XZIwuRvY4XNwYMJpw==",
"license": "ISC"
},
"node_modules/sharp": { "node_modules/sharp": {
"version": "0.35.3", "version": "0.35.3",
"resolved": "https://registry.npmjs.org/sharp/-/sharp-0.35.3.tgz", "resolved": "https://registry.npmjs.org/sharp/-/sharp-0.35.3.tgz",
...@@ -4376,6 +4679,21 @@ ...@@ -4376,6 +4679,21 @@
"url": "https://github.com/sponsors/wooorm" "url": "https://github.com/sponsors/wooorm"
} }
}, },
"node_modules/sprintf-js": {
"version": "1.0.3",
"resolved": "https://registry.npmjs.org/sprintf-js/-/sprintf-js-1.0.3.tgz",
"integrity": "sha512-D9cPgkvLlV3t3IzL0D0YLvGA9Ahk4PcvVwUbN0dSGr1aP0Nrt4AEnTUbuGvquEC0mA64Gqt1fzirlRs5ibXx8g==",
"license": "BSD-3-Clause"
},
"node_modules/statuses": {
"version": "2.0.2",
"resolved": "https://registry.npmjs.org/statuses/-/statuses-2.0.2.tgz",
"integrity": "sha512-DvEy55V3DB7uknRo+4iOGT5fP1slR8wQohVdknigZPMpMstaKJQWhwiYBACJE3Ul2pTnATihhBYnRhZQHGBiRw==",
"license": "MIT",
"engines": {
"node": ">= 0.8"
}
},
"node_modules/stream-replace-string": { "node_modules/stream-replace-string": {
"version": "2.0.0", "version": "2.0.0",
"resolved": "https://registry.npmjs.org/stream-replace-string/-/stream-replace-string-2.0.0.tgz", "resolved": "https://registry.npmjs.org/stream-replace-string/-/stream-replace-string-2.0.0.tgz",
...@@ -4424,6 +4742,15 @@ ...@@ -4424,6 +4742,15 @@
"node": ">=8" "node": ">=8"
} }
}, },
"node_modules/strip-bom-string": {
"version": "1.0.0",
"resolved": "https://registry.npmjs.org/strip-bom-string/-/strip-bom-string-1.0.0.tgz",
"integrity": "sha512-uCC2VHvQRYu+lMh4My/sFNmF2klFymLX1wHJeXnbEJERpV/ZsVuonzerjfrGpIGF7LBVa1O7i9kjiWvJiFck8g==",
"license": "MIT",
"engines": {
"node": ">=0.10.0"
}
},
"node_modules/svgo": { "node_modules/svgo": {
"version": "4.0.2", "version": "4.0.2",
"resolved": "https://registry.npmjs.org/svgo/-/svgo-4.0.2.tgz", "resolved": "https://registry.npmjs.org/svgo/-/svgo-4.0.2.tgz",
...@@ -4489,6 +4816,15 @@ ...@@ -4489,6 +4816,15 @@
"url": "https://github.com/sponsors/SuperchupuDev" "url": "https://github.com/sponsors/SuperchupuDev"
} }
}, },
"node_modules/toidentifier": {
"version": "1.0.1",
"resolved": "https://registry.npmjs.org/toidentifier/-/toidentifier-1.0.1.tgz",
"integrity": "sha512-o5sSPKEkg/DIQNmH43V0/uerLrpzVedkUh8tGNvaeXpfpuwjKenlSox/2O/BTlZUtEe+JG7s5YhEz608PlAHRA==",
"license": "MIT",
"engines": {
"node": ">=0.6"
}
},
"node_modules/trim-lines": { "node_modules/trim-lines": {
"version": "3.0.1", "version": "3.0.1",
"resolved": "https://registry.npmjs.org/trim-lines/-/trim-lines-3.0.1.tgz", "resolved": "https://registry.npmjs.org/trim-lines/-/trim-lines-3.0.1.tgz",
......
...@@ -4,14 +4,22 @@ ...@@ -4,14 +4,22 @@
"version": "1.0.0", "version": "1.0.0",
"private": true, "private": true,
"scripts": { "scripts": {
"dev": "astro dev", "dev": "node --env-file=.env ./node_modules/astro/bin/astro.mjs dev",
"build": "astro check && astro build", "build": "node scripts/build-site.mjs",
"build:inside-lock": "node scripts/build-site.mjs --inside-lock",
"build:astro": "astro check && astro build",
"preview": "astro preview", "preview": "astro preview",
"check": "astro check" "check": "astro check",
"start": "node --env-file=.env server.mjs",
"admin": "npm start",
"serve": "npm run build && npm start"
}, },
"dependencies": { "dependencies": {
"@astrojs/node": "^11.0.2",
"@astrojs/sitemap": "^3.7.3", "@astrojs/sitemap": "^3.7.3",
"astro": "^7.1.3" "astro": "^7.1.3",
"gray-matter": "^4.0.3",
"marked": "^14.1.4"
}, },
"devDependencies": { "devDependencies": {
"@astrojs/check": "^0.9.6", "@astrojs/check": "^0.9.6",
......
const $ = (selector) => document.querySelector(selector);
const API_BASE = "/api/cms";
let categories = [];
let editingSlug = null;
let editingStatus = "new-unsaved";
let dirty = false;
let previewTimer = null;
let previewRequest = 0;
async function api(path, options = {}) {
const endpoint = path.startsWith("/") ? path : `/${path}`;
const response = await fetch(`${API_BASE}${endpoint}`, {
headers: { "Content-Type": "application/json" },
...options,
body: options.body ? JSON.stringify(options.body) : undefined,
});
let data = {};
try { data = await response.json(); } catch {}
if (!response.ok) throw new Error(data.error || `请求失败(${response.status})`);
return data;
}
const show = (selector) => $(selector).classList.remove("hidden");
const hide = (selector) => $(selector).classList.add("hidden");
async function boot() {
const session = await api("/session").catch(() => ({ authed: false }));
if (session.authed) {
hide("#login"); show("#app");
await loadCategories();
loadArticles();
}
else { show("#login"); hide("#app"); }
}
$("#login-form").addEventListener("submit", async (event) => {
event.preventDefault();
$("#login-error").textContent = "";
try {
await api("/session", { method: "POST", body: { password: $("#password").value } });
$("#password").value = "";
hide("#login"); show("#app");
await loadCategories();
loadArticles();
} catch (error) { $("#login-error").textContent = error.message; }
});
$("#logout").addEventListener("click", async () => { await api("/session", { method: "DELETE" }); location.reload(); });
const statusMap = {
"new-unsaved": ["尚未保存", "new-draft", "填写完成后先保存草稿,线上网站不会发生变化。"],
"new-draft": ["新建未发布", "new-draft", "这篇文章目前只有草稿版本,发布后才会出现在官网。"],
"edited-draft": ["修改未发布", "edited-draft", "草稿已经保存,官网仍在展示上一次发布的版本。"],
live: ["已上线", "live", "当前编辑内容与官网展示的版本一致。"],
};
function applyStatus(element, status) {
const [label, className] = statusMap[status] || statusMap["new-draft"];
element.className = `status ${className}`;
element.textContent = label;
}
async function loadArticles() {
const articles = await api("/articles").catch((error) => { alert(error.message); return []; });
const list = $("#article-list");
list.innerHTML = "";
const pending = articles.filter((item) => item.publishStatus !== "live").length;
$("#pending-badge").textContent = `${pending} 篇草稿待发布`;
$("#pending-badge").classList.toggle("hidden", pending === 0);
if (!articles.length) { list.innerHTML = '<div class="empty">还没有文章,点击“新建文章”开始。</div>'; return; }
for (const article of articles) {
const card = document.createElement("article");
card.className = "article-row";
card.innerHTML = '<div class="article-summary"><h2></h2><p><span class="category"></span><span class="updated"></span><span class="status"></span></p></div><button class="ghost small edit-button">编辑</button>';
card.querySelector("h2").textContent = article.title;
card.querySelector(".category").textContent = article.category;
card.querySelector(".updated").textContent = `更新于 ${article.updated}`;
applyStatus(card.querySelector(".status"), article.publishStatus);
card.querySelector(".edit-button").onclick = () => openEditor(article.slug);
list.append(card);
}
}
function fillCategories(selected) {
const current = selected || $("#category").value || categories[0] || "";
const options = $("#category-options");
options.innerHTML = "";
categories.forEach((name) => {
const option = document.createElement("button");
option.type = "button";
option.className = "select-option";
option.dataset.value = name;
option.setAttribute("role", "option");
option.setAttribute("aria-selected", String(name === current));
option.innerHTML = '<span></span><span class="option-check" aria-hidden="true">✓</span>';
option.querySelector("span").textContent = name;
option.addEventListener("click", () => {
selectCategory(name, true);
closeCategoryMenu();
});
options.append(option);
});
selectCategory(categories.includes(current) ? current : categories[0] || "", false);
}
function selectCategory(name, markDirty) {
$("#category").value = name;
$("#category-value").textContent = name || "请选择分类";
$("#category-options").querySelectorAll(".select-option").forEach((option) => {
option.setAttribute("aria-selected", String(option.dataset.value === name));
});
if (markDirty) dirty = true;
}
function closeCategoryMenu() {
$("#category-menu").classList.add("hidden");
$("#category-trigger").setAttribute("aria-expanded", "false");
$("#category-select").classList.remove("open");
}
function toggleCategoryMenu() {
const opening = $("#category-menu").classList.contains("hidden");
if (!opening) return closeCategoryMenu();
$("#category-menu").classList.remove("hidden");
$("#category-trigger").setAttribute("aria-expanded", "true");
$("#category-select").classList.add("open");
$("#category-error").textContent = "";
}
$("#category-trigger").addEventListener("click", (event) => { event.stopPropagation(); toggleCategoryMenu(); });
$("#category-menu").addEventListener("click", (event) => event.stopPropagation());
document.addEventListener("click", closeCategoryMenu);
document.addEventListener("keydown", (event) => { if (event.key === "Escape") closeCategoryMenu(); });
async function createCategory() {
const input = $("#new-category");
const name = input.value.trim();
$("#category-error").textContent = "";
try {
const result = await api("/categories", { method: "POST", body: { name } });
categories = result.categories;
input.value = "";
fillCategories(result.category);
dirty = true;
closeCategoryMenu();
if (!$("#category-modal").classList.contains("hidden")) await loadCategoryManager();
} catch (error) { $("#category-error").textContent = error.message; }
}
$("#add-category").addEventListener("click", createCategory);
$("#new-category").addEventListener("keydown", (event) => {
if (event.key !== "Enter") return;
event.preventDefault();
createCategory();
});
async function loadCategories() {
const result = await api("/categories");
categories = result.categories;
fillCategories($("#category").value);
return result;
}
async function loadCategoryManager() {
const result = await loadCategories();
renderCategoryManager(result.stats || []);
}
function clearCategoryPanels() {
$("#category-manager-list").querySelectorAll(".category-inline-panel").forEach((panel) => panel.remove());
}
function categoryPanel(row, text) {
clearCategoryPanels();
const panel = document.createElement("div");
panel.className = "category-inline-panel";
const note = document.createElement("p");
note.textContent = text;
panel.append(note);
row.append(panel);
return panel;
}
async function runCategoryBuild(action, method, body) {
$("#manager-category-error").textContent = "";
try {
await triggerBuild("/categories", { action, method, body });
await loadCategoryManager();
await loadArticles();
} catch (error) {
$("#manager-category-error").textContent = error.message;
await loadCategoryManager().catch(() => {});
}
}
function showRenameCategory(row, stat) {
const panel = categoryPanel(row, `重命名后,${stat.count} 篇文章会同步更新分类。`);
const form = document.createElement("div");
form.className = "category-rename-form";
const input = document.createElement("input");
input.maxLength = 20;
input.value = stat.name;
input.setAttribute("aria-label", `重命名 ${stat.name}`);
const save = document.createElement("button");
save.type = "button";
save.className = "primary";
save.textContent = "保存名称";
const cancel = document.createElement("button");
cancel.type = "button";
cancel.className = "ghost";
cancel.textContent = "取消";
save.onclick = () => {
const name = input.value.trim();
if (!name || name === stat.name) return clearCategoryPanels();
runCategoryBuild("更新分类", "PATCH", { current: stat.name, name });
};
cancel.onclick = clearCategoryPanels;
input.addEventListener("keydown", (event) => {
if (event.key === "Enter") { event.preventDefault(); save.click(); }
if (event.key === "Escape") clearCategoryPanels();
});
form.append(input, save, cancel);
panel.append(form);
input.focus();
input.select();
}
function showDeleteCategory(row, stat) {
const panel = categoryPanel(
row,
stat.count ? `该分类下有 ${stat.count} 篇文章,请选择删除后要迁移到的分类。` : "该分类下没有文章,可以直接删除。",
);
const actions = document.createElement("div");
actions.className = stat.count ? "replacement-options" : "category-inline-actions";
const choices = stat.count ? categories.filter((name) => name !== stat.name) : [""];
choices.forEach((replacement) => {
const button = document.createElement("button");
button.type = "button";
button.className = stat.count ? "" : "confirm-danger";
button.textContent = stat.count ? `迁移到“${replacement}”并删除` : "确认删除分类";
button.onclick = () => runCategoryBuild("删除分类", "DELETE", { name: stat.name, replacement });
actions.append(button);
});
const cancel = document.createElement("button");
cancel.type = "button";
cancel.className = "ghost";
cancel.textContent = "取消";
cancel.onclick = clearCategoryPanels;
actions.append(cancel);
panel.append(actions);
}
function renderCategoryManager(stats) {
const list = $("#category-manager-list");
list.innerHTML = "";
stats.forEach((stat) => {
const row = document.createElement("div");
row.className = "category-manager-row";
const main = document.createElement("div");
main.className = "category-row-main";
const name = document.createElement("div");
name.className = "category-row-name";
const strong = document.createElement("strong");
strong.textContent = stat.name;
const count = document.createElement("span");
count.textContent = stat.count ? `${stat.count} 篇文章` : "暂无文章";
name.append(strong, count);
const actions = document.createElement("div");
actions.className = "category-row-actions";
const rename = document.createElement("button");
rename.type = "button";
rename.className = "ghost";
rename.textContent = "重命名";
rename.onclick = () => showRenameCategory(row, stat);
const remove = document.createElement("button");
remove.type = "button";
remove.className = "ghost danger";
remove.textContent = "删除";
remove.disabled = categories.length <= 1;
remove.title = remove.disabled ? "至少需要保留一个分类" : "删除分类";
remove.onclick = () => showDeleteCategory(row, stat);
actions.append(rename, remove);
main.append(name, actions);
row.append(main);
list.append(row);
});
}
async function openCategoryManager() {
$("#manager-category-error").textContent = "";
show("#category-modal");
try { await loadCategoryManager(); }
catch (error) { $("#manager-category-error").textContent = error.message; }
}
$("#manage-categories").addEventListener("click", openCategoryManager);
$("#close-category-modal").addEventListener("click", () => hide("#category-modal"));
$("#manager-add-category").addEventListener("click", async () => {
const input = $("#manager-new-category");
$("#manager-category-error").textContent = "";
try {
await api("/categories", { method: "POST", body: { name: input.value.trim() } });
input.value = "";
await loadCategoryManager();
} catch (error) { $("#manager-category-error").textContent = error.message; }
});
$("#manager-new-category").addEventListener("keydown", (event) => {
if (event.key === "Enter") { event.preventDefault(); $("#manager-add-category").click(); }
});
function setView(editing) {
$("#list-view").classList.toggle("hidden", editing);
$("#edit-view").classList.toggle("hidden", !editing);
}
function setEditorStatus(status) {
editingStatus = status;
applyStatus($("#editor-status"), status);
$("#version-note").textContent = statusMap[status]?.[2] || "";
const persisted = status !== "new-unsaved";
$("#more-actions").classList.toggle("hidden", !persisted);
$("#more-actions").open = false;
$("#discard").classList.toggle("hidden", status !== "edited-draft");
$("#unpublish").classList.toggle("hidden", !["live", "edited-draft"].includes(status));
$("#delete-article").classList.toggle("hidden", !persisted);
}
async function openEditor(slug) {
editingSlug = slug;
dirty = false;
fillCategories();
$("#preview").innerHTML = "";
$("#message").textContent = "";
$("#upload-status").textContent = "";
if (slug) {
const article = await api(`/articles/${slug}`);
$("#edit-heading").textContent = "编辑文章";
$("#title").value = article.title;
fillCategories(article.category);
$("#body").value = article.body;
setEditorStatus(article.publishStatus);
} else {
$("#edit-heading").textContent = "新建文章";
$("#title").value = "";
$("#body").value = "";
setEditorStatus("new-unsaved");
}
setView(true);
schedulePreview(0);
$("#title").focus();
}
$("#new-article").addEventListener("click", () => openEditor(null));
$("#back").addEventListener("click", () => {
if (dirty && !confirm("还有未保存的内容,确定返回文章列表吗?")) return;
setView(false);
loadArticles();
});
function payload() {
return {
title: $("#title").value.trim(),
category: $("#category").value,
body: $("#body").value,
};
}
async function save() {
const result = editingSlug
? await api(`/articles/${editingSlug}`, { method: "PUT", body: payload() })
: await api("/articles", { method: "POST", body: payload() });
editingSlug = result.slug;
dirty = false;
setEditorStatus(result.publishStatus);
return result.slug;
}
$("#edit-form").addEventListener("submit", async (event) => {
event.preventDefault();
$("#message").textContent = "正在保存…";
try {
await save();
$("#message").textContent = editingStatus === "live" ? "内容与线上版本一致。" : "草稿已保存,线上版本没有改变。";
} catch (error) { $("#message").textContent = error.message; }
});
$("#publish").addEventListener("click", async () => {
$("#message").textContent = "正在保存草稿…";
try {
const slug = await save();
await triggerBuild(`/articles/${slug}/publish`);
setEditorStatus("live");
$("#message").textContent = "发布成功,官网已更新。";
} catch (error) { $("#message").textContent = error.message; }
});
$("#discard").addEventListener("click", async () => {
if (!editingSlug) return;
if (!confirm("确定放弃未发布的修改,恢复为当前线上版本吗?")) return;
try {
const result = await api(`/articles/${editingSlug}/draft`, { method: "DELETE" });
dirty = false;
if (result.removed) { setView(false); loadArticles(); }
else await openEditor(editingSlug);
} catch (error) { $("#message").textContent = error.message; }
});
$("#unpublish").addEventListener("click", async () => {
if (!editingSlug) return;
const detail = editingStatus === "edited-draft" ? "未发布的修改会继续保留为草稿。" : "文章内容会继续保留为草稿。";
if (!confirm(`确定将这篇文章从官网下架吗?${detail}`)) return;
$("#more-actions").open = false;
$("#message").textContent = "正在下架文章…";
try {
await triggerBuild(`/articles/${editingSlug}/unpublish`, { action: "下架" });
setEditorStatus("new-draft");
$("#message").textContent = "文章已下架,内容已保留为草稿。";
} catch (error) { $("#message").textContent = error.message; }
});
$("#delete-article").addEventListener("click", async () => {
if (!editingSlug) return;
const prompt = editingStatus === "new-draft"
? "确定彻底删除这篇草稿吗?删除后无法恢复。"
: "确定彻底删除这篇文章吗?线上版本和草稿都会删除,且无法恢复。";
if (!confirm(prompt)) return;
$("#more-actions").open = false;
$("#message").textContent = "正在删除文章…";
try {
await triggerBuild(`/articles/${editingSlug}`, { action: "删除", method: "DELETE" });
dirty = false;
editingSlug = null;
setView(false);
await loadArticles();
} catch (error) { $("#message").textContent = error.message; }
});
async function renderPreview() {
const body = $("#body").value.trim();
if (!body) { $("#preview").innerHTML = ""; return; }
const request = ++previewRequest;
try {
const result = await api("/preview", { method: "POST", body: { body } });
if (request === previewRequest) $("#preview").innerHTML = result.html;
} catch {
if (request === previewRequest) $("#preview").textContent = "预览暂时不可用";
}
}
function schedulePreview(delay = 350) {
clearTimeout(previewTimer);
previewTimer = setTimeout(renderPreview, delay);
}
$("#title").addEventListener("input", () => { dirty = true; });
$("#body").addEventListener("input", () => { dirty = true; schedulePreview(); });
$("#upload-button").addEventListener("click", () => $("#file").click());
$("#file").addEventListener("change", async (event) => {
const file = event.target.files?.[0];
event.target.value = "";
if (!file) return;
$("#upload-status").textContent = "上传中…";
try {
const dataUrl = await new Promise((resolve, reject) => {
const reader = new FileReader();
reader.onload = () => resolve(reader.result);
reader.onerror = reject;
reader.readAsDataURL(file);
});
const result = await api("/uploads", { method: "POST", body: { dataUrl } });
const textarea = $("#body");
const start = textarea.selectionStart;
const markdown = `\n![${file.name}](${result.url})\n`;
textarea.value = textarea.value.slice(0, start) + markdown + textarea.value.slice(textarea.selectionEnd);
textarea.dispatchEvent(new Event("input"));
$("#upload-status").textContent = "图片已插入";
} catch (error) { $("#upload-status").textContent = error.message; }
});
async function triggerBuild(endpoint, { action = "发布", method = "POST", body } = {}) {
show("#build-modal");
hide("#close-modal");
$("#build-title").textContent = `正在${action}…`;
$("#build-log").textContent = "系统正在更新官网,请稍候。";
try {
await api(endpoint, { method, body });
} catch (error) {
$("#build-title").textContent = `${action}失败`;
$("#build-log").textContent = error.message;
show("#close-modal");
throw error;
}
while (true) {
await new Promise((resolve) => setTimeout(resolve, 1000));
const state = await api("/build");
if (state.status === "building") continue;
$("#build-title").textContent = state.ok ? `${action}成功` : `${action}失败`;
$("#build-log").textContent = state.ok ? "静态页面已经生成,官网内容已更新。" : (state.log || `${action}失败,请联系技术人员。`);
show("#close-modal");
if (!state.ok) throw new Error(`${action}失败,原文章已恢复,请检查操作日志。`);
return;
}
}
$("#close-modal").addEventListener("click", () => hide("#build-modal"));
boot();
:root {
--primary: #16ae9c;
--primary-dark: #11897b;
--deep: #0e727c;
--light: #e4efea;
--bg: #f6f8f7;
--surface: #fff;
--text: #243532;
--muted: #6b7280;
--border: #d6e4de;
--danger: #c04444;
font-family: "PingFang SC", "Microsoft YaHei", system-ui, sans-serif;
}
* { box-sizing: border-box; }
body { margin: 0; color: var(--text); background: var(--bg); }
.hidden { display: none !important; }
button, input, textarea, select { font: inherit; }
button, .button { min-height: 40px; padding: 0 17px; display: inline-flex; align-items: center; justify-content: center; border: 0; border-radius: 999px; cursor: pointer; text-decoration: none; transition: .18s ease; }
.primary { color: white; background: var(--primary-dark); }
.primary:hover { background: var(--deep); transform: translateY(-1px); }
.ghost { color: var(--primary-dark); background: transparent; border: 1px solid var(--border); }
.ghost:hover { border-color: var(--primary); }
.small { min-height: 34px; padding-inline: 13px; font-size: 12px; }
.error { min-height: 20px; color: var(--danger); font-size: 13px; }
.login { min-height: 100vh; padding: 24px; display: grid; place-items: center; background: linear-gradient(135deg, #faf8f4, var(--light)); }
.login-card { width: min(420px, 100%); padding: 42px; display: grid; gap: 16px; background: white; border: 1px solid var(--border); border-radius: 22px; box-shadow: 0 24px 60px rgba(36,79,72,.12); }
.brand-mark { color: var(--primary); font-size: 14px; font-weight: 700; letter-spacing: .18em; }
.login-card h1 { margin: 0; font-size: 30px; }
.login-card p { margin: -8px 0 4px; color: var(--muted); }
.login-card label, .field-panel label, .field-label { display: grid; gap: 7px; color: var(--muted); font-size: 13px; }
input, textarea, select { width: 100%; padding: 11px 13px; color: var(--text); background: white; border: 1px solid var(--border); border-radius: 9px; }
input:focus, textarea:focus, select:focus { outline: 2px solid rgba(22,174,156,.14); border-color: var(--primary); }
.topbar { min-height: 68px; padding: 12px 28px; position: sticky; top: 0; z-index: 10; display: flex; align-items: center; justify-content: space-between; gap: 22px; color: white; background: #101413; }
.topbar > div:first-child { display: flex; align-items: center; gap: 13px; }
.topbar strong { color: var(--primary); font-size: 19px; }
.topbar span { font-size: 13px; opacity: .76; }
.top-actions { display: flex; align-items: center; gap: 9px; }
.topbar .ghost { color: white; border-color: rgba(255,255,255,.24); }
.pending-badge { padding: 5px 10px; color: #ffe49b; background: rgba(255,206,94,.12); border: 1px solid rgba(255,206,94,.3); border-radius: 999px; }
.view { width: min(1120px, calc(100% - 40px)); margin: 0 auto; padding: 44px 0 70px; }
.view-head { margin-bottom: 26px; display: flex; align-items: center; justify-content: space-between; gap: 18px; }
.view-head p { margin: 0 0 5px; color: var(--primary-dark); font-size: 11px; font-weight: 700; letter-spacing: .16em; }
.view-head h1 { margin: 0; font-size: 30px; }
.view-actions { display: flex; gap: 9px; }
.article-list { display: grid; gap: 10px; }
.article-row { padding: 18px 20px; display: flex; align-items: center; justify-content: space-between; gap: 20px; background: white; border: 1px solid var(--border); border-radius: 14px; }
.article-row h2 { margin: 0 0 8px; font-size: 17px; }
.article-row p { margin: 0; display: flex; flex-wrap: wrap; gap: 8px 13px; align-items: center; color: var(--muted); font-size: 12px; }
.article-row code { color: #8d9995; }
.status { padding: 2px 8px; border-radius: 999px; }
.status.live { color: #188367; background: #e2f6ef; }
.status.new-draft { color: #916300; background: #fff2c7; }
.status.edited-draft { color: #9c4c22; background: #ffeadc; }
.row-actions { display: flex; gap: 8px; }
.empty { padding: 70px; color: var(--muted); text-align: center; background: white; border: 1px dashed var(--border); border-radius: 14px; }
#edit-form { display: grid; gap: 18px; }
.field-panel, .editor-panel { padding: 24px; background: white; border: 1px solid var(--border); border-radius: 16px; }
.field-panel { display: grid; gap: 15px; }
.field-panel small { font-weight: 400; opacity: .8; }
.field-row { display: grid; grid-template-columns: 1fr 1fr; gap: 15px; }
.custom-select { position: relative; }
.select-trigger { width: 100%; padding: 0 13px; justify-content: space-between; color: var(--text); background: white; border: 1px solid var(--border); border-radius: 9px; text-align: left; }
.select-trigger:hover, .custom-select.open .select-trigger { border-color: var(--primary); }
.custom-select.open .select-trigger { outline: 2px solid rgba(22,174,156,.14); }
.select-chevron { color: var(--muted); transition: transform .18s ease; }
.custom-select.open .select-chevron { transform: rotate(180deg); }
.select-menu { width: 100%; margin-top: 7px; position: absolute; z-index: 20; overflow: hidden; background: white; border: 1px solid var(--border); border-radius: 12px; box-shadow: 0 18px 45px rgba(36,79,72,.16); }
.select-options { max-height: 220px; padding: 7px; display: grid; gap: 2px; overflow-y: auto; }
.select-option { width: 100%; min-height: 40px; padding: 0 11px; justify-content: space-between; color: var(--text); background: transparent; border-radius: 8px; }
.select-option:hover { background: #f0f7f4; }
.select-option[aria-selected="true"] { color: var(--primary-dark); background: #e7f5f1; font-weight: 600; }
.option-check { opacity: 0; color: var(--primary-dark); }
.select-option[aria-selected="true"] .option-check { opacity: 1; }
.category-create { padding: 12px; background: #f7faf9; border-top: 1px solid var(--border); }
.category-create > span { display: block; margin-bottom: 8px; color: var(--text); font-weight: 600; }
.category-create > div { display: flex; gap: 8px; }
.category-create input { min-width: 0; }
.category-create button { min-width: 68px; flex: 0 0 auto; white-space: nowrap; }
.category-create .error { min-height: 0; margin: 6px 2px 0; }
.editor-titlebar { align-items: flex-end; }
.editor-titlebar > div { display: grid; gap: 12px; }
.editor-titlebar > .status { margin-bottom: 4px; padding: 6px 12px; font-size: 13px; }
.back-button { min-height: auto; width: max-content; padding: 0; color: var(--muted); background: transparent; border-radius: 0; }
.back-button:hover { color: var(--primary-dark); }
.version-note { margin: -12px 0 18px; padding: 13px 16px; color: #52625e; background: #edf5f2; border: 1px solid var(--border); border-radius: 11px; font-size: 13px; }
.auto-meta { margin: 0; padding: 11px 13px; color: var(--muted); background: #f7faf9; border-radius: 9px; font-size: 12px; }
.editor-head { margin-bottom: 13px; display: flex; align-items: center; justify-content: space-between; gap: 15px; }
.editor-head > div { display: flex; align-items: center; gap: 9px; }
.editor-head small { color: var(--muted); font-size: 12px; font-weight: 400; }
#upload-status { color: var(--muted); font-size: 12px; }
.editor-grid { min-height: 480px; display: grid; grid-template-columns: 1fr 1fr; gap: 14px; }
#body { min-height: 480px; resize: vertical; font-family: inherit; font-size: 15px; line-height: 1.8; }
.preview { padding: 22px; overflow: auto; background: #fbfcfb; border: 1px solid var(--border); border-radius: 9px; line-height: 1.8; }
.preview:empty::before { content: "文章预览会显示在这里"; color: var(--muted); }
.preview h1, .preview h2, .preview h3 { color: var(--primary-dark); }
.preview img { max-width: 100%; }
.edit-actions { padding: 15px 18px; position: sticky; bottom: 14px; z-index: 5; display: flex; align-items: center; gap: 10px; background: rgba(255,255,255,.96); border: 1px solid var(--border); border-radius: 14px; box-shadow: 0 12px 32px rgba(36,79,72,.1); backdrop-filter: blur(10px); }
.save-button { background: white; }
.more-actions { position: relative; }
.more-actions summary { min-height: 40px; padding: 0 15px; display: flex; align-items: center; color: var(--muted); background: white; border: 1px solid var(--border); border-radius: 999px; cursor: pointer; font-size: 13px; list-style: none; }
.more-actions summary::-webkit-details-marker { display: none; }
.more-actions summary::after { content: "⌄"; margin-left: 7px; transition: transform .18s ease; }
.more-actions[open] summary::after { transform: rotate(180deg); }
.more-actions[open] summary { color: var(--primary-dark); border-color: var(--primary); }
.action-menu { min-width: 180px; padding: 7px; position: absolute; right: 0; bottom: calc(100% + 8px); display: grid; gap: 2px; background: white; border: 1px solid var(--border); border-radius: 11px; box-shadow: 0 14px 36px rgba(36,79,72,.16); }
.menu-action { width: 100%; min-height: 38px; padding: 0 11px; justify-content: flex-start; color: var(--text); background: transparent; border-radius: 7px; font-size: 13px; }
.menu-action:hover { background: #f1f6f4; }
.menu-action.danger { color: var(--danger); }
.menu-action.danger:hover { background: #fff0f0; }
#message { margin-left: 8px; color: var(--muted); font-size: 13px; }
.modal { position: fixed; inset: 0; z-index: 30; padding: 20px; display: grid; place-items: center; background: rgba(0,0,0,.6); }
.modal-card { width: min(780px, 100%); max-height: 82vh; background: white; border-radius: 16px; overflow: hidden; }
.modal-card > div { padding: 15px 18px; display: flex; align-items: center; justify-content: space-between; border-bottom: 1px solid var(--border); }
.category-manager { width: min(680px, 100%); }
.modal-card > .modal-head { padding: 18px 20px; }
.modal-head > div { display: grid; gap: 4px; }
.modal-head small { color: var(--muted); font-size: 12px; font-weight: 400; }
.modal-card > .category-manager-body { max-height: 68vh; padding: 20px; display: block; overflow-y: auto; border: 0; }
.manager-create { display: flex; gap: 9px; }
.manager-create input { min-width: 0; }
.manager-create button { flex: 0 0 auto; white-space: nowrap; }
.category-manager-list { margin-top: 8px; display: grid; gap: 8px; }
.category-manager-row { padding: 13px 14px; background: #f8faf9; border: 1px solid var(--border); border-radius: 11px; }
.category-row-main { display: flex; align-items: center; justify-content: space-between; gap: 16px; }
.category-row-name { min-width: 0; display: grid; gap: 3px; }
.category-row-name strong { overflow: hidden; text-overflow: ellipsis; white-space: nowrap; }
.category-row-name span { color: var(--muted); font-size: 12px; }
.category-row-actions { display: flex; gap: 5px; }
.category-row-actions button { min-height: 32px; padding-inline: 10px; font-size: 12px; }
.category-row-actions .danger { color: var(--danger); }
.category-row-actions button:disabled { cursor: not-allowed; opacity: .45; }
.category-inline-panel { margin-top: 11px; padding-top: 11px; display: grid; gap: 9px; border-top: 1px solid var(--border); }
.category-inline-panel p { margin: 0; color: var(--muted); font-size: 12px; }
.category-rename-form { display: flex; gap: 8px; }
.category-rename-form input { min-width: 0; }
.category-inline-actions, .replacement-options { display: flex; flex-wrap: wrap; gap: 7px; }
.category-inline-actions button, .replacement-options button { min-height: 32px; padding-inline: 11px; font-size: 12px; }
.confirm-danger { color: white; background: var(--danger); }
.replacement-options button { color: var(--primary-dark); background: white; border: 1px solid var(--border); }
.replacement-options button:hover { border-color: var(--primary); background: #edf7f4; }
.build-card { width: min(780px, 100%); }
#build-log { max-height: 62vh; margin: 0; padding: 18px; overflow: auto; color: var(--muted); background: #f7f9f8; white-space: pre-wrap; font-size: 12px; }
@media (max-width: 760px) {
.topbar, .view-head, .article-row { align-items: flex-start; flex-direction: column; }
.top-actions { width: 100%; flex-wrap: wrap; }
.view-actions { width: 100%; }
.view-actions button { flex: 1; }
.field-row, .editor-grid { grid-template-columns: 1fr; }
.view { width: min(100% - 28px, 1120px); padding-top: 28px; }
.row-actions { width: 100%; }
.edit-actions { flex-wrap: wrap; }
#message { width: 100%; margin: 4px 0 0; }
.login-card { padding: 30px 24px; }
.manager-create, .category-row-main, .category-rename-form { align-items: stretch; flex-direction: column; }
}
import { buildSiteAtomic, withSiteBuildLock } from "./site-build.mjs";
try {
const build = () => buildSiteAtomic({ onOutput: (text) => process.stdout.write(text) });
if (process.argv.includes("--inside-lock")) {
if (process.env.SUMEIQIAO_SITE_LOCK_HELD !== "1") throw new Error("build:inside-lock 只能在共享构建锁中运行");
await build();
} else {
await withSiteBuildLock(build);
}
} catch (error) {
console.error(error instanceof Error ? error.message : error);
process.exitCode = 1;
}
import { spawn } from "node:child_process";
import { withSiteBuildLock } from "./site-build.mjs";
const separator = process.argv.indexOf("--");
const command = separator >= 0 ? process.argv.slice(separator + 1) : [];
if (!command.length) {
console.error("用法:node scripts/run-with-site-lock.mjs -- <部署命令> [参数]");
process.exit(2);
}
await withSiteBuildLock(() => new Promise((resolve, reject) => {
const child = spawn(command[0], command.slice(1), {
stdio: "inherit",
env: { ...process.env, SUMEIQIAO_SITE_LOCK_HELD: "1" },
});
child.on("error", reject);
child.on("exit", (code, signal) => {
if (code === 0) resolve();
else reject(new Error(signal ? `部署命令被信号 ${signal} 终止` : `部署命令退出码:${code}`));
});
})).catch((error) => {
console.error(error instanceof Error ? error.message : error);
process.exitCode = 1;
});
export interface BuildOptions {
onOutput?: (text: string) => void;
}
export class SiteBuildLockBusyError extends Error {}
export function tryAcquireSiteBuildLock(): Promise<(() => Promise<void>) | null>;
export function withSiteBuildLock<T>(task: () => Promise<T>, options?: { timeoutMs?: number }): Promise<T>;
export function buildSiteAtomic(options?: BuildOptions): Promise<string>;
import crypto from "node:crypto";
import fs from "node:fs/promises";
import os from "node:os";
import path from "node:path";
import { spawn } from "node:child_process";
const ROOT = process.cwd();
const RUNTIME_DIR = path.join(ROOT, ".runtime");
const DEFAULT_LOCK = process.env.CMS_DATA_DIR
? path.join(path.resolve(process.env.CMS_DATA_DIR), ".site-build.lock")
: path.join(RUNTIME_DIR, "site-build.lock");
const LOCK_FILE = path.resolve(process.env.CMS_BUILD_LOCK || DEFAULT_LOCK);
const RECOVERY_LOCK_FILE = `${LOCK_FILE}.recovery`;
const ASTRO_BIN = path.join(ROOT, "node_modules", "astro", "bin", "astro.mjs");
const DIST_DIR = path.join(ROOT, "dist");
const MAX_LOG_LENGTH = 2 * 1024 * 1024;
export class SiteBuildLockBusyError extends Error {
constructor() {
super("网站正在部署或生成静态页面,请稍后重试");
this.name = "SiteBuildLockBusyError";
}
}
const delay = (milliseconds) => new Promise((resolve) => setTimeout(resolve, milliseconds));
async function fileExists(file) {
try { await fs.access(file); return true; } catch { return false; }
}
function processIsAlive(pid) {
if (!Number.isInteger(pid) || pid <= 0) return false;
try { process.kill(pid, 0); return true; } catch { return false; }
}
async function removeStaleLock() {
let recoveryHandle;
try {
recoveryHandle = await fs.open(RECOVERY_LOCK_FILE, "wx");
const raw = await fs.readFile(LOCK_FILE, "utf8");
const lock = JSON.parse(raw);
const sameHost = lock.hostname === os.hostname();
if (sameHost && !processIsAlive(Number(lock.pid))) {
await fs.unlink(LOCK_FILE);
return true;
}
} catch (error) {
if (error.code === "ENOENT") return true;
if (error.code === "EEXIST") return false;
} finally {
if (recoveryHandle) {
await recoveryHandle.close().catch(() => {});
await fs.unlink(RECOVERY_LOCK_FILE).catch(() => {});
}
}
return false;
}
async function acquireSiteBuildLock(timeoutMs = 15 * 60 * 1000) {
await fs.mkdir(path.dirname(LOCK_FILE), { recursive: true });
const started = Date.now();
const token = crypto.randomBytes(12).toString("hex");
while (true) {
try {
const handle = await fs.open(LOCK_FILE, "wx");
await handle.writeFile(JSON.stringify({ token, pid: process.pid, hostname: os.hostname(), startedAt: new Date().toISOString() }));
await handle.close();
return async () => {
try {
const current = JSON.parse(await fs.readFile(LOCK_FILE, "utf8"));
if (current.token === token) await fs.unlink(LOCK_FILE);
} catch (error) {
if (error.code !== "ENOENT") throw error;
}
};
} catch (error) {
if (error.code !== "EEXIST") throw error;
if (await removeStaleLock()) continue;
if (Date.now() - started >= timeoutMs) throw new SiteBuildLockBusyError();
await delay(300);
}
}
}
export async function tryAcquireSiteBuildLock() {
try {
return await acquireSiteBuildLock(0);
} catch (error) {
if (error instanceof SiteBuildLockBusyError) return null;
throw error;
}
}
export async function withSiteBuildLock(task, options = {}) {
const release = await acquireSiteBuildLock(options.timeoutMs);
try { return await task(); } finally { await release(); }
}
function runAstro(command, env, onOutput) {
return new Promise((resolve, reject) => {
const child = spawn(process.execPath, [ASTRO_BIN, command], { cwd: ROOT, env: { ...process.env, ...env } });
let log = "";
const append = (chunk) => {
const text = chunk.toString();
log = `${log}${text}`.slice(-MAX_LOG_LENGTH);
onOutput?.(text);
};
child.stdout.on("data", append);
child.stderr.on("data", append);
child.on("error", reject);
child.on("exit", (code) => code === 0 ? resolve(log) : reject(Object.assign(new Error(`astro ${command} 执行失败`), { log })));
});
}
export async function buildSiteAtomic(options = {}) {
await fs.mkdir(RUNTIME_DIR, { recursive: true });
const id = `${Date.now()}-${process.pid}-${crypto.randomBytes(4).toString("hex")}`;
const temporary = path.join(RUNTIME_DIR, `dist-${id}`);
const backup = path.join(RUNTIME_DIR, `dist-backup-${id}`);
let movedCurrent = false;
let log = "";
try {
log += await runAstro("check", {}, options.onOutput);
log += await runAstro("build", { SUMEIQIAO_BUILD_OUT_DIR: temporary }, options.onOutput);
if (await fileExists(DIST_DIR)) {
await fs.rename(DIST_DIR, backup);
movedCurrent = true;
}
try {
await fs.rename(temporary, DIST_DIR);
} catch (error) {
if (movedCurrent) await fs.rename(backup, DIST_DIR);
throw error;
}
if (movedCurrent) {
await fs.rm(backup, { recursive: true, force: true }).catch((error) => {
options.onOutput?.(`\n旧构建目录清理失败,可稍后手动清理:${error.message}\n`);
});
}
return log;
} catch (error) {
await fs.rm(temporary, { recursive: true, force: true });
if (movedCurrent && !await fileExists(DIST_DIR) && await fileExists(backup)) await fs.rename(backup, DIST_DIR);
if (error.log) error.log = `${log}${error.log}`.slice(-MAX_LOG_LENGTH);
else error.log = log;
throw error;
}
}
process.env.PORT ||= process.env.CMS_PORT || "8789";
await import("./dist/server/entry.mjs");
---
import { fmtDate, paginationWindow, type Article, type CategoryInfo } from "../lib/articles";
interface Props {
items: Article[];
categories: CategoryInfo[];
totalCount: number;
activeSlug: string | null;
currentPage: number;
lastPage: number;
basePath: string;
}
const { items, categories, totalCount, activeSlug, currentPage, lastPage, basePath } = Astro.props as Props;
const pageHref = (page: number) => page <= 1 ? `${basePath}/` : `${basePath}/page/${page}/`;
const pages = paginationWindow(currentPage, lastPage);
---
<nav class="article-tabs" aria-label="资讯分类">
<a class:list={["article-tab", { active: activeSlug === null }]} href="/articles/">全部 <span>{totalCount}</span></a>
{categories.map((category) => (
<a class:list={["article-tab", { active: activeSlug === category.slug }]} href={`/articles/topic/${category.slug}/`}>
{category.name} <span>{category.count}</span>
</a>
))}
</nav>
{items.length ? (
<div class="article-grid">
{items.map((item, index) => (
<article class="article-card" data-reveal>
<a href={`/articles/${item.id}/`} aria-label={`阅读:${item.data.title}`}>
<div class="article-card__meta">
<span>{item.data.category}</span><time datetime={fmtDate(item.data.date)}>{fmtDate(item.data.date)}</time>
</div>
<div class="article-card__index">{String((currentPage - 1) * 9 + index + 1).padStart(2, "0")}</div>
<h2>{item.data.title}</h2>
<p>{item.data.excerpt}</p>
<strong>阅读详情 <span>↗</span></strong>
</a>
</article>
))}
</div>
) : <p class="article-empty">该分类暂时还没有文章。</p>}
{lastPage > 1 && (
<nav class="article-pagination" aria-label="资讯分页">
{currentPage > 1 ? <a href={pageHref(currentPage - 1)} rel="prev">←</a> : <span aria-hidden="true">←</span>}
{pages.map((page) => page === 0
? <span class="gap">…</span>
: page === currentPage
? <span class="active" aria-current="page">{page}</span>
: <a href={pageHref(page)}>{page}</a>
)}
{currentPage < lastPage ? <a href={pageHref(currentPage + 1)} rel="next">→</a> : <span aria-hidden="true">→</span>}
</nav>
)}
---
import Base from "../layouts/Base.astro";
import Header from "./Header.astro";
import Footer from "./Footer.astro";
import ArticleListing from "./ArticleListing.astro";
import { site } from "../data/site";
import { PAGE_SIZE, type Article, type CategoryInfo } from "../lib/articles";
interface Props {
items: Article[];
categories: CategoryInfo[];
totalCount: number;
activeSlug: string | null;
activeName: string | null;
currentPage: number;
lastPage: number;
basePath: string;
}
const { items, categories, totalCount, activeSlug, activeName, currentPage, lastPage, basePath } = Astro.props as Props;
const heading = activeName ?? "健康资讯";
const pageSuffix = currentPage > 1 ? `|第${currentPage}页` : "";
const title = `${heading}${pageSuffix}|${site.brand.name}`;
const description = activeName
? `塑美俏${activeName}分类的健康管理文章与品牌资讯。`
: "塑美俏体龄管理、经络调理、健康科普与门店经营相关资讯。";
const pageUrl = new URL(`${basePath}${currentPage > 1 ? `/page/${currentPage}` : ""}/`, Astro.site).href;
const jsonLd = [
{
"@context": "https://schema.org",
"@type": "CollectionPage",
name: heading,
description,
url: pageUrl,
inLanguage: "zh-CN",
mainEntity: {
"@type": "ItemList",
itemListElement: items.map((item, index) => ({
"@type": "ListItem",
position: (currentPage - 1) * PAGE_SIZE + index + 1,
name: item.data.title,
url: new URL(`/articles/${item.id}/`, Astro.site).href,
})),
},
},
{
"@context": "https://schema.org",
"@type": "BreadcrumbList",
itemListElement: [
{ "@type": "ListItem", position: 1, name: "首页", item: Astro.site?.href },
{ "@type": "ListItem", position: 2, name: "健康资讯", item: new URL("/articles/", Astro.site).href },
...(activeName ? [{ "@type": "ListItem", position: 3, name: activeName, item: pageUrl }] : []),
],
},
];
---
<Base title={title} description={description} jsonLd={jsonLd}>
<Header />
<main id="main-content">
<section class="page-hero article-hero" data-word="JOURNAL">
<div class="container page-hero__inner" data-reveal>
<div class="breadcrumb"><a href="/">首页</a> / <a href="/articles/">健康资讯</a>{activeName && ` / ${activeName}`}</div>
<div class="eyebrow"><span></span>SUMEIQIAO JOURNAL</div>
<h1>{heading}</h1>
<p>{description}</p>
</div>
</section>
<section class="section-pad section-white">
<div class="container">
<ArticleListing {items} {categories} {totalCount} {activeSlug} {currentPage} {lastPage} {basePath} />
</div>
</section>
</main>
<Footer />
</Base>
...@@ -18,6 +18,7 @@ import { site } from "../data/site"; ...@@ -18,6 +18,7 @@ import { site } from "../data/site";
<h2>认识塑美俏</h2> <h2>认识塑美俏</h2>
<a href="/about/">品牌故事</a> <a href="/about/">品牌故事</a>
<a href="/services/">体龄管理</a> <a href="/services/">体龄管理</a>
<a href="/articles/">健康资讯</a>
<a href="/join/">加盟支持</a> <a href="/join/">加盟支持</a>
<a href="/faq/">常见问题</a> <a href="/faq/">常见问题</a>
</div> </div>
......
...@@ -164,6 +164,17 @@ export const site = { ...@@ -164,6 +164,17 @@ export const site = {
{ href: "/services/#wellness-conditioning", label: "亚健康调理" }, { href: "/services/#wellness-conditioning", label: "亚健康调理" },
], ],
}, },
{
href: "/articles/",
label: "健康资讯",
children: [
{ href: "/articles/", label: "全部资讯" },
{ href: "/articles/topic/body-age/", label: "体龄管理" },
{ href: "/articles/topic/meridian/", label: "经络调理" },
{ href: "/articles/topic/wellness/", label: "健康科普" },
{ href: "/articles/topic/store-growth/", label: "门店经营" },
],
},
{ {
href: "/about/", href: "/about/",
label: "关于我们", label: "关于我们",
......
import crypto from "node:crypto";
import path from "node:path";
import fs from "node:fs/promises";
import matter from "gray-matter";
import { marked } from "marked";
const ROOT = process.cwd();
const DATA_ROOT = process.env.CMS_DATA_DIR ? path.resolve(process.env.CMS_DATA_DIR) : null;
export const ARTICLES_DIR = DATA_ROOT ? path.join(DATA_ROOT, "articles") : path.join(ROOT, "src", "content", "articles");
export const PUBLISHED_DIR = DATA_ROOT ? path.join(DATA_ROOT, "published") : path.join(ROOT, "src", "content", "published");
export const CATEGORIES_FILE = DATA_ROOT ? path.join(DATA_ROOT, "categories.json") : path.join(ROOT, "src", "content", "categories.json");
export const UPLOADS_DIR = DATA_ROOT ? path.join(DATA_ROOT, "uploads") : path.join(ROOT, "public", "uploads");
const DEFAULT_CATEGORIES = ["体龄管理", "经络调理", "健康科普", "门店经营"];
const DEFAULT_AUTHOR = "塑美俏体龄管理";
const CATEGORY_SLUGS: Record<string, string> = {
体龄管理: "body-age",
经络调理: "meridian-care",
健康科普: "health-guide",
门店经营: "store-growth",
};
const SLUG_RE = /^[a-z0-9]+(?:-[a-z0-9]+)*$/;
export type PublishStatus = "new-draft" | "edited-draft" | "live";
export interface StoredArticle {
slug: string;
title: string;
date: string;
updated: string;
category: string;
author: string;
excerpt: string;
status: "draft" | "published";
body: string;
}
export interface Article {
id: string;
data: {
title: string;
slug: string;
date: Date;
updated: Date;
category: string;
author: string;
excerpt: string;
status: "published";
};
body: string;
}
export interface CategoryStat {
name: string;
count: number;
}
export interface ContentSnapshot {
restore: () => Promise<void>;
}
export class StoreError extends Error {
status: number;
details?: Record<string, unknown>;
constructor(message: string, status = 400, details?: Record<string, unknown>) {
super(message);
this.status = status;
this.details = details;
}
}
export const safeSlug = (slug: unknown): string | null => typeof slug === "string" && SLUG_RE.test(slug) ? slug : null;
export const fmtDate = (value?: string | Date): string => {
const date = value instanceof Date ? value : new Date(value || Date.now());
return Number.isNaN(date.valueOf()) ? new Date().toISOString().slice(0, 10) : date.toISOString().slice(0, 10);
};
const autoExcerpt = (body: string, fallback: string): string => {
const plain = String(body || "")
.replace(/!\[[^\]]*\]\([^)]*\)/g, " ")
.replace(/\[([^\]]+)\]\([^)]*\)/g, "$1")
.replace(/<[^>]+>/g, " ")
.replace(/[`*_>#~|\-]+/g, " ")
.replace(/\s+/g, " ")
.trim();
const text = plain || String(fallback || "").trim();
return text.length > 120 ? `${text.slice(0, 120).trim()}…` : text;
};
function serialize(data: StoredArticle, body: string): string {
const quote = (value: unknown) => JSON.stringify(value == null ? "" : String(value));
return [
"---",
`title: ${quote(data.title)}`,
`slug: ${quote(data.slug)}`,
`date: ${fmtDate(data.date)}`,
`updated: ${fmtDate(data.updated || data.date)}`,
`category: ${quote(data.category)}`,
`author: ${quote(data.author || DEFAULT_AUTHOR)}`,
`excerpt: ${quote(data.excerpt)}`,
`status: ${quote(data.status || "draft")}`,
"---",
"",
String(body || "").trim(),
"",
].join("\n");
}
async function fileExists(file: string): Promise<boolean> {
try { await fs.access(file); return true; } catch { return false; }
}
async function writeAtomic(file: string, content: string | Buffer): Promise<void> {
await fs.mkdir(path.dirname(file), { recursive: true });
const temporary = `${file}.${process.pid}.${crypto.randomBytes(4).toString("hex")}.tmp`;
try {
await fs.writeFile(temporary, content);
await fs.rename(temporary, file);
} catch (error) {
await fs.unlink(temporary).catch(() => {});
throw error;
}
}
async function ensureStore(): Promise<void> {
await Promise.all([
fs.mkdir(ARTICLES_DIR, { recursive: true }),
fs.mkdir(PUBLISHED_DIR, { recursive: true }),
fs.mkdir(UPLOADS_DIR, { recursive: true }),
]);
if (!await fileExists(CATEGORIES_FILE)) {
await writeAtomic(CATEGORIES_FILE, `${JSON.stringify(DEFAULT_CATEGORIES, null, 2)}\n`);
}
}
export async function getCategoryNames(): Promise<string[]> {
await ensureStore();
try {
const parsed: unknown = JSON.parse(await fs.readFile(CATEGORIES_FILE, "utf8"));
const names = Array.isArray(parsed)
? parsed.map((value) => String(value).replace(/\s+/g, " ").trim()).filter(Boolean)
: [];
return [...new Set(names)].length ? [...new Set(names)] : [...DEFAULT_CATEGORIES];
} catch {
return [...DEFAULT_CATEGORIES];
}
}
async function saveCategories(categories: string[]): Promise<void> {
await writeAtomic(CATEGORIES_FILE, `${JSON.stringify(categories, null, 2)}\n`);
}
function normalizeCategoryName(value: unknown): string {
const name = String(value || "").replace(/\s+/g, " ").trim();
if (!name) throw new StoreError("请输入分类名称");
if (name.length > 20) throw new StoreError("分类名称不能超过 20 个字");
return name;
}
export async function addCategory(value: unknown): Promise<string[]> {
const name = normalizeCategoryName(value);
const categories = await getCategoryNames();
if (categories.includes(name)) throw new StoreError("该分类已经存在", 409);
const next = [...categories, name];
await saveCategories(next);
return next;
}
export async function readArticleFrom(directory: string, slug: string): Promise<StoredArticle> {
const raw = await fs.readFile(path.join(directory, `${slug}.md`), "utf8");
const { data, content } = matter(raw);
return {
slug,
title: String(data.title || ""),
date: fmtDate(data.date),
updated: fmtDate(data.updated || data.date),
category: String(data.category || ""),
author: String(data.author || DEFAULT_AUTHOR),
excerpt: String(data.excerpt || ""),
status: data.status === "draft" ? "draft" : "published",
body: content.trim(),
};
}
export const readWorkingArticle = (slug: string) => readArticleFrom(ARTICLES_DIR, slug);
async function markdownFiles(directory: string): Promise<string[]> {
await ensureStore();
return (await fs.readdir(directory)).filter((file) => file.endsWith(".md"));
}
async function snapshotDirectory(directory: string): Promise<Map<string, string>> {
const snapshot = new Map<string, string>();
for (const filename of await markdownFiles(directory)) {
snapshot.set(filename, await fs.readFile(path.join(directory, filename), "utf8"));
}
return snapshot;
}
async function restoreDirectory(directory: string, snapshot: Map<string, string>): Promise<void> {
for (const filename of await markdownFiles(directory)) {
if (!snapshot.has(filename)) await fs.unlink(path.join(directory, filename));
}
for (const [filename, content] of snapshot) await writeAtomic(path.join(directory, filename), content);
}
export async function createContentSnapshot(): Promise<ContentSnapshot> {
await ensureStore();
const articles = await snapshotDirectory(ARTICLES_DIR);
const published = await snapshotDirectory(PUBLISHED_DIR);
const categories = await fs.readFile(CATEGORIES_FILE, "utf8");
return {
restore: async () => {
await restoreDirectory(ARTICLES_DIR, articles);
await restoreDirectory(PUBLISHED_DIR, published);
await writeAtomic(CATEGORIES_FILE, categories);
},
};
}
const sameArticleContent = (left: StoredArticle, right: StoredArticle): boolean =>
["slug", "title", "date", "category", "author", "excerpt", "body"]
.every((key) => String(left[key as keyof StoredArticle] ?? "") === String(right[key as keyof StoredArticle] ?? ""));
export async function getPublishStatus(article: StoredArticle): Promise<PublishStatus> {
const liveFile = path.join(PUBLISHED_DIR, `${article.slug}.md`);
if (!await fileExists(liveFile)) return "new-draft";
const liveArticle = await readArticleFrom(PUBLISHED_DIR, article.slug);
return sameArticleContent(article, liveArticle) ? "live" : "edited-draft";
}
export async function listWorkingArticles(): Promise<Array<Omit<StoredArticle, "body"> & { publishStatus: PublishStatus }>> {
const articles = await Promise.all((await markdownFiles(ARTICLES_DIR)).map(async (file) => {
const article = await readWorkingArticle(file.replace(/\.md$/, ""));
const { body: _body, ...meta } = article;
return { ...meta, publishStatus: await getPublishStatus(article) };
}));
return articles.sort((a, b) => b.updated.localeCompare(a.updated) || b.date.localeCompare(a.date));
}
export async function writeArticle(slug: string, input: Record<string, unknown>, isNew = false): Promise<StoredArticle> {
await ensureStore();
const file = path.join(ARTICLES_DIR, `${slug}.md`);
if (isNew && await fileExists(file)) throw new StoreError("该网址标识已存在", 409);
const existing = !isNew && await fileExists(file) ? await readWorkingArticle(slug) : null;
const categories = await getCategoryNames();
const body = String(input.body || "").trim();
const normalized: StoredArticle = {
title: String(input.title || "").trim(),
slug,
date: existing?.date || fmtDate(),
updated: fmtDate(),
category: categories.includes(String(input.category)) ? String(input.category) : categories[0],
author: DEFAULT_AUTHOR,
excerpt: autoExcerpt(body, String(input.title || "")),
status: "draft",
body,
};
const liveFile = path.join(PUBLISHED_DIR, `${slug}.md`);
if (await fileExists(liveFile)) {
const liveArticle = await readArticleFrom(PUBLISHED_DIR, slug);
if (sameArticleContent(normalized, liveArticle)) {
normalized.status = "published";
normalized.updated = liveArticle.updated;
}
}
await writeAtomic(file, serialize(normalized, body));
return normalized;
}
export async function generateSlug(category: unknown, date = fmtDate()): Promise<string> {
await ensureStore();
const prefix = CATEGORY_SLUGS[String(category)] || "health-article";
const base = `${prefix}-${date.replaceAll("-", "")}`;
let slug = base;
let suffix = 2;
while (await fileExists(path.join(ARTICLES_DIR, `${slug}.md`)) || await fileExists(path.join(PUBLISHED_DIR, `${slug}.md`))) {
slug = `${base}-${suffix++}`;
}
return slug;
}
async function restoreFile(file: string, content: string | null): Promise<void> {
if (content === null) await fs.unlink(file).catch(() => {});
else await writeAtomic(file, content);
}
export async function publishArticle(slug: string): Promise<void> {
const article = await readWorkingArticle(slug);
const published: StoredArticle = { ...article, status: "published", updated: fmtDate() };
const text = serialize(published, article.body);
const draftFile = path.join(ARTICLES_DIR, `${slug}.md`);
const liveFile = path.join(PUBLISHED_DIR, `${slug}.md`);
const previousDraft = await fs.readFile(draftFile, "utf8");
const previousLive = await fileExists(liveFile) ? await fs.readFile(liveFile, "utf8") : null;
try {
await writeAtomic(liveFile, text);
await writeAtomic(draftFile, text);
} catch (error) {
await restoreFile(draftFile, previousDraft);
await restoreFile(liveFile, previousLive);
throw error;
}
}
export async function unpublishArticle(slug: string): Promise<void> {
const draftFile = path.join(ARTICLES_DIR, `${slug}.md`);
const liveFile = path.join(PUBLISHED_DIR, `${slug}.md`);
const previousDraft = await fs.readFile(draftFile, "utf8");
const previousLive = await fs.readFile(liveFile, "utf8");
const article = await readWorkingArticle(slug);
try {
await writeAtomic(draftFile, serialize({ ...article, status: "draft" }, article.body));
await fs.unlink(liveFile);
} catch (error) {
await restoreFile(draftFile, previousDraft);
await restoreFile(liveFile, previousLive);
throw error;
}
}
export async function deleteArticle(slug: string): Promise<void> {
const files = [path.join(ARTICLES_DIR, `${slug}.md`), path.join(PUBLISHED_DIR, `${slug}.md`)];
const backups: Array<{ file: string; content: string }> = [];
for (const file of files) if (await fileExists(file)) backups.push({ file, content: await fs.readFile(file, "utf8") });
if (!backups.length) throw new StoreError("文章不存在", 404);
try {
for (const { file } of backups) await fs.unlink(file);
} catch (error) {
for (const { file, content } of backups) await writeAtomic(file, content);
throw error;
}
}
export async function discardDraft(slug: string): Promise<{ removed: boolean; publishStatus: PublishStatus | null }> {
const liveFile = path.join(PUBLISHED_DIR, `${slug}.md`);
const draftFile = path.join(ARTICLES_DIR, `${slug}.md`);
if (await fileExists(liveFile)) {
await fs.copyFile(liveFile, draftFile);
return { removed: false, publishStatus: "live" };
}
await fs.unlink(draftFile);
return { removed: true, publishStatus: null };
}
async function categoryArticleFiles(category: string): Promise<Array<{ file: string; article: StoredArticle; raw: string }>> {
const results: Array<{ file: string; article: StoredArticle; raw: string }> = [];
for (const directory of [ARTICLES_DIR, PUBLISHED_DIR]) {
for (const filename of await markdownFiles(directory)) {
const slug = filename.replace(/\.md$/, "");
const article = await readArticleFrom(directory, slug);
if (article.category === category) {
const file = path.join(directory, filename);
results.push({ file, article, raw: await fs.readFile(file, "utf8") });
}
}
}
return results;
}
export async function getCategoryStats(): Promise<CategoryStat[]> {
const categories = await getCategoryNames();
const seen = new Map<string, Set<string>>(categories.map((name) => [name, new Set()]));
for (const directory of [ARTICLES_DIR, PUBLISHED_DIR]) {
for (const filename of await markdownFiles(directory)) {
const slug = filename.replace(/\.md$/, "");
const article = await readArticleFrom(directory, slug);
if (!seen.has(article.category)) seen.set(article.category, new Set());
seen.get(article.category)?.add(slug);
}
}
return categories.map((name) => ({ name, count: seen.get(name)?.size || 0 }));
}
async function updateCategoryArticles(current: string, replacement: string, nextCategories: string[]): Promise<void> {
const affected = await categoryArticleFiles(current);
const previousCategories = await fs.readFile(CATEGORIES_FILE, "utf8");
try {
for (const item of affected) {
const updated = { ...item.article, category: replacement };
await writeAtomic(item.file, serialize(updated, updated.body));
}
await saveCategories(nextCategories);
} catch (error) {
for (const item of affected) await writeAtomic(item.file, item.raw);
await writeAtomic(CATEGORIES_FILE, previousCategories);
throw error;
}
}
export async function renameCategory(currentValue: unknown, nextValue: unknown): Promise<string[]> {
const current = normalizeCategoryName(currentValue);
const nextName = normalizeCategoryName(nextValue);
const categories = await getCategoryNames();
if (!categories.includes(current)) throw new StoreError("分类不存在", 404);
if (current !== nextName && categories.includes(nextName)) throw new StoreError("该分类已经存在", 409);
if (current === nextName) return categories;
const next = categories.map((name) => name === current ? nextName : name);
await updateCategoryArticles(current, nextName, next);
return next;
}
export async function removeCategory(value: unknown, replacementValue: unknown): Promise<string[]> {
const name = normalizeCategoryName(value);
const categories = await getCategoryNames();
if (!categories.includes(name)) throw new StoreError("分类不存在", 404);
if (categories.length <= 1) throw new StoreError("至少需要保留一个文章分类", 409);
const affected = await categoryArticleFiles(name);
const count = new Set(affected.map((item) => item.article.slug)).size;
const replacement = String(replacementValue || "").trim();
if (count > 0 && (!replacement || !categories.includes(replacement) || replacement === name)) {
throw new StoreError("请先选择这些文章要迁移到的分类", 409, { requiresReplacement: true, count });
}
const next = categories.filter((category) => category !== name);
await updateCategoryArticles(name, replacement, next);
return next;
}
export async function getPublishedArticles(): Promise<Article[]> {
const items = await Promise.all((await markdownFiles(PUBLISHED_DIR)).map(async (file) => {
const article = await readArticleFrom(PUBLISHED_DIR, file.replace(/\.md$/, ""));
return {
id: article.slug,
data: {
title: article.title,
slug: article.slug,
date: new Date(article.date),
updated: new Date(article.updated),
category: article.category,
author: article.author,
excerpt: article.excerpt,
status: "published" as const,
},
body: article.body,
};
}));
return items.sort((a, b) => b.data.date.valueOf() - a.data.date.valueOf());
}
export async function getPublishedArticle(slug: string): Promise<(Article & { html: string }) | null> {
if (!safeSlug(slug)) return null;
try {
const article = await readArticleFrom(PUBLISHED_DIR, slug);
return {
id: article.slug,
data: {
title: article.title,
slug: article.slug,
date: new Date(article.date),
updated: new Date(article.updated),
category: article.category,
author: article.author,
excerpt: article.excerpt,
status: "published",
},
body: article.body,
html: await marked.parse(article.body),
};
} catch (error) {
if ((error as NodeJS.ErrnoException).code === "ENOENT") return null;
throw error;
}
}
export async function saveUpload(dataUrl: unknown): Promise<string> {
await ensureStore();
const extensions: Record<string, string> = { "image/png": "png", "image/jpeg": "jpg", "image/webp": "webp", "image/gif": "gif" };
const match = String(dataUrl || "").match(/^data:([^;]+);base64,(.+)$/s);
if (!match || !extensions[match[1]]) throw new StoreError("仅支持 PNG、JPG、WEBP 或 GIF 图片");
const buffer = Buffer.from(match[2], "base64");
if (buffer.length > 8 * 1024 * 1024) throw new StoreError("图片不能超过 8MB", 413);
const name = `${Date.now()}-${crypto.randomBytes(4).toString("hex")}.${extensions[match[1]]}`;
await writeAtomic(path.join(UPLOADS_DIR, name), buffer);
return `/uploads/${name}`;
}
import { getPublishedArticles as readPublishedArticles, type Article } from "./article-store";
export type { Article };
export const PAGE_SIZE = 9;
const CATEGORY_SLUGS: Record<string, string> = {
体龄管理: "body-age",
经络调理: "meridian",
健康科普: "wellness",
门店经营: "store-growth",
};
function fallbackSlug(category: string): string {
const ascii = category.toLowerCase().replace(/[^a-z0-9]+/g, "-").replace(/^-+|-+$/g, "");
if (ascii) return ascii;
let hash = 0;
for (const char of category) hash = (hash * 31 + (char.codePointAt(0) ?? 0)) >>> 0;
return `c${hash.toString(36)}`;
}
export const categoryToSlug = (category: string) => CATEGORY_SLUGS[category] ?? fallbackSlug(category);
export function slugToCategory(slug: string, categories: string[]): string | undefined {
return categories.find((category) => categoryToSlug(category) === slug);
}
export async function getPublishedArticles(): Promise<Article[]> {
return readPublishedArticles();
}
export interface CategoryInfo {
name: string;
slug: string;
count: number;
}
export function getCategories(items: Article[]): CategoryInfo[] {
const counts = new Map<string, number>();
for (const item of items) counts.set(item.data.category, (counts.get(item.data.category) ?? 0) + 1);
return [...counts.entries()]
.map(([name, count]) => ({ name, slug: categoryToSlug(name), count }))
.sort((a, b) => b.count - a.count || a.name.localeCompare(b.name, "zh-CN"));
}
export const lastPageOf = (total: number, pageSize = PAGE_SIZE) => Math.max(1, Math.ceil(total / pageSize));
export const pageSlice = <T>(items: T[], page: number, pageSize = PAGE_SIZE) => items.slice((page - 1) * pageSize, page * pageSize);
export const fmtDate = (date: Date) => date.toISOString().slice(0, 10);
export function paginationWindow(current: number, last: number, span = 2): number[] {
const pages = new Set<number>([1, last]);
for (let page = current - span; page <= current + span; page++) if (page >= 1 && page <= last) pages.add(page);
const sorted = [...pages].sort((a, b) => a - b);
const result: number[] = [];
let previous = 0;
for (const page of sorted) {
if (previous && page - previous > 1) result.push(0);
result.push(page);
previous = page;
}
return result;
}
import crypto from "node:crypto";
import { marked } from "marked";
import {
StoreError,
addCategory,
createContentSnapshot,
deleteArticle,
discardDraft,
generateSlug,
getCategoryNames,
getCategoryStats,
getPublishStatus,
listWorkingArticles,
publishArticle,
readWorkingArticle,
removeCategory,
renameCategory,
safeSlug,
saveUpload,
unpublishArticle,
writeArticle,
} from "./article-store";
import { buildSiteAtomic, tryAcquireSiteBuildLock, withSiteBuildLock } from "../../scripts/site-build.mjs";
const PASSWORD = process.env.CMS_PASSWORD || "admin";
const SECRET = process.env.CMS_SECRET || crypto.randomBytes(32).toString("hex");
const API_KEY = process.env.CMS_API_KEY || "";
const loginAttempts = new Map<string, { count: number; until: number }>();
type BuildState = {
status: "idle" | "building" | "success" | "error";
ok: boolean | null;
log: string;
startedAt: string | null;
finishedAt: string | null;
};
let buildState: BuildState = { status: "idle", ok: null, log: "", startedAt: null, finishedAt: null };
const json = (data: unknown, status = 200, headers?: HeadersInit) => Response.json(data, { status, headers });
const safeEqual = (leftValue: unknown, rightValue: unknown): boolean => {
const left = Buffer.from(String(leftValue));
const right = Buffer.from(String(rightValue));
return left.length === right.length && crypto.timingSafeEqual(left, right);
};
const sessionToken = () => crypto.createHmac("sha256", SECRET).update("sumeiqiao-cms-v1").digest("hex");
function cookies(request: Request): Record<string, string> {
return Object.fromEntries((request.headers.get("cookie") || "").split(";").filter(Boolean).map((part) => {
const index = part.indexOf("=");
return [part.slice(0, index).trim(), decodeURIComponent(part.slice(index + 1).trim())];
}));
}
function apiKeyValid(request: Request): boolean {
if (!API_KEY) return false;
const auth = request.headers.get("authorization")?.match(/^Bearer\s+(.+)$/i)?.[1];
const key = auth || request.headers.get("x-api-key");
return key ? safeEqual(key, API_KEY) : false;
}
const authed = (request: Request): boolean =>
Boolean(cookies(request).cms_session && safeEqual(cookies(request).cms_session, sessionToken())) || apiKeyValid(request);
async function bodyOf(request: Request): Promise<Record<string, unknown>> {
try { return await request.json(); } catch { return {}; }
}
function cookieHeader(request: Request, value: string, maxAge: number): string {
const forwarded = request.headers.get("x-forwarded-proto");
const secure = new URL(request.url).protocol === "https:" || forwarded === "https";
return `cms_session=${value}; HttpOnly; SameSite=Strict; Path=/; Max-Age=${maxAge}${secure ? "; Secure" : ""}`;
}
function loginAllowed(ip: string): boolean {
const state = loginAttempts.get(ip);
return !state || state.until < Date.now();
}
function loginFailed(ip: string): void {
const state = loginAttempts.get(ip) || { count: 0, until: 0 };
state.count += 1;
if (state.count >= 5) state.until = Date.now() + 10 * 60 * 1000;
loginAttempts.set(ip, state);
}
function requireSlug(value: string | undefined): string {
const slug = safeSlug(value);
if (!slug) throw new StoreError("网址标识不合法");
return slug;
}
async function startContentBuild(change: () => Promise<void>): Promise<boolean> {
if (buildState.status === "building") return false;
const releaseLock = await tryAcquireSiteBuildLock();
if (!releaseLock) return false;
buildState = { status: "building", ok: null, log: "", startedAt: new Date().toISOString(), finishedAt: null };
void (async () => {
const snapshot = await createContentSnapshot();
try {
await change();
const log = await buildSiteAtomic();
buildState = { status: "success", ok: true, log, startedAt: buildState.startedAt, finishedAt: new Date().toISOString() };
} catch (error) {
let rollbackMessage = "";
try { await snapshot.restore(); } catch (rollbackError) {
rollbackMessage = `\n内容回滚失败:${rollbackError instanceof Error ? rollbackError.message : String(rollbackError)}`;
}
const message = error instanceof Error ? error.message : String(error);
const log = typeof error === "object" && error && "log" in error ? String(error.log || "") : "";
buildState = {
status: "error",
ok: false,
log: `${log}${log ? "\n" : ""}${message}${rollbackMessage}`,
startedAt: buildState.startedAt,
finishedAt: new Date().toISOString(),
};
}
})().finally(releaseLock).catch((error) => {
buildState = {
status: "error",
ok: false,
log: error instanceof Error ? error.message : String(error),
startedAt: buildState.startedAt,
finishedAt: new Date().toISOString(),
};
});
return true;
}
async function startOrConflict(change: () => Promise<void>): Promise<Response> {
if (!await startContentBuild(change)) {
return json({ error: "网站正在部署或生成静态页面,本次操作未受理,请稍后重试" }, 409, { "Retry-After": "5" });
}
return json({ ok: true, status: "building" });
}
export async function handleCmsApi(request: Request, routeValue: string, clientAddress = "unknown"): Promise<Response> {
const route = routeValue.replace(/^\/+|\/+$/g, "");
const parts = route.split("/").filter(Boolean);
const method = request.method.toUpperCase();
try {
if (route === "session") {
if (method === "GET") return json({ authed: authed(request) });
if (method === "POST") {
if (!loginAllowed(clientAddress)) throw new StoreError("登录尝试过于频繁,请稍后再试", 429);
const body = await bodyOf(request);
if (!safeEqual(body.password || "", PASSWORD)) {
loginFailed(clientAddress);
throw new StoreError("管理密码错误", 401);
}
loginAttempts.delete(clientAddress);
return json({ ok: true }, 200, { "Set-Cookie": cookieHeader(request, sessionToken(), 86400) });
}
if (method === "DELETE") return json({ ok: true }, 200, { "Set-Cookie": cookieHeader(request, "", 0) });
}
if (!authed(request)) throw new StoreError("请先登录文章后台", 401);
if (route === "categories") {
if (method === "GET") return json({ categories: await getCategoryNames(), stats: await getCategoryStats() });
const body = await bodyOf(request);
if (method === "POST") {
const categories = await withSiteBuildLock(() => addCategory(body.name));
return json({ ok: true, category: String(body.name || "").trim(), categories, stats: await getCategoryStats() }, 201);
}
if (method === "PATCH") {
return startOrConflict(async () => { await renameCategory(body.current, body.name); });
}
if (method === "DELETE") {
return startOrConflict(async () => { await removeCategory(body.name, body.replacement); });
}
}
if (route === "build" && method === "GET") return json(buildState);
if (route === "articles") {
if (method === "GET") return json(await listWorkingArticles());
if (method === "POST") {
const body = await bodyOf(request);
if (!String(body.title || "").trim()) throw new StoreError("请填写文章标题");
if (!String(body.body || "").trim()) throw new StoreError("请填写文章正文");
const slug = await generateSlug(body.category);
const article = await withSiteBuildLock(() => writeArticle(slug, body, true));
return json({ ok: true, slug, publishStatus: await getPublishStatus(article) }, 201);
}
}
if (parts[0] === "articles" && parts[1]) {
const slug = requireSlug(parts[1]);
if (parts.length === 3 && parts[2] === "draft" && method === "DELETE") {
return json({ ok: true, ...await withSiteBuildLock(() => discardDraft(slug)) });
}
if (parts.length === 3 && parts[2] === "publish" && method === "POST") {
return startOrConflict(async () => { await publishArticle(slug); });
}
if (parts.length === 3 && parts[2] === "unpublish" && method === "POST") {
return startOrConflict(async () => { await unpublishArticle(slug); });
}
if (parts.length === 2 && method === "GET") {
const article = await readWorkingArticle(slug);
return json({ ...article, publishStatus: await getPublishStatus(article) });
}
if (parts.length === 2 && method === "PUT") {
const body = await bodyOf(request);
if (!String(body.title || "").trim()) throw new StoreError("请填写文章标题");
if (!String(body.body || "").trim()) throw new StoreError("请填写文章正文");
const article = await withSiteBuildLock(() => writeArticle(slug, body));
return json({ ok: true, slug, publishStatus: await getPublishStatus(article) });
}
if (parts.length === 2 && method === "DELETE") {
return startOrConflict(async () => { await deleteArticle(slug); });
}
}
if (route === "preview" && method === "POST") {
const body = await bodyOf(request);
return json({ html: await marked.parse(String(body.body || "")) });
}
if (route === "uploads" && method === "POST") {
const body = await bodyOf(request);
return json({ ok: true, url: await saveUpload(body.dataUrl) });
}
return json({ error: "接口不存在" }, 404);
} catch (error) {
if (error instanceof StoreError) return json({ error: error.message, ...error.details }, error.status);
if ((error as NodeJS.ErrnoException).code === "ENOENT") return json({ error: "文章不存在" }, 404);
console.error(error);
return json({ error: error instanceof Error ? error.message : "服务器处理失败" }, 500);
}
}
<!doctype html>
<html lang="zh-CN">
<head>
<meta charset="utf-8" />
<meta name="viewport" content="width=device-width, initial-scale=1" />
<meta name="robots" content="noindex,nofollow" />
<title>塑美俏 · 健康资讯后台</title>
<link rel="stylesheet" href="/admin/style.css" />
</head>
<body>
<section id="login" class="login hidden">
<form id="login-form" class="login-card">
<div class="brand-mark">塑美俏</div>
<h1>健康资讯后台</h1>
<p>输入管理密码,管理官网文章内容。</p>
<label>管理密码<input id="password" type="password" autocomplete="current-password" required /></label>
<button class="primary" type="submit">登录后台</button>
<div id="login-error" class="error"></div>
</form>
</section>
<div id="app" class="hidden">
<header class="topbar">
<div><strong>塑美俏</strong><span>健康资讯后台</span></div>
<div class="top-actions">
<span id="pending-badge" class="pending-badge hidden"></span>
<a class="button ghost" href="/articles/" target="_blank" rel="noopener">查看前台</a>
<button id="logout" class="ghost">退出</button>
</div>
</header>
<main id="list-view" class="view">
<div class="view-head"><div><p>CONTENT</p><h1>健康资讯</h1></div><div class="view-actions"><button id="manage-categories" class="ghost">管理分类</button><button id="new-article" class="primary">+ 新建文章</button></div></div>
<div id="article-list" class="article-list"></div>
</main>
<main id="edit-view" class="view hidden">
<div class="view-head editor-titlebar">
<div><button id="back" class="back-button" type="button">← 返回文章列表</button><h1 id="edit-heading">编辑文章</h1></div>
<span id="editor-status" class="status"></span>
</div>
<div id="version-note" class="version-note"></div>
<form id="edit-form">
<section class="field-panel">
<label>文章标题<input id="title" required /></label>
<div class="field-label">
<span>文章分类</span>
<div id="category-select" class="custom-select">
<input id="category" type="hidden" />
<button id="category-trigger" class="select-trigger" type="button" aria-haspopup="listbox" aria-expanded="false">
<span id="category-value"></span><span class="select-chevron" aria-hidden="true"></span>
</button>
<div id="category-menu" class="select-menu hidden">
<div id="category-options" class="select-options" role="listbox" aria-label="文章分类"></div>
<div class="category-create">
<span>添加新分类</span>
<div><input id="new-category" maxlength="20" placeholder="输入分类名称" /><button id="add-category" class="primary small" type="button">添加</button></div>
<p id="category-error" class="error"></p>
</div>
</div>
</div>
</div>
<p class="auto-meta">文章网址、摘要、作者和 SEO 信息将由系统自动生成,无需填写。</p>
</section>
<section class="editor-panel">
<div class="editor-head"><div><strong>文章正文</strong><small>右侧会自动显示预览</small></div><div><span id="upload-status"></span><button id="upload-button" class="ghost small" type="button">插入图片</button></div></div>
<input id="file" class="hidden" type="file" accept="image/png,image/jpeg,image/webp,image/gif" />
<div class="editor-grid"><textarea id="body" required spellcheck="false" placeholder="在这里撰写文章正文……"></textarea><div id="preview" class="preview" aria-live="polite"></div></div>
</section>
<div class="edit-actions">
<button class="ghost save-button" type="submit">保存草稿</button>
<button id="publish" class="primary" type="button">发布到官网</button>
<details id="more-actions" class="more-actions hidden">
<summary>更多操作</summary>
<div class="action-menu">
<button id="discard" class="menu-action hidden" type="button">放弃未发布修改</button>
<button id="unpublish" class="menu-action danger hidden" type="button">下架文章</button>
<button id="delete-article" class="menu-action danger hidden" type="button">删除文章</button>
</div>
</details>
<span id="message"></span>
</div>
</form>
</main>
</div>
<div id="category-modal" class="modal hidden">
<div class="modal-card category-manager">
<div class="modal-head"><div><strong>文章分类管理</strong><small>重命名会同步更新该分类下的文章</small></div><button id="close-category-modal" class="ghost small" type="button">关闭</button></div>
<div class="category-manager-body">
<div class="manager-create"><input id="manager-new-category" maxlength="20" placeholder="输入新分类名称" /><button id="manager-add-category" class="primary" type="button">添加分类</button></div>
<p id="manager-category-error" class="error"></p>
<div id="category-manager-list" class="category-manager-list"></div>
</div>
</div>
</div>
<div id="build-modal" class="modal hidden">
<div class="modal-card build-card">
<div><strong id="build-title">正在生成静态页面</strong><button id="close-modal" class="ghost small hidden" type="button">关闭</button></div>
<pre id="build-log">系统正在更新官网,请稍候。</pre>
</div>
</div>
<script is:inline src="/admin/app.js"></script>
</body>
</html>
import type { APIRoute } from "astro";
import { handleCmsApi } from "../../../lib/cms-api";
export const prerender = false;
const handler: APIRoute = ({ request, params, clientAddress }) =>
handleCmsApi(request, params.route || "", clientAddress);
export const GET = handler;
export const POST = handler;
export const PUT = handler;
export const PATCH = handler;
export const DELETE = handler;
---
import Base from "../../layouts/Base.astro";
import Header from "../../components/Header.astro";
import Footer from "../../components/Footer.astro";
import { site } from "../../data/site";
import { getPublishedArticle, getPublishedArticles } from "../../lib/article-store";
import { fmtDate } from "../../lib/articles";
type ArticleDetail = NonNullable<Awaited<ReturnType<typeof getPublishedArticle>>>;
export async function getStaticPaths() {
const articles = await getPublishedArticles();
return Promise.all(articles.map(async (article) => ({
params: { slug: article.id },
props: { entry: await getPublishedArticle(article.id) },
})));
}
const { entry } = Astro.props as { entry: ArticleDetail };
const article = entry.data;
const date = fmtDate(article.date);
const title = `${article.title}|健康资讯|${site.brand.name}`;
const pageUrl = new URL(`/articles/${entry.id}/`, Astro.site).href;
const jsonLd = [
{
"@context": "https://schema.org",
"@type": "Article",
headline: article.title,
description: article.excerpt,
datePublished: date,
dateModified: fmtDate(article.updated || article.date),
articleSection: article.category,
inLanguage: "zh-CN",
author: { "@type": "Organization", name: article.author },
publisher: { "@id": new URL("/#organization", Astro.site).href },
mainEntityOfPage: { "@type": "WebPage", "@id": pageUrl },
url: pageUrl,
},
{
"@context": "https://schema.org",
"@type": "BreadcrumbList",
itemListElement: [
{ "@type": "ListItem", position: 1, name: "首页", item: Astro.site?.href },
{ "@type": "ListItem", position: 2, name: "健康资讯", item: new URL("/articles/", Astro.site).href },
{ "@type": "ListItem", position: 3, name: article.title, item: pageUrl },
],
},
];
---
<Base title={title} description={article.excerpt} ogType="article" jsonLd={jsonLd}>
<Header />
<main id="main-content" class="article-detail-page">
<article>
<header class="article-detail-head">
<div class="container article-detail-head__inner">
<div class="breadcrumb"><a href="/">首页</a> / <a href="/articles/">健康资讯</a> / {article.category}</div>
<span class="article-detail-category">{article.category}</span>
<h1>{article.title}</h1>
<p>{article.excerpt}</p>
<div class="article-detail-meta"><time datetime={date}>{date}</time><span>{article.author}</span></div>
</div>
</header>
<div class="container article-detail-layout">
<aside><a href="/articles/">← 返回健康资讯</a><p>健康管理服务不替代医疗诊断与治疗。如有不适或异常指标,请及时咨询专业医疗人员。</p></aside>
<div class="article-prose" set:html={entry.html}></div>
</div>
</article>
</main>
<Footer />
</Base>
---
import ArticlesView from "../../components/ArticlesView.astro";
import { getPublishedArticles, getCategories, pageSlice, lastPageOf } from "../../lib/articles";
const all = await getPublishedArticles();
const categories = getCategories(all);
const items = pageSlice(all, 1);
---
<ArticlesView items={items} categories={categories} totalCount={all.length} activeSlug={null} activeName={null} currentPage={1} lastPage={lastPageOf(all.length)} basePath="/articles" />
---
import ArticlesView from "../../../components/ArticlesView.astro";
import { getPublishedArticles, getCategories, pageSlice, lastPageOf } from "../../../lib/articles";
export async function getStaticPaths() {
const articles = await getPublishedArticles();
return Array.from({ length: Math.max(0, lastPageOf(articles.length) - 1) }, (_, index) => ({
params: { page: String(index + 2) },
}));
}
const all = await getPublishedArticles();
const page = Number(Astro.params.page);
---
<ArticlesView items={pageSlice(all, page)} categories={getCategories(all)} totalCount={all.length} activeSlug={null} activeName={null} currentPage={page} lastPage={lastPageOf(all.length)} basePath="/articles" />
---
import ArticlesView from "../../../../components/ArticlesView.astro";
import { getPublishedArticles, getCategories, slugToCategory, pageSlice, lastPageOf } from "../../../../lib/articles";
export async function getStaticPaths() {
const articles = await getPublishedArticles();
return getCategories(articles).map((category) => ({
params: { slug: category.slug },
props: { categoryName: category.name },
}));
}
const all = await getPublishedArticles();
const categories = getCategories(all);
const categoryName = String(Astro.props.categoryName || slugToCategory(Astro.params.slug!, categories.map((item) => item.name)) || "");
const filtered = all.filter((item) => item.data.category === categoryName);
---
<ArticlesView items={pageSlice(filtered, 1)} categories={categories} totalCount={all.length} activeSlug={Astro.params.slug!} activeName={categoryName} currentPage={1} lastPage={lastPageOf(filtered.length)} basePath={`/articles/topic/${Astro.params.slug}`} />
---
import ArticlesView from "../../../../../components/ArticlesView.astro";
import { getPublishedArticles, getCategories, slugToCategory, pageSlice, lastPageOf } from "../../../../../lib/articles";
export async function getStaticPaths() {
const articles = await getPublishedArticles();
const paths: Array<{ params: { slug: string; page: string }; props: { categoryName: string } }> = [];
for (const category of getCategories(articles)) {
for (let page = 2; page <= lastPageOf(category.count); page += 1) {
paths.push({ params: { slug: category.slug, page: String(page) }, props: { categoryName: category.name } });
}
}
return paths;
}
const all = await getPublishedArticles();
const categories = getCategories(all);
const categoryName = String(Astro.props.categoryName || slugToCategory(Astro.params.slug!, categories.map((item) => item.name)) || "");
const filtered = all.filter((item) => item.data.category === categoryName);
const page = Number(Astro.params.page);
---
<ArticlesView items={pageSlice(filtered, page)} categories={categories} totalCount={all.length} activeSlug={Astro.params.slug!} activeName={categoryName} currentPage={page} lastPage={lastPageOf(filtered.length)} basePath={`/articles/topic/${Astro.params.slug}`} />
import type { APIRoute } from "astro";
import path from "node:path";
import fs from "node:fs/promises";
import { UPLOADS_DIR } from "../../lib/article-store";
export const prerender = false;
const MIME_TYPES: Record<string, string> = {
".png": "image/png",
".jpg": "image/jpeg",
".jpeg": "image/jpeg",
".webp": "image/webp",
".gif": "image/gif",
};
export const GET: APIRoute = async ({ params }) => {
const filename = params.file || "";
if (!/^[a-zA-Z0-9._-]+$/.test(filename)) return new Response("Not Found", { status: 404 });
try {
const content = await fs.readFile(path.join(UPLOADS_DIR, filename));
return new Response(content, {
headers: {
"Content-Type": MIME_TYPES[path.extname(filename).toLowerCase()] || "application/octet-stream",
"Cache-Control": "public, max-age=31536000, immutable",
},
});
} catch {
return new Response("Not Found", { status: 404 });
}
};
...@@ -118,7 +118,7 @@ section[id], .faq-item[id] { scroll-margin-top: 112px; } ...@@ -118,7 +118,7 @@ section[id], .faq-item[id] { scroll-margin-top: 112px; }
display: flex; display: flex;
align-items: stretch; align-items: stretch;
justify-content: center; justify-content: center;
gap: clamp(18px, 2.2vw, 34px); gap: clamp(12px, 1.55vw, 25px);
list-style: none; list-style: none;
} }
.nav-item { .nav-item {
...@@ -468,6 +468,52 @@ section[id], .faq-item[id] { scroll-margin-top: 112px; } ...@@ -468,6 +468,52 @@ section[id], .faq-item[id] { scroll-margin-top: 112px; }
.not-found h1 { margin: 16px 0 10px; color: var(--ink-green); font-family: var(--serif); font-size: 40px; font-weight: 600; } .not-found h1 { margin: 16px 0 10px; color: var(--ink-green); font-family: var(--serif); font-size: 40px; font-weight: 600; }
.not-found p { color: var(--muted); } .not-found p { color: var(--muted); }
/* 健康资讯 */
.article-hero h1 { max-width: 760px; }
.article-tabs { margin-bottom: 46px; display: flex; flex-wrap: wrap; gap: 10px; }
.article-tab { padding: 9px 16px; color: var(--muted); background: var(--bg); border: 1px solid var(--border); border-radius: 999px; font-size: 13px; transition: color .18s ease, background .18s ease, border-color .18s ease; }
.article-tab span { margin-left: 5px; color: var(--secondary); font-size: 11px; }
.article-tab:hover, .article-tab.active { color: white; background: var(--primary-dark); border-color: var(--primary-dark); }
.article-tab.active span, .article-tab:hover span { color: rgba(255,255,255,.7); }
.article-grid { display: grid; grid-template-columns: repeat(3, minmax(0, 1fr)); gap: 20px; }
.article-card { min-height: 390px; background: var(--surface); border: 1px solid var(--border); border-radius: 20px; transition: transform .25s ease, border-color .25s ease, box-shadow .25s ease; }
.article-card:hover { transform: translateY(-5px); border-color: var(--secondary); box-shadow: 0 22px 48px rgba(36,79,72,.1); }
.article-card > a { min-height: 390px; padding: 28px; display: flex; flex-direction: column; }
.article-card__meta { display: flex; align-items: center; justify-content: space-between; gap: 12px; color: var(--muted); font-size: 11px; }
.article-card__meta span { color: var(--primary-dark); font-weight: 600; }
.article-card__index { margin-top: 46px; color: var(--secondary); font-family: Georgia, serif; font-size: 12px; }
.article-card h2 { margin: 17px 0 14px; color: var(--ink-green); font-size: 25px; font-weight: 600; line-height: 1.45; }
.article-card p { margin-bottom: 24px; color: var(--muted); font-size: 13px; }
.article-card strong { margin-top: auto; color: var(--primary-dark); font-size: 13px; }
.article-card strong span { margin-left: 4px; }
.article-empty { padding: 70px 0; color: var(--muted); text-align: center; border-block: 1px solid var(--border); }
.article-pagination { margin-top: 54px; display: flex; align-items: center; justify-content: center; gap: 8px; }
.article-pagination a, .article-pagination > span { width: 38px; height: 38px; display: grid; place-content: center; color: var(--muted); border: 1px solid var(--border); border-radius: 50%; font-size: 13px; }
.article-pagination a:hover, .article-pagination .active { color: white; background: var(--primary-dark); border-color: var(--primary-dark); }
.article-pagination .gap { border-color: transparent; }
.article-detail-head { padding: 88px 0 78px; background: linear-gradient(135deg, var(--bg), var(--secondary-light)); }
.article-detail-head__inner { max-width: 920px; }
.article-detail-category { display: inline-block; margin-top: 12px; color: var(--primary-dark); font-size: 12px; font-weight: 700; letter-spacing: .12em; }
.article-detail-head h1 { max-width: 900px; margin: 19px 0 20px; color: var(--ink-green); font-size: clamp(42px, 6vw, 68px); font-weight: 600; line-height: 1.2; }
.article-detail-head p { max-width: 760px; margin-bottom: 24px; color: var(--muted); font-size: 18px; }
.article-detail-meta { display: flex; gap: 18px; color: #82908b; font-size: 12px; }
.article-detail-layout { padding-top: 82px; padding-bottom: 112px; display: grid; grid-template-columns: 220px minmax(0, 760px); justify-content: center; gap: 76px; align-items: start; }
.article-detail-layout aside { position: sticky; top: 128px; padding-top: 18px; border-top: 1px solid var(--border); }
.article-detail-layout aside a { color: var(--primary-dark); font-size: 13px; font-weight: 600; }
.article-detail-layout aside p { margin: 25px 0 0; color: var(--muted); font-size: 11px; line-height: 1.8; }
.article-prose { min-width: 0; color: #48524f; font-size: 17px; line-height: 1.95; }
.article-prose > :first-child { margin-top: 0; }
.article-prose h2 { margin: 2.1em 0 .75em; color: var(--ink-green); font-size: 31px; font-weight: 600; line-height: 1.4; }
.article-prose h3 { margin: 1.8em 0 .65em; color: var(--primary-dark); font-size: 23px; font-weight: 600; }
.article-prose p, .article-prose ul, .article-prose ol { margin-bottom: 1.35em; }
.article-prose ul, .article-prose ol { padding-left: 1.4em; }
.article-prose strong { color: var(--ink-green); }
.article-prose a { color: var(--primary-dark); text-decoration: underline; text-underline-offset: 3px; }
.article-prose blockquote { margin: 1.7em 0; padding: 20px 24px; color: var(--ink-green); background: var(--secondary-light); border-left: 3px solid var(--primary); }
.article-prose img { margin: 32px auto; border-radius: 16px; }
.article-prose code { padding: 2px 6px; background: var(--secondary-light); border-radius: 4px; font-size: .9em; }
[data-reveal] { opacity: 0; transform: translateY(24px); transition: opacity .7s ease, transform .7s ease; } [data-reveal] { opacity: 0; transform: translateY(24px); transition: opacity .7s ease, transform .7s ease; }
[data-reveal].is-visible { opacity: 1; transform: none; } [data-reveal].is-visible { opacity: 1; transform: none; }
@media (prefers-reduced-motion: reduce) { @media (prefers-reduced-motion: reduce) {
...@@ -478,12 +524,14 @@ section[id], .faq-item[id] { scroll-margin-top: 112px; } ...@@ -478,12 +524,14 @@ section[id], .faq-item[id] { scroll-margin-top: 112px; }
@media (max-width: 1050px) { @media (max-width: 1050px) {
.site-header__inner { grid-template-columns: 150px 1fr auto; gap: 18px; } .site-header__inner { grid-template-columns: 150px 1fr auto; gap: 18px; }
.desktop-nav > ul { gap: 17px; } .desktop-nav > ul { gap: 12px; }
.nav-link { font-size: 13px; } .nav-link { font-size: 13px; }
.header-cta { display: none; } .header-cta { display: none; }
.services-layout, .faq-layout { grid-template-columns: 290px 1fr; gap: 45px; } .services-layout, .faq-layout { grid-template-columns: 290px 1fr; gap: 45px; }
.support-grid { grid-template-columns: repeat(2, 1fr); } .support-grid { grid-template-columns: repeat(2, 1fr); }
.join-flow { grid-template-columns: repeat(3, 1fr); } .join-flow { grid-template-columns: repeat(3, 1fr); }
.article-grid { grid-template-columns: repeat(2, minmax(0, 1fr)); }
.article-detail-layout { grid-template-columns: 190px minmax(0, 1fr); gap: 46px; }
.footer-grid { grid-template-columns: 1.3fr .8fr .9fr; } .footer-grid { grid-template-columns: 1.3fr .8fr .9fr; }
.footer-contact { grid-column: 2 / -1; } .footer-contact { grid-column: 2 / -1; }
} }
...@@ -523,6 +571,8 @@ section[id], .faq-item[id] { scroll-margin-top: 112px; } ...@@ -523,6 +571,8 @@ section[id], .faq-item[id] { scroll-margin-top: 112px; }
.value-card h3 { margin-top: 50px; } .value-card h3 { margin-top: 50px; }
.contact-grid { grid-template-columns: 1fr; } .contact-grid { grid-template-columns: 1fr; }
.contact-card { min-height: 220px; } .contact-card { min-height: 220px; }
.article-detail-layout { grid-template-columns: 1fr; gap: 38px; }
.article-detail-layout aside { position: static; }
} }
@media (max-width: 560px) { @media (max-width: 560px) {
...@@ -557,6 +607,14 @@ section[id], .faq-item[id] { scroll-margin-top: 112px; } ...@@ -557,6 +607,14 @@ section[id], .faq-item[id] { scroll-margin-top: 112px; }
.page-hero h1 { font-size: 48px; } .page-hero h1 { font-size: 48px; }
.page-hero p { font-size: 16px; } .page-hero p { font-size: 16px; }
.detail-card { grid-template-columns: 1fr; gap: 20px; padding: 26px; } .detail-card { grid-template-columns: 1fr; gap: 20px; padding: 26px; }
.article-grid { grid-template-columns: 1fr; }
.article-card, .article-card > a { min-height: 340px; }
.article-detail-head { padding: 68px 0 62px; }
.article-detail-head h1 { font-size: 42px; }
.article-detail-head p { font-size: 16px; }
.article-detail-layout { padding-top: 58px; padding-bottom: 78px; }
.article-prose { font-size: 16px; }
.article-prose h2 { font-size: 27px; }
.detail-card__number { font-size: 34px; } .detail-card__number { font-size: 34px; }
.detail-facts { grid-template-columns: 1fr; } .detail-facts { grid-template-columns: 1fr; }
.process-grid { grid-template-columns: 1fr; } .process-grid { grid-template-columns: 1fr; }
......
Markdown is supported
0% or
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!
Please register or to comment