liufumingren 434b5d38a8 style(doc-site): 文档站去掉页脚与 1440px 限宽
Co-authored-by: Copilot <223556219+Copilot@users.noreply.github.com>
2026-11-16 02:43:31 +08:00

620 lines
20 KiB
JavaScript
Raw Permalink 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 { DocSection, DocArticle } = this.app.model;
const order = [ [ 'sort', 'ASC' ], [ 'id', 'ASC' ] ];
const [ sections, articles ] = await Promise.all([
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);
}
return sections.map(section => ({
id: Number(section.id),
code: section.code,
name: section.name,
description: section.description || '',
articles: articlesBySection.get(String(section.id)) || [],
})).filter(section => SAFE_SEGMENT.test(section.code));
}
/** 生成整站(页面 + sitemap),返回生成的文件相对路径列表 */
async generate(ctx) {
const model = await this.loadModel();
const base = this.baseUrl(ctx);
ensureDir(this.siteDir);
const written = [];
const firstSection = model[0] || null;
// `/doc/`:默认展示第一个栏目(没有栏目就展示空态)
writeFile(this.indexPath, this.renderPage({ model, base, active: firstSection, article: null }));
written.push('index.html');
for (const section of model) {
writeFile(
path.join(this.siteDir, section.code, 'index.html'),
this.renderPage({ model, base, active: section, article: null }),
);
written.push(`${section.code}/index.html`);
for (const article of section.articles) {
writeFile(
path.join(this.siteDir, section.code, `${article.slug}.html`),
this.renderPage({ model, base, active: section, article }),
);
written.push(`${section.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(section => section.code));
const slugsByCode = new Map(model.map(section => [ section.code, new Set(section.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 section of model) {
urls.push(`${base}/doc/${section.code}/`);
for (const article of section.articles) {
urls.push(`${base}/doc/${section.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(section => {
const isActive = active && section.code === active.code;
return `<a class="tab${isActive ? ' is-active' : ''}" href="/doc/${escape(section.code)}/">${escape(section.name)}</a>`;
}).join('');
}
/** 侧边栏:当前栏目下的内容页列表(不再分组,直接就是文章) */
renderSidebar(active, article) {
if (!active) return '<p class="side-empty">还没有文档栏目。</p>';
if (!active.articles.length) return '<p class="side-empty">这个栏目下还没有内容。</p>';
return `<ul>
${active.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>`;
}
/** 正文第一行如果就是文章标题(`# 标题`),去掉它:标题已经在页头渲染过了 */
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>
${toc.length ? `<nav class="doc-toc" aria-label="本页目录">
<div class="doc-toc__title">本页目录</div>
<ul>${toc.map(item => `<li class="lv-${item.level}"><a class="doc-toc__link" href="#${item.id}" data-toc-id="${item.id}">${escape(item.text)}</a></li>`).join('')}</ul>
</nav>` : ''}
<div class="doc-body">
${rendered.html}
</div>
${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>
${this.tocScript()}
</body>
</html>
`;
}
tocScript() {
return `<script>
(() => {
const content = document.querySelector('.content');
const toc = document.querySelector('.doc-toc');
if (!content || !toc) return;
const links = Array.from(toc.querySelectorAll('.doc-toc__link'));
const headings = links
.map(link => document.getElementById(link.dataset.tocId))
.filter(Boolean);
if (!headings.length) return;
let scheduled = false;
const updateActive = () => {
scheduled = false;
const root = content.getBoundingClientRect();
const threshold = root.top + Math.min(120, content.clientHeight * 0.2);
let active = headings[0];
for (const heading of headings) {
if (heading.getBoundingClientRect().top <= threshold) active = heading;
else break;
}
if (content.scrollTop + content.clientHeight >= content.scrollHeight - 2) {
active = headings[headings.length - 1];
}
links.forEach(link => {
const selected = link.dataset.tocId === active.id;
link.classList.toggle('is-active', selected);
if (selected) link.setAttribute('aria-current', 'location');
else link.removeAttribute('aria-current');
});
const activeLink = links.find(link => link.dataset.tocId === active.id);
if (activeLink) {
const tocRect = toc.getBoundingClientRect();
const linkRect = activeLink.getBoundingClientRect();
if (linkRect.top < tocRect.top) toc.scrollTop -= tocRect.top - linkRect.top;
else if (linkRect.bottom > tocRect.bottom) toc.scrollTop += linkRect.bottom - tocRect.bottom;
}
};
const scheduleUpdate = () => {
if (scheduled) return;
scheduled = true;
requestAnimationFrame(updateActive);
};
content.addEventListener('scroll', scheduleUpdate, { passive: true });
window.addEventListener('resize', scheduleUpdate, { passive: true });
window.addEventListener('load', scheduleUpdate, { once: true });
updateActive();
})();
</script>`;
}
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;
width: 100%;
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;
}
.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 300px 64px 40px;
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 {
position: fixed;
z-index: 20;
top: 76px;
right: 20px;
width: 260px;
max-height: calc(100vh - 96px);
overflow-y: auto;
padding: 14px 12px;
border: 1px solid var(--border);
border-radius: 10px;
background: var(--side-bg);
box-shadow: 0 8px 24px rgba(15, 23, 42, 0.08);
}
.doc-toc__title { font-size: 12px; letter-spacing: 0.08em; color: var(--text-muted); margin: 0 8px 8px; }
.doc-toc ul { list-style: none; margin: 0; padding: 0; }
.doc-toc li { margin: 2px 0; font-size: 13px; }
.doc-toc__link {
display: block;
padding: 5px 8px;
border-radius: 6px;
color: #475569;
line-height: 1.5;
transition: background-color 0.15s ease, color 0.15s ease;
}
.doc-toc__link:hover { background: var(--brand-soft); text-decoration: none; }
.doc-toc__link.is-active { background: var(--brand); color: #fff; font-weight: 600; }
.doc-toc .lv-3 { padding-left: 14px; }
.doc-toc .lv-4 { padding-left: 28px; }
.doc-body h2,
.doc-body h3,
.doc-body h4 { scroll-margin-top: 20px; }
.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); }
@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 280px 48px 20px; }
.doc-head h1 { font-size: 24px; }
}
@media (max-width: 860px) {
.content { padding-right: 20px; }
.doc-toc {
position: static;
width: auto;
max-height: none;
overflow: visible;
margin: 0 0 24px;
box-shadow: none;
}
}
/* 打印时恢复自然文档流,避免长文被固定高度裁掉 */
@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; }
.doc-toc { position: static; width: auto; max-height: none; box-shadow: none; }
}
`;
}
}
module.exports = DocSiteService;