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",
}); });
This diff is collapsed.
...@@ -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",
......
This diff is collapsed.
This diff is collapsed.
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: "关于我们",
......
This diff is collapsed.
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