diff --git a/packages/plugin-notes-data/src/node/prepareNotesData.ts b/packages/plugin-notes-data/src/node/prepareNotesData.ts index 5172e4a2..e4b7c166 100644 --- a/packages/plugin-notes-data/src/node/prepareNotesData.ts +++ b/packages/plugin-notes-data/src/node/prepareNotesData.ts @@ -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 || '',