Files
astro-jiao77.cn/src/components/common/TOCSidebar.astro
2025-10-01 09:51:06 +08:00

841 lines
21 KiB
Plaintext

---
export interface Props {
title?: string;
toggleLabel?: string;
targetSelector?: string;
}
const {
title = '目录',
toggleLabel = '目录',
targetSelector = '[data-report-content]'
} = Astro.props;
const sidebarId = `toc-sidebar-${Math.random().toString(36).slice(2, 10)}`;
---
<!-- 侧边栏容器 -->
<aside id={sidebarId} class="toc-sidebar" data-toc-sidebar aria-hidden="false" data-target-selector={targetSelector}>
<!-- 切换按钮 -->
<button class="toc-toggle" type="button" aria-label={toggleLabel} data-toc-toggle>
<svg class="toc-toggle__icon" viewBox="0 0 24 24" width="20" height="20">
<path fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round" d="M3 12h18M3 6h18M3 18h18"/>
</svg>
<span class="toc-toggle__label">{toggleLabel}</span>
</button>
<!-- 背景遮罩 (仅移动端) -->
<div class="toc-backdrop" data-toc-backdrop></div>
<!-- 侧边栏面板 -->
<div class="toc-panel" data-toc-panel>
<header class="toc-header">
<h3 class="toc-title">{title}</h3>
<button class="toc-close" type="button" aria-label="关闭目录" data-toc-close>
<svg viewBox="0 0 24 24" width="18" height="18">
<path fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round" d="M18 6L6 18M6 6l12 12"/>
</svg>
</button>
</header>
<nav class="toc-nav">
<ul class="toc-list" data-toc-list></ul>
</nav>
</div>
</aside>
<script is:inline define:vars={{ sidebarId, targetSelector }}>
// @ts-nocheck
// 变量由 Astro define:vars 注入: sidebarId, targetSelector
const __initTOC = () => {
const sidebar = document.getElementById(sidebarId);
if (!sidebar) return;
const tocList = sidebar.querySelector('[data-toc-list]');
const toggleBtn = sidebar.querySelector('[data-toc-toggle]');
const closeBtn = sidebar.querySelector('[data-toc-close]');
const backdrop = sidebar.querySelector('[data-toc-backdrop]');
const panel = sidebar.querySelector('[data-toc-panel]');
if (!tocList || !toggleBtn || !closeBtn || !backdrop || !panel) return;
// 响应式断点
const mediaQuery = window.matchMedia('(min-width: 1024px)');
// 生成ID的工具函数
const generateId = (text) => {
return text.toLowerCase()
.replace(/[\p{Extended_Pictographic}\u2600-\u27BF]/gu, '') // 移除emoji
.replace(/[^\w\u4e00-\u9fa5\s-]/g, '') // 保留文字、数字、中文、空格、连字符
.replace(/\s+/g, '-')
.replace(/-+/g, '-')
.replace(/^-+|-+$/g, '');
};
// 构建目录树
const buildTOC = () => {
const targetRoot = document.querySelector(targetSelector) || document.body;
const headings = Array.from(targetRoot.querySelectorAll('h2, h3, h4'))
.filter(h => h.textContent?.trim());
if (!headings.length) return;
// 为标题添加ID
const existingIds = new Set();
headings.forEach(heading => {
if (!heading.id) {
let baseId = generateId(heading.textContent.trim()) || 'section';
let finalId = baseId;
let counter = 1;
while (existingIds.has(finalId) || document.getElementById(finalId)) {
finalId = `${baseId}-${counter++}`;
}
heading.id = finalId;
existingIds.add(finalId);
} else {
existingIds.add(heading.id);
}
});
// 构建嵌套结构
const tocData = [];
const stack = [];
headings.forEach(heading => {
const level = parseInt(heading.tagName.charAt(1));
const text = heading.textContent.trim();
const id = heading.id;
const item = {
level,
text,
id,
children: []
};
// 找到合适的父级
while (stack.length > 0 && stack[stack.length - 1].level >= level) {
stack.pop();
}
if (stack.length === 0) {
tocData.push(item);
} else {
stack[stack.length - 1].children.push(item);
}
stack.push(item);
});
// 渲染TOC
renderTOC(tocData);
setupScrollSpy(headings);
};
// 渲染TOC HTML
const renderTOC = (items, isNested = false) => {
if (!items.length) return '';
const html = items.map(item => {
const hasChildren = item.children.length > 0;
const isCollapsed = item.level >= 4; // h4及以下默认折叠
return `
<li class="toc-item toc-item--level-${item.level}" data-level="${item.level}">
<div class="toc-item-content">
${hasChildren ?
`<button class="toc-expand" type="button" aria-expanded="${!isCollapsed}" data-expand>
<svg class="toc-expand-icon" viewBox="0 0 24 24" width="14" height="14">
<path fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round" d="M9 18l6-6-6-6"/>
</svg>
</button>` :
'<span class="toc-spacer"></span>'
}
<a href="#${item.id}" class="toc-link" data-target="${item.id}" data-level="${item.level}">
${item.text}
</a>
</div>
${hasChildren ?
`<ul class="toc-sublist ${isCollapsed ? 'toc-sublist--collapsed' : ''}">
${renderTOC(item.children, true)}
</ul>` : ''
}
</li>
`;
}).join('');
if (!isNested) {
tocList.innerHTML = html;
}
return html;
};
// 侧边栏状态管理 - 修复移动端问题
const setSidebarOpen = (isOpen) => {
sidebar.classList.toggle('toc-sidebar--open', isOpen);
sidebar.classList.toggle('toc-sidebar--closed', !isOpen);
sidebar.setAttribute('aria-hidden', String(!isOpen));
toggleBtn.setAttribute('aria-expanded', String(isOpen));
// 确保面板动画正确执行
if (!mediaQuery.matches) {
if (isOpen) {
panel.style.transform = 'translateY(0)';
requestAnimationFrame(() => {
panel.style.transform = 'translateY(0)';
});
} else {
panel.style.transform = 'translateY(100%)';
}
}
};
// 响应式处理
const handleMediaChange = () => {
if (mediaQuery.matches) {
// 桌面端:默认展开
setSidebarOpen(true);
sidebar.classList.add('toc-sidebar--desktop');
} else {
// 移动端:默认收起
setSidebarOpen(false);
sidebar.classList.remove('toc-sidebar--desktop');
}
};
// 事件监听 - 修复点击无效的问题
const handleToggleClick = (e) => {
e.preventDefault();
e.stopPropagation();
console.log('Toggle clicked'); // 调试用
const isOpen = sidebar.classList.contains('toc-sidebar--open');
setSidebarOpen(!isOpen);
};
const handleCloseClick = (e) => {
e.preventDefault();
e.stopPropagation();
console.log('Close clicked'); // 调试用
setSidebarOpen(false);
};
const handleBackdropClick = (e) => {
e.preventDefault();
e.stopPropagation();
setSidebarOpen(false);
};
// 强制重新绑定事件(移除可能存在的旧监听器)
const newToggleBtn = toggleBtn.cloneNode(true);
const newCloseBtn = closeBtn.cloneNode(true);
const newBackdrop = backdrop.cloneNode(true);
toggleBtn.parentNode.replaceChild(newToggleBtn, toggleBtn);
closeBtn.parentNode.replaceChild(newCloseBtn, closeBtn);
backdrop.parentNode.replaceChild(newBackdrop, backdrop);
// 重新获取元素并绑定事件
const currentToggleBtn = sidebar.querySelector('[data-toc-toggle]');
const currentCloseBtn = sidebar.querySelector('[data-toc-close]');
const currentBackdrop = sidebar.querySelector('[data-toc-backdrop]');
currentToggleBtn.addEventListener('click', handleToggleClick, { passive: false });
currentCloseBtn.addEventListener('click', handleCloseClick, { passive: false });
currentBackdrop.addEventListener('click', handleBackdropClick, { passive: false });
// 折叠/展开处理
tocList.addEventListener('click', (e) => {
const expandBtn = e.target.closest('[data-expand]');
if (expandBtn) {
e.preventDefault();
const sublist = expandBtn.closest('.toc-item').querySelector('.toc-sublist');
if (sublist) {
const isCollapsed = sublist.classList.contains('toc-sublist--collapsed');
sublist.classList.toggle('toc-sublist--collapsed', !isCollapsed);
expandBtn.setAttribute('aria-expanded', String(isCollapsed));
}
return;
}
const link = e.target.closest('.toc-link');
if (link) {
e.preventDefault();
const targetId = link.getAttribute('data-target');
const target = targetId ? document.getElementById(targetId) : null;
if (target) {
target.scrollIntoView({ behavior: 'smooth', block: 'start' });
history.replaceState(null, '', `#${targetId}`);
}
// 移动端点击后关闭侧边栏
if (!mediaQuery.matches) {
setSidebarOpen(false);
}
}
});
// 滚动高亮
let activeLink = null;
const setActiveLink = (id) => {
if (activeLink) {
activeLink.classList.remove('toc-link--active');
}
// 修复:使用正确的属性选择器
const newActiveLink = tocList.querySelector(`[data-target="${id}"]`);
if (newActiveLink) {
newActiveLink.classList.add('toc-link--active');
activeLink = newActiveLink;
// 自动展开父级
let parent = newActiveLink.closest('.toc-sublist');
while (parent) {
parent.classList.remove('toc-sublist--collapsed');
const expandBtn = parent.previousElementSibling?.querySelector('[data-expand]');
if (expandBtn) {
expandBtn.setAttribute('aria-expanded', 'true');
}
parent = parent.closest('.toc-item')?.parentElement?.closest('.toc-sublist');
}
}
};
const setupScrollSpy = (headings) => {
const observer = new IntersectionObserver((entries) => {
const visibleEntries = entries
.filter(entry => entry.isIntersecting)
.sort((a, b) => b.intersectionRatio - a.intersectionRatio);
if (visibleEntries.length > 0) {
setActiveLink(visibleEntries[0].target.id);
}
}, {
rootMargin: '-20% 0px -70% 0px',
threshold: [0, 0.25, 0.5, 0.75, 1]
});
headings.forEach(heading => observer.observe(heading));
};
// 键盘事件
document.addEventListener('keydown', (e) => {
if (e.key === 'Escape' && sidebar.classList.contains('toc-sidebar--open')) {
setSidebarOpen(false);
}
});
// 初始化
buildTOC();
mediaQuery.addEventListener('change', handleMediaChange);
handleMediaChange();
};
if (document.readyState === 'loading') {
document.addEventListener('DOMContentLoaded', __initTOC, { once: true });
} else {
__initTOC();
}
// Astro 过渡后重新初始化
document.addEventListener('astro:after-swap', () => {
__initTOC();
});
</script>
<style>
/* 基础布局 */
.toc-sidebar {
position: fixed;
top: 0;
left: 0;
width: 100vw;
height: 100vh;
z-index: 50;
pointer-events: none;
/* 底部安全距离(同时考虑安全区域) */
--toc-safe-bottom: clamp(12px, 2vh, 24px);
--toc-safe-area-bottom: env(safe-area-inset-bottom, 16px);
}
.toc-sidebar--open {
pointer-events: auto;
}
/* 切换按钮 */
.toc-toggle {
position: fixed;
bottom: 1.5rem;
right: 1.5rem;
display: flex;
align-items: center;
gap: 0.5rem;
padding: 0.75rem 1rem;
border-radius: 2rem;
background: rgba(248, 250, 255, 0.18);
backdrop-filter: blur(30px) saturate(150%);
border: 1px solid rgba(148, 163, 184, 0.28);
color: #011a2d;
font-weight: 600;
cursor: pointer;
box-shadow: 0 20px 48px rgba(15, 23, 42, 0.18);
transition: all 0.3s cubic-bezier(0.4, 0, 0.2, 1);
pointer-events: auto;
z-index: 60;
}
.toc-toggle::before {
content: '';
position: absolute;
inset: 0;
border-radius: inherit;
background: linear-gradient(120deg, rgba(255, 255, 255, 0.12), transparent 60%),
radial-gradient(80% 160% at 120% -40%, rgba(59, 130, 246, 0.18), transparent 70%);
opacity: 0.4;
pointer-events: none;
}
.toc-toggle:hover {
transform: translateY(-2px);
background: rgba(248, 250, 255, 0.25);
border-color: rgba(148, 163, 184, 0.35);
box-shadow: 0 24px 48px rgba(15, 23, 42, 0.22);
}
.toc-toggle__icon {
width: 20px;
height: 20px;
stroke-width: 2;
}
.toc-toggle__label {
font-size: 0.875rem;
}
/* 背景遮罩 */
.toc-backdrop {
position: fixed;
top: 0;
left: 0;
width: 100%;
height: 100%;
background: rgba(15, 23, 42, 0.6);
backdrop-filter: blur(4px);
opacity: 0;
visibility: hidden;
transition: all 0.3s ease;
z-index: 10;
}
.toc-sidebar--open .toc-backdrop {
opacity: 1;
visibility: visible;
}
/* 侧边栏面板 */
.toc-panel {
position: fixed;
bottom: 0;
left: 0;
right: 0;
max-height: 80vh;
background: linear-gradient(135deg,
rgba(174, 206, 221, 0.16),
rgba(177, 217, 212, 0.12),
rgba(178, 197, 213, 0.12)
);
backdrop-filter: blur(16px) saturate(130%);
border: 1px solid rgba(91, 119, 142, 0.28);
/* 显示底部边框,并通过 bottom 安全距离与屏幕底部留白 */
border-bottom: 1px solid rgba(91, 119, 142, 0.28);
border-radius: 1.5rem 1.5rem 0 0;
box-shadow: 0 16px 40px rgba(15, 23, 42, 0.16);
transform: translateY(100%);
transition: all 0.4s cubic-bezier(0.4, 0, 0.2, 1);
display: flex;
flex-direction: column;
overflow: hidden;
z-index: 20;
}
.toc-panel::before {
content: '';
position: absolute;
inset: 0;
background: linear-gradient(120deg, rgba(255, 255, 255, 0.12), transparent 60%),
radial-gradient(80% 160% at 120% -40%, rgba(59, 130, 246, 0.18), transparent 70%);
opacity: 0.4;
pointer-events: none;
border-radius: inherit;
}
.toc-sidebar--open .toc-panel {
transform: translateY(0);
bottom: calc(var(--toc-safe-bottom) + var(--toc-safe-area-bottom));
}
.toc-panel:hover {
background: linear-gradient(135deg,
rgba(174, 206, 221, 0.2),
rgba(177, 217, 212, 0.16),
rgba(178, 197, 213, 0.16)
);
border-color: rgba(91, 119, 142, 0.35);
box-shadow: 0 20px 48px rgba(15, 23, 42, 0.2);
}
/* 面板头部 */
.toc-header {
display: flex;
align-items: center;
justify-content: space-between;
padding: 1.5rem 1.5rem 1rem;
border-bottom: 1px solid rgba(148, 163, 184, 0.2);
position: relative;
}
.toc-title {
font-size: 1.125rem;
font-weight: 700;
margin: 0;
color: #011a2d;
}
.toc-close {
display: flex;
align-items: center;
justify-content: center;
width: 2rem;
height: 2rem;
border: 1px solid rgba(148, 163, 184, 0.25);
border-radius: 50%;
background: rgba(248, 250, 255, 0.15);
backdrop-filter: blur(20px) saturate(120%);
color: #011a2d;
cursor: pointer;
transition: all 0.2s ease;
position: relative;
}
.toc-close::before {
content: '';
position: absolute;
inset: 0;
border-radius: inherit;
background: linear-gradient(135deg, rgba(255, 255, 255, 0.1), transparent 50%);
opacity: 0.6;
pointer-events: none;
}
.toc-close:hover {
background: rgba(248, 250, 255, 0.25);
border-color: rgba(148, 163, 184, 0.35);
transform: scale(1.05);
box-shadow: 0 8px 24px rgba(15, 23, 42, 0.15);
}
.toc-close svg {
width: 18px;
height: 18px;
}
/* 导航区域 */
.toc-nav {
flex: 1;
overflow-y: auto;
padding: 1rem 1.5rem 1.5rem;
position: relative;
}
.toc-nav::-webkit-scrollbar {
width: 6px;
}
.toc-nav::-webkit-scrollbar-track {
background: rgba(148, 163, 184, 0.1);
border-radius: 3px;
}
.toc-nav::-webkit-scrollbar-thumb {
background: rgba(148, 163, 184, 0.3);
border-radius: 3px;
}
.toc-nav::-webkit-scrollbar-thumb:hover {
background: rgba(148, 163, 184, 0.4);
}
/* 目录列表 */
.toc-list,
.toc-sublist {
list-style: none;
margin: 0;
padding: 0;
}
.toc-sublist {
margin-left: 1rem;
margin-top: 0.25rem;
overflow: hidden;
transition: all 0.3s ease;
}
.toc-sublist--collapsed {
max-height: 0;
margin-top: 0;
}
/* 目录项 */
.toc-item {
margin-bottom: 0.125rem;
}
.toc-item-content {
display: flex;
align-items: center;
gap: 0.5rem;
}
.toc-expand {
display: flex;
align-items: center;
justify-content: center;
width: 1.5rem;
height: 1.5rem;
border: none;
background: transparent;
color: #6b7280;
cursor: pointer;
transition: all 0.2s ease;
border-radius: 0.25rem;
flex-shrink: 0;
}
.toc-expand:hover {
background: rgba(255, 255, 255, 0.1);
color: #011a2d;
}
.toc-expand[aria-expanded="true"] .toc-expand-icon {
transform: rotate(90deg);
}
.toc-expand-icon {
width: 14px;
height: 14px;
transition: transform 0.2s ease;
}
.toc-spacer {
width: 1.5rem;
height: 1.5rem;
flex-shrink: 0;
}
/* 目录链接 */
.toc-link {
flex: 1;
display: block;
padding: 0.5rem 0.75rem;
border-radius: 0.5rem;
text-decoration: none;
font-weight: 500;
transition: all 0.2s ease;
border-left: 3px solid transparent;
}
/* 根据层级设置样式 */
.toc-item--level-2 .toc-link {
font-size: 0.95rem;
font-weight: 600;
color: #011a2d;
}
.toc-item--level-3 .toc-link {
font-size: 0.875rem;
font-weight: 500;
color: #374151;
}
.toc-item--level-4 .toc-link {
font-size: 0.8rem;
font-weight: 400;
color: #6b7280;
}
.toc-link:hover {
background: rgba(59, 130, 246, 0.1);
border-left-color: rgba(59, 130, 246, 0.5);
transform: translateX(2px);
}
.toc-link--active {
background: linear-gradient(135deg, rgba(59, 130, 246, 0.15), rgba(29, 78, 216, 0.1));
border-left-color: #3b82f6;
color: #1d4ed8 !important;
font-weight: 600 !important;
box-shadow: 0 2px 8px rgba(59, 130, 246, 0.2);
}
/* 桌面端样式 */
@media (min-width: 1024px) {
.toc-sidebar {
--toc-width: clamp(280px, 20vw, 300px);
--container-max-width: 1200px;
--container-padding: 1rem;
--toc-offset: calc(max(var(--container-padding), (100vw - var(--container-max-width)) / 2) - var(--toc-width) - 1.5rem);
position: fixed;
top: 6rem;
left: clamp(1rem, var(--toc-offset), 2rem);
width: var(--toc-width);
height: calc(100vh - 7rem - var(--toc-safe-bottom) - var(--toc-safe-area-bottom));
pointer-events: auto;
z-index: 30;
}
.toc-sidebar--desktop {
pointer-events: auto;
}
.toc-toggle {
position: static;
bottom: auto;
right: auto;
width: 100%;
justify-content: center;
margin-bottom: 1rem;
/* 更柔和的按钮玻璃态,贴合主题 */
background: rgba(174, 206, 221, 0.16);
backdrop-filter: blur(14px) saturate(130%);
border: 1px solid rgba(91, 119, 142, 0.28);
box-shadow: 0 12px 32px rgba(15, 23, 42, 0.14);
}
.toc-backdrop {
display: none;
}
.toc-panel {
position: static;
bottom: auto;
left: auto;
right: auto;
width: 100%;
max-height: calc(100vh - 8rem);
height: auto;
min-height: 60vh;
border-radius: 1.25rem;
/* Morandi 主题的轻玻璃渐变,避免偏白 */
background: rgba(255, 255, 255, 0.25);
backdrop-filter: blur(20px) saturate(120%);
border: 1px solid rgba(91, 119, 142, 0.25);
box-shadow: 0 16px 40px rgba(15, 23, 42, 0.12);
/* 默认展开,避免脚本未初始化时看不到侧边栏 */
transform: translateX(0);
opacity: 1;
transition: all 0.3s cubic-bezier(0.4, 0, 0.2, 1);
overflow: hidden;
display: flex;
flex-direction: column;
/* 桌面端:面板底部与屏幕边缘保留安全距离 */
margin-bottom: calc(var(--toc-safe-bottom) + var(--toc-safe-area-bottom));
}
/* 移除过强的前景叠加,保持更纯净的玻璃质感 */
.toc-panel::before { display: none; }
/* 如果脚本需要关闭,则通过添加此类实现 */
.toc-sidebar--closed .toc-panel {
transform: translateX(-100%);
opacity: 0;
}
.toc-header {
padding: 1.25rem 1.25rem 1rem;
border-bottom: 1px solid rgba(91, 119, 142, 0.25);
}
.toc-nav {
flex: 1;
overflow-y: auto;
overflow-x: hidden;
padding: 0.75rem 1rem 1rem;
scrollbar-width: thin;
scrollbar-color: rgba(148, 163, 184, 0.3) transparent;
}
.toc-nav::-webkit-scrollbar {
width: 6px;
}
.toc-nav::-webkit-scrollbar-thumb {
background-color: rgba(148, 163, 184, 0.3);
border-radius: 3px;
}
.toc-nav::-webkit-scrollbar-thumb:hover {
background-color: rgba(148, 163, 184, 0.5);
}
.toc-header {
padding: 1.25rem 1.25rem 1rem;
border-bottom: 1px solid rgba(91, 119, 142, 0.25);
flex-shrink: 0;
}
/* 桌面端的紧凑间距 */
.toc-item {
margin-bottom: 0.0625rem;
}
.toc-link {
padding: 0.375rem 0.75rem;
}
.toc-item--level-2 .toc-link {
font-size: 0.9rem;
}
.toc-item--level-3 .toc-link {
font-size: 0.8rem;
}
.toc-item--level-4 .toc-link {
font-size: 0.75rem;
}
}
/* 无障碍和动画偏好 */
@media (prefers-reduced-motion: reduce) {
.toc-panel,
.toc-toggle,
.toc-backdrop,
.toc-link,
.toc-sublist,
.toc-expand-icon {
transition: none !important;
}
}
/* 高对比度模式支持 */
@media (prefers-contrast: high) {
.toc-panel {
background: rgba(255, 255, 255, 0.95);
border-color: rgba(0, 0, 0, 0.3);
}
.toc-link {
color: #000;
}
.toc-link--active {
background: #0066cc;
color: #fff !important;
}
}
</style>