UNPKG

vite-plugin-vitepress-auto-sidebar

Version:

The vite plugin that automatically generates sidebar data by scanning directories, based on vitepress

203 lines (199 loc) 5.83 kB
import { join } from 'path'; import { existsSync, readFileSync, readdirSync, statSync } from 'fs'; import c from 'picocolors'; import fm from 'front-matter'; const DEFAULT_IGNORE_FOLDER = ["scripts", "components", "assets", ".vitepress"]; function log(...info) { console.log(c.bold(c.cyan("[auto-sidebar]")), ...info); } function removePrefix(str, identifier) { return str.replace(identifier, ""); } function getTitleFromFile(realFileName) { if (!existsSync(realFileName)) { return void 0; } const fileExtension = realFileName.substring( realFileName.lastIndexOf(".") + 1 ); if (fileExtension !== "md" && fileExtension !== "MD") { return void 0; } const data = readFileSync(realFileName, { encoding: "utf-8" }); const lines = data.split(/\r?\n/); for (const line of lines) { if (line.startsWith("# ")) { return line.substring(2); } } return void 0; } function getTitleFromFileByYaml(realFileName) { if (!existsSync(realFileName)) { return void 0; } const regex = /\.md$/i; if (!regex.test(realFileName)) { return void 0; } const data = readFileSync(realFileName, { encoding: "utf-8" }); const content = fm(data); return content.attributes?.title || void 0; } function extractTitleFn({ titleFromFile = false, titleFromFileByYaml = false }) { if (titleFromFile) { return getTitleFromFile; } if (titleFromFileByYaml) { return getTitleFromFileByYaml; } return void 0; } let option; function createSideBarItems(targetPath, path, recursive = true) { const { ignoreIndexItem, deletePrefix, collapsed, sideBarItemsResolved, beforeCreateSideBarItems, ignoreList = [], titleFromFile = false, titleFromFileByYaml = false } = option; const rawNode = readdirSync(join(targetPath, ...path)); const node = beforeCreateSideBarItems?.(rawNode) ?? rawNode; const currentDir = join(targetPath, ...path); if (ignoreIndexItem && node.length === 1 && node[0] === "index.md") { return []; } const result = []; const exec = extractTitleFn({ titleFromFile, titleFromFileByYaml }); for (const fname of node) { if (recursive && statSync(join(targetPath, ...path, fname)).isDirectory()) { if (ignoreList.some((item) => item === fname || item instanceof RegExp && item.test(fname))) { continue; } const items = createSideBarItems(join(targetPath), [...path, fname]); let text = fname; if (exec) { const filenames = [ join(currentDir, fname, "index.md"), join(currentDir, fname, "index.MD"), join(currentDir, fname, fname + ".md") ]; for (const filename of filenames) { const title = exec(filename); if (title) { text = title; break; } } } if (deletePrefix) { text = removePrefix(text, deletePrefix); } if (items.length > 0) { const sidebarItem = { text, items }; sidebarItem.collapsed = collapsed; result.push(sidebarItem); } } else { if (ignoreIndexItem && fname === "index.md" || /^-.*\.(md|MD)$/.test(fname) || ignoreList.some((item2) => item2 === fname || item2 instanceof RegExp && item2.test(fname)) || !fname.endsWith(".md")) { continue; } const fileName = fname.replace(/\.md$/, ""); let text = fileName; if (deletePrefix) { text = removePrefix(text, deletePrefix); } const realFileName = join(currentDir, fname); if (exec) { const title = exec(realFileName); if (title) { text = title; } } const item = { text, link: "/" + [...path.filter(Boolean), `${fileName}.html`].join("/") }; result.push(item); } } return sideBarItemsResolved?.(result) ?? result; } function createSideBarGroups(targetPath, folder, recursive = true) { return [ { items: createSideBarItems(targetPath, [folder], recursive) } ]; } function createSidebarMulti(path) { const { ignoreList = [], ignoreIndexItem = false, sideBarResolved, scanRootMdFiles = true } = option; const il = [...DEFAULT_IGNORE_FOLDER, ...ignoreList]; const data = {}; const node = readdirSync(path).filter( (n) => statSync(join(path, n)).isDirectory() && !il.includes(n) ); if (scanRootMdFiles) { data["/"] = createSideBarGroups(path, "", false); } for (const k of node) { data[`/${k}/`] = createSideBarGroups(path, k); } if (ignoreIndexItem) { for (const i in data) { let obj = data[i]; if (Array.isArray(obj)) { obj = obj.filter((i2) => i2.items != null && i2.items.length > 0); if (obj.length === 0) { Reflect.deleteProperty(data, i); } } } } return sideBarResolved?.(data) ?? data; } function VitePluginVitePressAutoSidebar(opt = {}) { return { name: "vite-plugin-vitepress-auto-sidebar", configureServer({ watcher, restart }) { const fsWatcher = watcher.add("*.md"); fsWatcher.on("all", async (event, path) => { if (event !== "change") { log(`${event} ${path}`); try { await restart(); log("update sidebar..."); } catch { log(`${event} ${path}`); log("update sidebar failed"); } } }); }, config(config) { option = opt; const { path = "/docs" } = option; const docsPath = join(process.cwd(), path); const { themeConfig } = config.vitepress.site; themeConfig.sidebar = createSidebarMulti(docsPath); log("injected sidebar data successfully"); return config; } }; } export { VitePluginVitePressAutoSidebar as default };