- layout 三栏: 左 sticky 目录(224px,滚动高亮+点击锚点) + 正文(940px) + 右 sticky 更多教程(256px) - 底部「更多教程」区块移至右侧固定浮动 - 正文排版全面加大间距: h2 52px上边距+底部分隔线, 段落20px, 列表10px, blockquote/表格/代码块统一美化 - 锚点 scroll-margin-top 让开 60px fixed 导航 - <1280px 回退单栏: 目录隐藏, 更多教程回正文下方全宽
229 lines
7.4 KiB
TypeScript
229 lines
7.4 KiB
TypeScript
/**
|
||
* 文章详情页(/article/:slug)
|
||
*
|
||
* 断网可用:正文与索引都是同源静态文件(public/articles/),不依赖任何外部服务。
|
||
* 内容组织见 docs/断网可用改造.md 的「详情页与 slug 规范」小节:
|
||
* - 正文:public/articles/<slug>.md
|
||
* - 索引:public/articles/index.json(id 必须等于 slug)
|
||
* - slug:^[a-z0-9]+(?:-[a-z0-9]+)*$,≤64 字符
|
||
*
|
||
* 版式:左侧浮动目录(锚点快速定位 + 滚动高亮)+ 中间正文 + 右侧浮动「更多教程」,
|
||
* 两侧面板 position: sticky 固定显示;窄屏(≤1280px)自动收起为单栏。
|
||
*/
|
||
import { useEffect, useMemo, useRef, useState } from 'react';
|
||
import { Link, useParams } from 'react-router-dom';
|
||
import ReactMarkdown from 'react-markdown';
|
||
import SubHeader from '@components/header/Header';
|
||
import Footer from '@components/footer/Footer';
|
||
import { language } from '@language/language';
|
||
import styles from './article.module.less';
|
||
|
||
export const SLUG_RE = /^[a-z0-9]+(?:-[a-z0-9]+)*$/;
|
||
export const SLUG_MAX = 64;
|
||
|
||
interface ArticleMeta {
|
||
id: string;
|
||
title: string;
|
||
description?: string;
|
||
date?: string;
|
||
tags?: string[];
|
||
}
|
||
|
||
interface TocItem {
|
||
id: string;
|
||
text: string;
|
||
level: 2 | 3;
|
||
}
|
||
|
||
/** 标题文本 → 锚点 id:小写、空白转连字符、仅保留字母数字(含中文)与连字符 */
|
||
function slugify(s: string): string {
|
||
return (
|
||
s
|
||
.trim()
|
||
.toLowerCase()
|
||
.replace(/\s+/g, '-')
|
||
.replace(/[^\p{L}\p{N}-]/gu, '')
|
||
.replace(/-{2,}/g, '-')
|
||
.replace(/^-+|-+$/g, '') || 'section'
|
||
);
|
||
}
|
||
|
||
function ArticleDetail() {
|
||
const { slug } = useParams<{ slug: string }>();
|
||
const [meta, setMeta] = useState<ArticleMeta | null>(null);
|
||
const [list, setList] = useState<ArticleMeta[]>([]);
|
||
const [md, setMd] = useState<string>('');
|
||
const [state, setState] = useState<'loading' | 'ok' | 'notfound' | 'badslug'>('loading');
|
||
const [toc, setToc] = useState<TocItem[]>([]);
|
||
const [active, setActive] = useState<string>('');
|
||
const articleRef = useRef<HTMLElement | null>(null);
|
||
|
||
const valid = useMemo(() => !!slug && slug.length <= SLUG_MAX && SLUG_RE.test(slug), [slug]);
|
||
|
||
useEffect(() => {
|
||
if (!valid) {
|
||
setState('badslug');
|
||
return;
|
||
}
|
||
let alive = true;
|
||
setState('loading');
|
||
|
||
fetch('/articles/index.json')
|
||
.then(r => (r.ok ? r.json() : []))
|
||
.then((arr: ArticleMeta[]) => {
|
||
if (!alive) return;
|
||
const all = Array.isArray(arr) ? arr : [];
|
||
setList(all);
|
||
const found = all.find(d => d.id === slug);
|
||
if (!found) {
|
||
setState('notfound');
|
||
return null;
|
||
}
|
||
setMeta(found);
|
||
return fetch('/articles/' + slug + '.md').then(r => (r.ok ? r.text() : ''));
|
||
})
|
||
.then(text => {
|
||
if (!alive) return;
|
||
if (typeof text === 'string') setMd(text);
|
||
setState(s => (s === 'loading' ? 'ok' : s));
|
||
})
|
||
.catch(() => alive && setState('notfound'));
|
||
|
||
return () => {
|
||
alive = false;
|
||
};
|
||
}, [slug, valid]);
|
||
|
||
// 正文渲染完成后:给 h2/h3 挂锚点 id,并生成左侧目录
|
||
useEffect(() => {
|
||
if (state !== 'ok' || !md) return;
|
||
const root = articleRef.current;
|
||
if (!root) return;
|
||
const heads = Array.from(root.querySelectorAll<HTMLElement>('h2, h3'));
|
||
const seen: Record<string, number> = {};
|
||
const items: TocItem[] = heads.map(el => {
|
||
const base = slugify(el.textContent || '');
|
||
const n = (seen[base] = (seen[base] || 0) + 1);
|
||
const id = n > 1 ? `${base}-${n}` : base;
|
||
el.id = id;
|
||
return { id, text: (el.textContent || '').trim(), level: el.tagName === 'H3' ? 3 : 2 };
|
||
});
|
||
setToc(items);
|
||
setActive(items[0]?.id || '');
|
||
// 带锚点进入(/article/xxx#heading)时直接定位
|
||
if (location.hash) {
|
||
const target = document.getElementById(decodeURIComponent(location.hash.slice(1)));
|
||
if (target) requestAnimationFrame(() => target.scrollIntoView({ block: 'start' }));
|
||
}
|
||
}, [md, state]);
|
||
|
||
// 滚动时高亮目录当前节(rAF 节流)
|
||
useEffect(() => {
|
||
if (!toc.length) return;
|
||
let raf = 0;
|
||
const onScroll = () => {
|
||
if (raf) return;
|
||
raf = requestAnimationFrame(() => {
|
||
raf = 0;
|
||
const y = window.scrollY + 140;
|
||
let cur = toc[0].id;
|
||
for (const t of toc) {
|
||
const el = document.getElementById(t.id);
|
||
if (!el) continue;
|
||
if (el.getBoundingClientRect().top + window.scrollY <= y) cur = t.id;
|
||
else break;
|
||
}
|
||
setActive(prev => (prev === cur ? prev : cur));
|
||
});
|
||
};
|
||
onScroll();
|
||
window.addEventListener('scroll', onScroll, { passive: true });
|
||
return () => {
|
||
window.removeEventListener('scroll', onScroll);
|
||
if (raf) cancelAnimationFrame(raf);
|
||
};
|
||
}, [toc]);
|
||
|
||
const goTo = (e: React.MouseEvent, id: string) => {
|
||
e.preventDefault();
|
||
const el = document.getElementById(id);
|
||
if (!el) return;
|
||
setActive(id);
|
||
el.scrollIntoView({ behavior: 'smooth', block: 'start' });
|
||
history.replaceState(null, '', '#' + id);
|
||
};
|
||
|
||
const others = list.filter(d => d.id !== slug).slice(0, 6);
|
||
|
||
return (
|
||
<div className={styles.page}>
|
||
<SubHeader
|
||
title={meta?.title || (state === 'badslug' ? '链接无效' : '米剪 教程')}
|
||
desc={meta?.description || language.val('common_company')}
|
||
/>
|
||
<div className={styles.layout}>
|
||
{toc.length > 0 && (
|
||
<nav className={styles.toc} aria-label="文章目录">
|
||
<div className={styles.tocTitle}>目录</div>
|
||
<ul className={styles.tocList}>
|
||
{toc.map(t => (
|
||
<li key={t.id} className={t.level === 3 ? styles.lvl3 : undefined}>
|
||
<a
|
||
href={'#' + t.id}
|
||
className={active === t.id ? styles.active : undefined}
|
||
onClick={e => goTo(e, t.id)}
|
||
>
|
||
{t.text}
|
||
</a>
|
||
</li>
|
||
))}
|
||
</ul>
|
||
</nav>
|
||
)}
|
||
|
||
<div className={styles.main}>
|
||
{state === 'loading' && <p className={styles.tip}>加载中…</p>}
|
||
|
||
{state === 'badslug' && (
|
||
<div className={styles.tip}>
|
||
<p>这个地址不符合文章链接规则(只允许小写字母、数字和连字符)。</p>
|
||
<Link to="/">回到首页</Link>
|
||
</div>
|
||
)}
|
||
|
||
{state === 'notfound' && (
|
||
<div className={styles.tip}>
|
||
<p>没有找到这篇文章:{slug}</p>
|
||
<Link to="/">回到首页</Link>
|
||
</div>
|
||
)}
|
||
|
||
{(state === 'ok' || (state === 'loading' && md)) && (
|
||
<article className={styles.article} ref={articleRef}>
|
||
{meta?.date && <p className={styles.meta}>更新于 {meta.date}</p>}
|
||
<ReactMarkdown className={styles.md}>{md}</ReactMarkdown>
|
||
</article>
|
||
)}
|
||
</div>
|
||
|
||
{others.length > 0 && (
|
||
<aside className={styles.related}>
|
||
<h3>更多教程</h3>
|
||
<ul>
|
||
{others.map(d => (
|
||
<li key={d.id}>
|
||
<Link to={'/article/' + d.id}>{d.title}</Link>
|
||
{d.description ? <span className={styles.desc}>{d.description}</span> : null}
|
||
</li>
|
||
))}
|
||
</ul>
|
||
</aside>
|
||
)}
|
||
</div>
|
||
<Footer />
|
||
</div>
|
||
);
|
||
}
|
||
|
||
export default ArticleDetail;
|