liufumingren 0bb288dc86 style(doc): 文档页面不再整体滚动,滚动条仅出现在侧边栏与正文区
- body 固定视口高度、flex 纵向布局并 overflow:hidden,页面级滚动条移除,sidebar/content 各自独立滚动(含移动端 40vh 侧边栏)

- 标题下显示创建时间(创建于),正文末尾显示最后更新时间(新增 .doc-foot 样式)

- 新增 @media print,打印时恢复自然文档流避免长文被固定高度裁切

Co-authored-by: Copilot <223556219+Copilot@users.noreply.github.com>
2026-11-09 15:32:53 +08:00

571 lines
18 KiB
JavaScript
Raw Blame History

This file contains ambiguous Unicode characters

This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.

'use strict';
const fs = require('fs');
const path = require('path');
const { Service } = require('egg');
const markdown = require('../lib/markdown');
const SITE_NAME = '云仓视频溯源';
/** 目录 / 文件名只允许安全的 ASCII:分类 code、文章 slug 都按这个校验 */
const SAFE_SEGMENT = /^[a-z0-9][a-z0-9_-]{0,63}$/;
function ensureDir(dir) {
fs.mkdirSync(dir, { recursive: true });
}
function writeFile(file, content) {
ensureDir(path.dirname(file));
fs.writeFileSync(file, content, 'utf8');
}
function escape(value) {
return markdown.escapeHtml(value);
}
/** 日期只留 YYYY-MM-DD */
function dateOnly(value) {
if (!value) return '';
const date = value instanceof Date ? value : new Date(value);
if (Number.isNaN(date.getTime())) return '';
return date.toISOString().slice(0, 10);
}
/**
* 文档站生成器(`/doc/**` 的静态 HTML + `/sitemap.txt`)
*
* 设计取舍:
* - **静态优先**:每次内容变更(增删改分类 / 栏目 / 文章)整站重写一遍,文章量级小(几十篇)足够快;
* - 首次访问 / 部署后文件不存在时 **按需生成**(`ensureSite`),不依赖启动钩子;
* - 生成目录放在 `run/doc-site`(不进仓库),由 `controller/web/doc.js` 直接读文件返回。
*/
class DocSiteService extends Service {
get siteDir() {
return this.app.config.docSite.dir;
}
get indexPath() {
return path.join(this.siteDir, 'index.html');
}
get sitemapPath() {
return path.join(this.siteDir, 'sitemap.txt');
}
/** 站点根地址(sitemap 用绝对地址):优先配置,其次当前请求的 origin */
baseUrl(ctx) {
const configured = (this.app.config.docSite && this.app.config.docSite.baseUrl) || '';
if (configured) return String(configured).replace(/\/+$/, '');
const origin = ctx && ctx.origin ? String(ctx.origin) : '';
return origin.replace(/\/+$/, '');
}
/** 已发布的分类 → 栏目 → 文章(仅 status=1,按 sort 排序) */
async loadModel() {
const { DocCategory, DocSection, DocArticle } = this.app.model;
const order = [ [ 'sort', 'ASC' ], [ 'id', 'ASC' ] ];
const [ categories, sections, articles ] = await Promise.all([
DocCategory.findAll({ where: { status: 1 }, order }),
DocSection.findAll({ where: { status: 1 }, order }),
DocArticle.findAll({ where: { status: 1 }, order }),
]);
const articlesBySection = new Map();
for (const article of articles) {
const key = String(article.sectionId);
if (!articlesBySection.has(key)) articlesBySection.set(key, []);
articlesBySection.get(key).push(article);
}
const sectionsByCategory = new Map();
for (const section of sections) {
const key = String(section.categoryId);
if (!sectionsByCategory.has(key)) sectionsByCategory.set(key, []);
sectionsByCategory.get(key).push(section);
}
return categories.map(category => {
const ownSections = sectionsByCategory.get(String(category.id)) || [];
const groups = ownSections.map(section => ({
id: Number(section.id),
name: section.name,
articles: articlesBySection.get(String(section.id)) || [],
})).filter(group => group.articles.length > 0);
return {
id: Number(category.id),
code: category.code,
name: category.name,
description: category.description || '',
groups,
articles: groups.reduce((all, group) => all.concat(group.articles), []),
};
}).filter(category => SAFE_SEGMENT.test(category.code));
}
/** 生成整站(页面 + sitemap),返回生成的文件相对路径列表 */
async generate(ctx) {
const model = await this.loadModel();
const base = this.baseUrl(ctx);
ensureDir(this.siteDir);
const written = [];
const firstCategory = model[0] || null;
// `/doc/`:默认展示第一个分类(没有分类就展示空态)
writeFile(this.indexPath, this.renderPage({ model, base, active: firstCategory, article: null }));
written.push('index.html');
for (const category of model) {
writeFile(
path.join(this.siteDir, category.code, 'index.html'),
this.renderPage({ model, base, active: category, article: null }),
);
written.push(`${category.code}/index.html`);
for (const article of category.articles) {
writeFile(
path.join(this.siteDir, category.code, `${article.slug}.html`),
this.renderPage({ model, base, active: category, article }),
);
written.push(`${category.code}/${article.slug}.html`);
}
}
this.prune(model);
this.writeSitemap(this.buildSitemapUrls(model, base));
return written;
}
/** 文件不存在就生成(部署后第一次访问 / 清缓存后) */
async ensureSite(ctx) {
if (fs.existsSync(this.indexPath)) return;
await this.generate(ctx);
}
/** 删掉已经不该存在的目录 / 页面(分类改名、文章下架后不留旧链接) */
prune(model) {
const codes = new Set(model.map(category => category.code));
const slugsByCode = new Map(model.map(category => [ category.code, new Set(category.articles.map(article => `${article.slug}.html`)) ]));
for (const entry of fs.readdirSync(this.siteDir, { withFileTypes: true })) {
if (!entry.isDirectory()) continue;
if (!codes.has(entry.name)) {
fs.rmSync(path.join(this.siteDir, entry.name), { recursive: true, force: true });
continue;
}
const allow = slugsByCode.get(entry.name) || new Set();
for (const file of fs.readdirSync(path.join(this.siteDir, entry.name))) {
if (file === 'index.html') continue;
if (!allow.has(file)) fs.rmSync(path.join(this.siteDir, entry.name, file), { force: true });
}
}
}
/** 全站 URL:站点首页 + 文档站各级页面(顺序稳定,新增的排在最后) */
buildSitemapUrls(model, base) {
const urls = [ `${base}/`, `${base}/doc/` ];
for (const category of model) {
urls.push(`${base}/doc/${category.code}/`);
for (const article of category.articles) {
urls.push(`${base}/doc/${category.code}/${article.slug}.html`);
}
}
return urls;
}
/**
* 写 sitemap.txt:**已有顺序保持不变,新链接追加到末尾**(文章新增即"在尾部加入")。
* 已经不存在的 URL 会被清掉(下架 / 删除的文章不给搜索引擎留着)。
*/
writeSitemap(urls) {
const wanted = new Set(urls);
let existing = [];
try {
existing = fs.readFileSync(this.sitemapPath, 'utf8')
.split(/\r?\n/)
.map(line => line.trim())
.filter(Boolean);
} catch {
existing = [];
}
const kept = [];
const keptSet = new Set();
for (const url of existing) {
if (!wanted.has(url) || keptSet.has(url)) continue;
kept.push(url);
keptSet.add(url);
}
const appended = urls.filter(url => !keptSet.has(url));
writeFile(this.sitemapPath, `${kept.concat(appended).join('\n')}\n`);
}
/** 单个文件在磁盘上的位置(拒绝 `..` 越界) */
resolveFile(relative) {
const clean = String(relative || '').replace(/^\/+/, '').replace(/\\/g, '/');
const target = path.resolve(this.siteDir, clean);
const root = path.resolve(this.siteDir);
if (target !== root && !target.startsWith(`${root}${path.sep}`)) return null;
return target;
}
// ---------------- 渲染 ----------------
/** 顶部 tab(分类全量展示,全局可切换) */
renderTabs(model, active) {
return model.map(category => {
const isActive = active && category.code === active.code;
return `<a class="tab${isActive ? ' is-active' : ''}" href="/doc/${escape(category.code)}/">${escape(category.name)}</a>`;
}).join('');
}
/** 侧边栏:当前分类下的「栏目 → 内容页」 */
renderSidebar(active, article) {
if (!active) return '<p class="side-empty">还没有文档分类。</p>';
if (!active.groups.length) return '<p class="side-empty">这个分类下还没有内容。</p>';
return active.groups.map(group => `
<div class="side-group">
<div class="side-group__title">${escape(group.name)}</div>
<ul>
${group.articles.map(item => {
const href = `/doc/${escape(active.code)}/${escape(item.slug)}.html`;
const isActive = article && Number(article.id) === Number(item.id);
return `<li><a class="side-link${isActive ? ' is-active' : ''}" href="${href}">${escape(item.title)}</a></li>`;
}).join('')}
</ul>
</div>`).join('');
}
/** 正文第一行如果就是文章标题(`# 标题`),去掉它:标题已经在页头渲染过了 */
stripLeadingTitle(content, title) {
const source = String(content || '');
const lines = source.split('\n');
const first = (lines[0] || '').trim();
if (first === `# ${String(title || '').trim()}`) return lines.slice(1).join('\n');
return source;
}
/** 文章正文(分类首页展示该分类第一篇文章) */
renderBody(active, article) {
if (!active) {
return `<div class="empty">
<h1>${SITE_NAME} · 文档</h1>
<p>文档站还没有内容。平台管理员可以在「平台管理 → 文档管理」里新建分类与内容页。</p>
</div>`;
}
const current = article || active.articles[0] || null;
if (!current) {
return `<div class="empty">
<h1>${escape(active.name)}</h1>
<p>${escape(active.description || '这个分类下还没有已发布的内容。')}</p>
</div>`;
}
const rendered = markdown.render(this.stripLeadingTitle(current.content, current.title));
const toc = rendered.toc.filter(item => item.level >= 2 && item.level <= 4);
const created = dateOnly(current.createdAt || current.created_at);
const updated = dateOnly(current.updatedAt || current.updated_at);
const summary = current.summary || markdown.plainText(current.content, 140);
return `<article class="doc">
<header class="doc-head">
<h1>${escape(current.title)}</h1>
${summary ? `<p class="doc-summary">${escape(summary)}</p>` : ''}
${created ? `<p class="doc-meta">创建于:${created}</p>` : ''}
</header>
<div class="doc-body">
${rendered.html}
</div>
${toc.length ? `<nav class="doc-toc">
<div class="doc-toc__title">本页目录</div>
<ul>${toc.map(item => `<li class="lv-${item.level}"><a href="#${item.id}">${escape(item.text)}</a></li>`).join('')}</ul>
</nav>` : ''}
${updated ? `<p class="doc-foot">最后更新:${updated}</p>` : ''}
</article>`;
}
renderPage({ model, base, active, article }) {
const current = article || (active && active.articles[0]) || null;
const pagePath = current && active
? `/doc/${active.code}/${current.slug}.html`
: active ? `/doc/${active.code}/` : '/doc/';
const title = current ? `${current.title} · ${active.name}` : active ? active.name : '文档';
const description = (current && current.summary)
|| (active && active.description)
|| `${SITE_NAME} 使用文档`;
return `<!DOCTYPE html>
<html lang="zh-CN">
<head>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1">
<title>${escape(title)} · ${SITE_NAME}</title>
<meta name="description" content="${escape(description)}">
<link rel="canonical" href="${escape(base)}${escape(pagePath)}">
<style>
${this.styles()}
</style>
</head>
<body>
<header class="topbar">
<a class="brand" href="/doc/">
<span class="brand-dot" aria-hidden="true"></span>
${SITE_NAME} · 文档
</a>
<nav class="tabs" aria-label="文档分类">${this.renderTabs(model, active)}</nav>
<a class="back" href="/">返回控制台 →</a>
</header>
<div class="layout">
<aside class="sidebar">
${active ? `<div class="side-head">${escape(active.name)}</div>` : ''}
${this.renderSidebar(active, current)}
</aside>
<main class="content">
${this.renderBody(active, current)}
</main>
</div>
<footer class="footer">
<span>${SITE_NAME} · 文档由「平台管理 → 文档管理」维护</span>
</footer>
</body>
</html>
`;
}
styles() {
return `
:root {
--brand: #2563eb;
--brand-soft: rgba(37, 99, 235, 0.08);
--text: #1f2937;
--text-muted: #64748b;
--border: #e5e7eb;
--side-bg: #f8fafc;
--code-bg: #0f172a;
}
* { box-sizing: border-box; }
html, body { margin: 0; padding: 0; height: 100%; }
body {
font-family: -apple-system, BlinkMacSystemFont, "Segoe UI", "PingFang SC", "Microsoft YaHei", sans-serif;
color: var(--text);
background: #fff;
line-height: 1.75;
font-size: 15px;
/* 页面本身不滚动,滚动条只出现在侧边栏与正文区 */
display: flex;
flex-direction: column;
height: 100%;
overflow: hidden;
}
a { color: var(--brand); text-decoration: none; }
a:hover { text-decoration: underline; }
.topbar {
position: relative;
z-index: 10;
flex: 0 0 auto;
display: flex;
align-items: center;
gap: 16px;
padding: 0 20px;
height: 56px;
background: rgba(255, 255, 255, 0.94);
backdrop-filter: blur(8px);
border-bottom: 1px solid var(--border);
}
.brand {
display: inline-flex;
align-items: center;
gap: 8px;
font-weight: 700;
color: var(--text);
white-space: nowrap;
}
.brand-dot {
width: 10px; height: 10px; border-radius: 50%;
background: linear-gradient(135deg, #24bbcd, #2563eb);
box-shadow: 0 0 0 4px rgba(37, 99, 235, 0.12);
}
.tabs {
display: flex;
align-items: center;
gap: 4px;
flex: 1 1 auto;
min-width: 0;
overflow-x: auto;
scrollbar-width: none;
}
.tabs::-webkit-scrollbar { display: none; }
.tab {
padding: 6px 12px;
border-radius: 999px;
color: #475569;
font-size: 13px;
white-space: nowrap;
}
.tab:hover { background: var(--brand-soft); text-decoration: none; }
.tab.is-active { background: var(--brand); color: #fff; }
.tab.is-active:hover { background: var(--brand); }
.back { font-size: 13px; color: var(--text-muted); white-space: nowrap; }
.layout {
display: grid;
grid-template-columns: 248px minmax(0, 1fr);
grid-template-rows: minmax(0, 1fr);
flex: 1 1 auto;
max-width: 1440px;
width: 100%;
margin: 0 auto;
min-height: 0;
overflow: hidden;
}
.sidebar {
padding: 24px 16px 40px;
background: var(--side-bg);
border-right: 1px solid var(--border);
min-height: 0;
overflow-y: auto;
overscroll-behavior: contain;
}
.side-head {
font-size: 12px;
letter-spacing: 0.08em;
text-transform: uppercase;
color: var(--text-muted);
margin: 0 6px 14px;
}
.side-group { margin-bottom: 18px; }
.side-group__title {
font-size: 12px;
font-weight: 700;
color: #334155;
margin: 0 6px 6px;
}
.sidebar ul { list-style: none; margin: 0; padding: 0; }
.side-link {
display: block;
padding: 5px 10px;
border-radius: 8px;
font-size: 13.5px;
color: #334155;
line-height: 1.5;
}
.side-link:hover { background: rgba(37, 99, 235, 0.08); text-decoration: none; }
.side-link.is-active { background: var(--brand); color: #fff; }
.side-empty { color: var(--text-muted); font-size: 13px; padding: 0 6px; }
.content {
padding: 32px 40px 64px;
min-width: 0;
min-height: 0;
overflow-y: auto;
overscroll-behavior: contain;
}
.doc { max-width: 820px; }
.doc-head h1 { font-size: 30px; line-height: 1.35; margin: 0 0 8px; }
.doc-summary { margin: 0 0 6px; color: var(--text-muted); }
.doc-meta { margin: 0 0 24px; font-size: 12.5px; color: #94a3b8; }
.doc-body h2 { font-size: 22px; margin: 36px 0 12px; padding-bottom: 6px; border-bottom: 1px solid var(--border); }
.doc-body h3 { font-size: 18px; margin: 28px 0 10px; }
.doc-body h4 { font-size: 16px; margin: 24px 0 8px; }
.doc-body p { margin: 0 0 14px; }
.doc-body ul, .doc-body ol { margin: 0 0 16px; padding-left: 22px; }
.doc-body li { margin: 4px 0; }
.doc-body code {
font-family: ui-monospace, SFMono-Regular, Consolas, "Liberation Mono", monospace;
font-size: 0.9em;
background: #f1f5f9;
border: 1px solid var(--border);
border-radius: 4px;
padding: 1px 5px;
}
.doc-body pre {
background: var(--code-bg);
color: #e2e8f0;
border-radius: 10px;
padding: 16px 18px;
overflow-x: auto;
margin: 0 0 18px;
}
.doc-body pre code { background: transparent; border: 0; padding: 0; color: inherit; }
.doc-body blockquote {
margin: 0 0 18px;
padding: 10px 16px;
border-left: 3px solid var(--brand);
background: var(--brand-soft);
border-radius: 0 8px 8px 0;
color: #334155;
}
.doc-body hr { border: 0; border-top: 1px solid var(--border); margin: 28px 0; }
.doc-body a { word-break: break-word; }
.doc-toc {
margin-top: 40px;
padding: 16px 18px;
border: 1px solid var(--border);
border-radius: 10px;
background: var(--side-bg);
max-width: 820px;
}
.doc-toc__title { font-size: 12px; letter-spacing: 0.08em; color: var(--text-muted); margin-bottom: 8px; }
.doc-toc ul { list-style: none; margin: 0; padding: 0; }
.doc-toc li { margin: 3px 0; font-size: 13.5px; }
.doc-toc .lv-3 { padding-left: 14px; }
.doc-toc .lv-4 { padding-left: 28px; }
.doc-foot {
max-width: 820px;
margin: 32px 0 0;
padding-top: 16px;
border-top: 1px solid var(--border);
font-size: 12.5px;
color: #94a3b8;
}
.empty { max-width: 720px; }
.empty h1 { font-size: 26px; }
.empty p { color: var(--text-muted); }
.footer {
flex: 0 0 auto;
border-top: 1px solid var(--border);
padding: 20px;
text-align: center;
font-size: 12.5px;
color: #94a3b8;
}
@media (max-width: 900px) {
.layout {
grid-template-columns: minmax(0, 1fr);
grid-template-rows: minmax(0, auto) minmax(0, 1fr);
}
.sidebar {
max-height: 40vh;
border-right: 0;
border-bottom: 1px solid var(--border);
padding: 16px 16px 20px;
}
.content { padding: 24px 20px 48px; }
.doc-head h1 { font-size: 24px; }
}
/* 打印时恢复自然文档流,避免长文被固定高度裁掉 */
@media print {
html, body { height: auto; overflow: visible; }
body { display: block; }
.topbar { position: static; }
.layout { display: block; overflow: visible; min-height: 0; }
.sidebar, .content { overflow: visible; max-height: none; height: auto; }
}
`;
}
}
module.exports = DocSiteService;