feat: 优化体验

This commit is contained in:
KazooTTT
2024-11-25 23:16:29 +08:00
parent f0037acb91
commit 92fc8c7861
4 changed files with 168 additions and 42 deletions

View File

@ -13,12 +13,12 @@ const { headings } = Astro.props
const toc = generateToc(headings)
---
<aside class='sticky top-20 order-2 -me-28 hidden basis-60 lg:flex lg:flex-col'>
<aside class='sticky top-20 order-2 -me-28 hidden h-[calc(100vh-6rem)] basis-60 lg:flex lg:flex-col'>
{
toc.length > 0 && (
<>
<h2 class='font-semibold'>TABLE OF CONTENTS</h2>
<ul class='text-card-foreground'>
<h2 class='mb-4 font-semibold'>TABLE OF CONTENTS</h2>
<ul class='text-card-foreground overflow-y-auto pr-4 max-h-[calc(100vh-10rem)]'>
{toc.map((heading) => (
<TOCHeading heading={heading} />
))}

View File

@ -10,16 +10,45 @@ const {
} = Astro.props
---
<li class={`${depth > 2 ? 'ms-2' : ''}`}>
<a
aria-label={`Scroll to section: ${text}`}
class={`block line-clamp-2 ${depth <= 2 ? 'mt-2' : 'mt-1 text-sm'} text-foreground/75 transition-all hover:text-foreground toc-link`}
href={`#${slug}`}
data-slug={slug}>{text}</a
>
<li>
<div class='flex items-center gap-1'>
{
subheadings.length > 0 && (
<button
class='collapse-button flex h-4 w-4 items-center justify-center rounded-sm hover:bg-accent/50'
aria-label='Toggle section'
data-slug={slug}
>
<svg
class='h-3 w-3 transform transition-transform duration-200'
xmlns='http://www.w3.org/2000/svg'
viewBox='0 0 24 24'
fill='none'
stroke='currentColor'
stroke-width='2'
stroke-linecap='round'
stroke-linejoin='round'
>
<polyline points='6 9 12 15 18 9' />
</svg>
</button>
)
}
<a
aria-label={`Scroll to section: ${text}`}
class={`line-clamp-2 hover:text-foreground toc-link flex-1
${depth === 1 ? 'text-base font-semibold' : depth === 2 ? 'text-base' : 'text-sm'}
text-foreground/75 transition-all`}
href={`#${slug}`}
data-slug={slug}>{text}</a
>
</div>
{
!!subheadings.length && (
<ul>
<ul
class='toc-list ms-6 overflow-hidden transition-all duration-300 ease-in-out'
style='max-height: none;'
>
{subheadings.map((subheading) => (
<Astro.self heading={subheading} />
))}
@ -30,6 +59,32 @@ const {
<script>
document.addEventListener('DOMContentLoaded', () => {
// Collapse/Expand functionality
const buttons = document.querySelectorAll('.collapse-button')
buttons.forEach((button) => {
button.addEventListener('click', (e) => {
e.preventDefault()
const btn = e.currentTarget as HTMLElement
const li = btn.closest('li')
const ul = li?.querySelector('.toc-list') as HTMLElement
const svg = btn.querySelector('svg')
if (ul && svg) {
if (ul.style.maxHeight === '0px') {
// Expand
ul.style.maxHeight = ul.scrollHeight + 'px'
svg.style.transform = ''
} else {
// Collapse
ul.style.maxHeight = '0px'
svg.style.transform = 'rotate(-180deg)'
}
}
})
})
// Smooth scrolling with offset
const tocLinks = document.querySelectorAll('.toc-link')
tocLinks.forEach((link) => {
link.addEventListener('click', (event) => {
@ -38,10 +93,60 @@ const {
if (slug) {
const element = document.getElementById(slug)
if (element) {
element.scrollIntoView({ behavior: 'smooth' })
const offset = 80 // Adjust this value based on header height
const elementPosition = element.getBoundingClientRect().top
const offsetPosition = elementPosition + window.pageYOffset - offset
window.scrollTo({
top: offsetPosition,
behavior: 'smooth'
})
}
}
})
})
// Active menu highlighting
const observerOptions = {
rootMargin: '-80px 0px -40% 0px',
threshold: 1.0
}
const headings = Array.from(
document.querySelectorAll('h1[id], h2[id], h3[id], h4[id], h5[id], h6[id]')
)
const headingElements = new Map()
headings.forEach((heading) => {
const id = heading.getAttribute('id')!
const tocLink = document.querySelector(`.toc-link[data-slug="${id}"]`)
if (tocLink) {
headingElements.set(heading, tocLink)
}
})
const observer = new IntersectionObserver((entries) => {
entries.forEach((entry) => {
const tocLink = headingElements.get(entry.target)
if (tocLink) {
if (entry.isIntersecting) {
// Remove active class from all links
document.querySelectorAll('.toc-link').forEach((link) => {
link.classList.remove('active', 'text-foreground')
})
// Add active class to current link
tocLink.classList.add('active', 'text-foreground')
}
}
})
}, observerOptions)
headings.forEach((heading) => observer.observe(heading))
})
</script>
<style>
.toc-link.active {
font-weight: 600;
}
</style>

View File

@ -46,7 +46,9 @@ const { headings } = await post.render()
</div>
<div
id='blog-gallery'
class='prose prose-base prose-zinc mt-12 text-muted-foreground dark:prose-invert prose-headings:font-medium prose-headings:text-foreground prose-headings:before:absolute prose-headings:before:-ms-4 prose-th:before:content-none'
class='prose prose-base prose-zinc mt-12 text-muted-foreground dark:prose-invert prose-headings:font-medium prose-headings:text-foreground prose-headings:before:absolute prose-headings:before:-ms-4 prose-code:bg-green-200
prose-th:before:content-none
prose-img:shadow'
>
<slot />
</div>
@ -77,7 +79,7 @@ const { headings } = await post.render()
id='image-modal'
class='pointer-events-none fixed inset-0 z-50 flex items-center justify-center bg-black bg-opacity-50 opacity-0 backdrop-blur-md transition-opacity duration-300 ease-in-out'
>
<div class='relative flex h-full w-full items-center justify-center p-4'>
<div class='relative flex h-full w-full items-center justify-center p-4' id='modal-container'>
<img
id='modal-image'
class='h-auto max-h-full w-auto max-w-full object-contain transition-transform duration-300 ease-in-out'
@ -125,13 +127,14 @@ const { headings } = await post.render()
// Image preview functionality
const imageModal = document.getElementById('image-modal')
const modalImage = document.getElementById('modal-image') as HTMLImageElement
const modalContainer = document.getElementById('modal-container')
function openModal() {
if (imageModal) {
imageModal.classList.remove('opacity-0', 'pointer-events-none')
modalImage.style.transform = 'scale(1)'
isZoomed = false
document.body.style.overflow = 'hidden' // 禁用滚动
document.body.style.overflow = 'hidden'
}
}
@ -142,7 +145,7 @@ const { headings } = await post.render()
modalImage.alt = ''
modalImage.style.transform = 'scale(1)'
isZoomed = false
document.body.style.overflow = '' // 恢复滚动
document.body.style.overflow = ''
}
}
@ -156,32 +159,34 @@ const { headings } = await post.render()
}
})
// 处理点击事件
if (imageModal) {
imageModal.addEventListener('click', (e) => {
if (e.target === imageModal) {
closeModal()
}
})
}
if (imageModal) {
document.addEventListener('keydown', (e) => {
if (e.key === 'Escape' && !imageModal.classList.contains('opacity-0')) {
const clickedElement = e.target as HTMLElement
// 如果点击的是 modal 背景或 modal-container不是图片和关闭按钮
if (clickedElement === imageModal || clickedElement === modalContainer) {
closeModal()
}
})
}
// 关闭按钮事件
const closeButton = document.getElementById('close-modal')
if (closeButton) {
closeButton.addEventListener('click', closeModal)
}
// 添加图片缩放功能
let isZoomed = false
// ESC 键关闭
document.addEventListener('keydown', (e) => {
if (e.key === 'Escape' && imageModal && !imageModal.classList.contains('opacity-0')) {
closeModal()
}
})
modalImage.addEventListener('click', () => {
// 图片缩放功能
let isZoomed = false
modalImage.addEventListener('click', (e) => {
e.stopPropagation() // 阻止事件冒泡到 modal
if (isZoomed) {
modalImage.style.transform = 'scale(1)'
modalImage.classList.remove('zoomed')

View File

@ -14,27 +14,43 @@ function diveChildren(item: TocItem, depth: number): Array<TocItem> {
}
export function generateToc(headings: ReadonlyArray<MarkdownHeading>) {
// this ignores/filters out h1 element(s)
const bodyHeadings = [...headings.filter(({ depth }) => depth > 1)]
const toc: Array<TocItem> = []
bodyHeadings.forEach((h) => {
headings.forEach((h) => {
const heading: TocItem = { ...h, subheadings: [] }
// add h2 elements into the top level
if (heading.depth === 2) {
if (heading.depth === 1) {
toc.push(heading)
} else if (heading.depth === 2) {
const lastH1 = toc[toc.length - 1]
if (lastH1 && lastH1.depth === 1) {
lastH1.subheadings.push(heading)
} else {
toc.push(heading)
}
} else {
const lastItemInToc = toc[toc.length - 1]!
if (heading.depth < lastItemInToc.depth) {
throw new Error(`Orphan heading found: ${heading.text}.`)
const lastItem = toc[toc.length - 1]
if (!lastItem) {
toc.push(heading)
return
}
// higher depth
// push into children, or children's children
const gap = heading.depth - lastItemInToc.depth
const target = diveChildren(lastItemInToc, gap)
target.push(heading)
if (lastItem.depth === 1 && lastItem.subheadings.length > 0) {
const lastH2 = lastItem.subheadings[lastItem.subheadings.length - 1]
if (heading.depth < lastH2.depth) {
throw new Error(`Orphan heading found: ${heading.text}.`)
}
const gap = heading.depth - lastH2.depth
const target = diveChildren(lastH2, gap)
target.push(heading)
} else {
if (heading.depth < lastItem.depth) {
throw new Error(`Orphan heading found: ${heading.text}.`)
}
const gap = heading.depth - lastItem.depth
const target = diveChildren(lastItem, gap)
target.push(heading)
}
}
})
return toc