import { escapeHtml } from '../utils.js'; function buildTree(relPaths, sep) { const tree = { _files: [], _dirs: {} }; relPaths.forEach((rel) => { const parts = rel.split(sep); let node = tree; for (let i = 0; i < parts.length - 1; i++) { const dir = parts[i]; if (!node._dirs[dir]) node._dirs[dir] = { _files: [], _dirs: {} }; node = node._dirs[dir]; } node._files.push(rel); }); return tree; } function renderTree(node, prefix, sep, currentRel, depth) { let html = ''; const depthClass = depth > 0 ? ` class="nav-depth-${Math.min(depth, 3)}"` : ''; node._files.slice().sort().forEach((rel) => { const label = rel.split(sep).pop().replace(/\.md$/i, '').replace(/-/g, ' '); const abs = prefix + rel; const cls = rel === currentRel ? ' active' : ''; if (depth === 0) { html += `\n
  • ${escapeHtml(label)}
  • `; } else { html += `\n${escapeHtml(label)}`; } }); Object.keys(node._dirs).sort().forEach((dirName) => { const child = node._dirs[dirName]; const isOpen = currentRel && currentRel.split(sep).includes(dirName); const openAttr = isOpen ? ' open' : ''; const homeFile = child._files.find((f) => /^home\.md$/i.test(f.split(sep).pop())); let folderLabel; if (homeFile) { const abs = prefix + homeFile; const cls = homeFile === currentRel ? ' active' : ''; folderLabel = `${escapeHtml(dirName)}`; } else { folderLabel = `${escapeHtml(dirName)}`; } const arrow = ``; const childNode = { _files: homeFile ? child._files.filter((f) => f !== homeFile) : child._files, _dirs: child._dirs, }; html += `\n`; }); return html; } function buildSidebar(baseDir, files, currentFile) { const sep = baseDir.includes('\\') ? '\\' : '/'; const dirName = baseDir.split(sep).pop(); const prefix = baseDir.endsWith(sep) ? baseDir : baseDir + sep; const toRel = abs => abs.startsWith(prefix) ? abs.slice(prefix.length) : abs; const currentRel = currentFile ? toRel(currentFile) : null; const relPaths = files.map(toRel); const tree = buildTree(relPaths, sep); let html = ` `; return html; } export function renderSidebar(baseDir, files, currentFile, onNavigate) { const sidebarEl = document.querySelector('#sidebar'); sidebarEl.innerHTML = buildSidebar(baseDir, files, currentFile); sidebarEl.querySelectorAll('a[data-path]').forEach(a => { a.addEventListener('click', e => { e.preventDefault(); onNavigate(a.dataset.path); }); }); }