tocのコードをちゃんとした

This commit is contained in:
moris 2025-02-28 11:16:39 +09:00
parent d356f9ef63
commit 2b8da7edee
5 changed files with 33 additions and 17 deletions

View file

@ -1,28 +1,39 @@
import Post from '$lib/server/LoadPost';
import { remark } from 'remark'
import Perser from '$lib/components/Markdown'
import { remark } from 'remark'
import { visitParents } from 'unist-util-visit-parents'
import { toString } from 'mdast-util-to-string'
import GithubSlugger from 'github-slugger';
export interface tocitem {
title: string,
id: string,
depth: 1 | 2 | 3 | 4 | 5 | 6
}
export async function load({params}) {
const md = await Post(params.slug);
const md = await Post(params.slug)
let persed = Perser(md.post)
let mdast = remark().parse(md.post)
let headers = mdast.children.filter((i) => i.type=='heading' && i.depth<4).map((i)=>{
let title = i.children[0].value
return {"depth": i.depth, "title": title}
let headers: tocitem[] = []
visitParents(mdast, 'heading', (node)=>{
let slugs = new GithubSlugger()
let title = toString(node)
let id = slugs.slug(title)
let depth = node.depth
let toc: tocitem = { title, id, depth }
headers.push(toc)
})
const slugs = new GithubSlugger()
let slugged = headers.map((x)=>x.depth ?slugs.slug(x.title):'').filter((x)=>x!='')
return {
id: params.slug,
metadata: md.metadata,
post: persed,
heading: slugged,
toc: headers,
}
}

View file

@ -144,9 +144,9 @@
<div>
<Share share={{url:`${baseURL}/post/${data.id}`, title:data.metadata.title}} />
</div>
{#if data.heading.length!=0}
{#if data.toc.length}
<div id='toc'>
<Toc toclist={data.heading}></Toc>
<Toc toclist={data.toc}></Toc>
</div>
{/if}
<div class="mi-posts js">

View file

@ -1,5 +1,6 @@
<script lang="ts">
export let toclist: string[];
export let toclist: tocitem[];
import type { tocitem } from './+page.server'
</script>
@ -7,7 +8,7 @@
<div style="margin:4px 0 0 8px;color:#aaaa;font-size:0.85em;">目次</div>
<ul>
{#each toclist as toc}
<li><a href='#{toc}'>{toc}</a></li>
<li><a href='#{toc.id}'>{toc.title}</a></li>
{/each}
</ul>
</nav>