feat(plugin-notes-data): add auto sidebar option

This commit is contained in:
pengzhanbo 2023-02-15 00:31:58 +08:00
parent 6863f025ee
commit 2e26fc7224

View File

@ -95,10 +95,47 @@ export const watchNotesData = (
function initSidebar(note: NotesItem, pages: NotePage[]): NotesSidebarItem[] {
if (!note.sidebar) return []
if (note.sidebar === 'auto') return []
if (note.sidebar === 'auto') return initSidebarByAuto(note, pages)
return initSidebarByConfig(note, pages)
}
function initSidebarByAuto(
note: NotesItem,
pages: NotePage[]
): NotesSidebarItem[] {
pages = pages.sort((prev, next) => {
const pi = prev.relativePath.match(/\//g)?.length || 0
const ni = next.relativePath.match(/\//g)?.length || 0
return pi < ni ? -1 : 1
})
const RE_INDEX = ['index.md', 'README.md', 'readme.md']
const result: NotesSidebarItem[] = []
for (const page of pages) {
const { relativePath, title, link } = page
const paths = relativePath
.slice(note.dir.replace(/^\/|\/$/g, '').length + 1)
.split('/')
let index = 0
let dir: string
let items = result
while ((dir = paths[index])) {
const text = dir.replace(/\.md$/, '')
let current = items.find((item) => item.text === text)
if (!current) {
current = { text, link: undefined, items: [] }
!RE_INDEX.includes(dir) ? items.push(current) : items.unshift(current)
}
if (dir.endsWith('.md')) {
current.link = link
current.text = title
}
items = current.items as NotesSidebarItem[]
index++
}
}
return result
}
function initSidebarByConfig(
{ text, dir, sidebar }: NotesItem,
pages: NotePage[]
@ -116,6 +153,7 @@ function initSidebarByConfig(
return {
text: item.text || item.dir || current?.title,
collapsed: item.collapsed,
link: item.link,
items: initSidebarByConfig(
{
link: item.link || '',