mirror of
https://github.com/litruv/Docs-Viewer.git
synced 2026-07-24 02:36:07 +10:00
Enhance build-docs.js to extract headers from markdown files and include them in metadata
This commit is contained in:
@@ -1,7 +1,21 @@
|
|||||||
//get all *.md files in ./docs, reccursively, and store them in an array, with their properties in the first block, they're from obsidian
|
|
||||||
const fs = require('fs');
|
const fs = require('fs');
|
||||||
const path = require('path');
|
const path = require('path');
|
||||||
|
|
||||||
|
function extractHeaders(content) {
|
||||||
|
const headerRegex = /^(#{1,6})\s+(.+)$/gm;
|
||||||
|
const headers = [];
|
||||||
|
let match;
|
||||||
|
|
||||||
|
while ((match = headerRegex.exec(content)) !== null) {
|
||||||
|
// Don't include h1 headers as they're typically the title
|
||||||
|
if (match[1].length > 1) {
|
||||||
|
headers.push(match[2].trim());
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
return headers;
|
||||||
|
}
|
||||||
|
|
||||||
function parseFrontMatter(content) {
|
function parseFrontMatter(content) {
|
||||||
const lines = content.trim().split('\n');
|
const lines = content.trim().split('\n');
|
||||||
let metadata = {};
|
let metadata = {};
|
||||||
@@ -20,9 +34,15 @@ function parseFrontMatter(content) {
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
const contentText = lines.slice(contentStart).join('\n').trim();
|
||||||
|
const headers = extractHeaders(contentText);
|
||||||
|
if (headers.length > 0) {
|
||||||
|
metadata.headers = headers;
|
||||||
|
}
|
||||||
|
|
||||||
return {
|
return {
|
||||||
metadata,
|
metadata,
|
||||||
content: lines.slice(contentStart).join('\n').trim()
|
content: contentText
|
||||||
};
|
};
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -124,7 +144,6 @@ function loadIndexTemplate() {
|
|||||||
const indexPath = path.join(__dirname, 'index.json');
|
const indexPath = path.join(__dirname, 'index.json');
|
||||||
try {
|
try {
|
||||||
const indexData = JSON.parse(fs.readFileSync(indexPath, 'utf-8'));
|
const indexData = JSON.parse(fs.readFileSync(indexPath, 'utf-8'));
|
||||||
// Strip out documents array, keeping all other properties
|
|
||||||
delete indexData.documents;
|
delete indexData.documents;
|
||||||
return indexData;
|
return indexData;
|
||||||
} catch (error) {
|
} catch (error) {
|
||||||
@@ -156,12 +175,10 @@ function combineIndexes(dir) {
|
|||||||
const indexData = loadIndexTemplate();
|
const indexData = loadIndexTemplate();
|
||||||
const documents = readAllMarkdownFiles(dir);
|
const documents = readAllMarkdownFiles(dir);
|
||||||
|
|
||||||
// Add the documents array with new content
|
|
||||||
indexData.documents = documents;
|
indexData.documents = documents;
|
||||||
writeIndexFile(indexData);
|
writeIndexFile(indexData);
|
||||||
}
|
}
|
||||||
|
|
||||||
// Replace console.log with combineIndexes call
|
|
||||||
combineIndexes(path.join(__dirname, 'docs'));
|
combineIndexes(path.join(__dirname, 'docs'));
|
||||||
|
|
||||||
module.exports = readAllMarkdownFiles;
|
module.exports = readAllMarkdownFiles;
|
||||||
|
|||||||
290
index.js
290
index.js
@@ -12,7 +12,7 @@ class EventBus {
|
|||||||
constructor() {
|
constructor() {
|
||||||
this.events = {};
|
this.events = {};
|
||||||
}
|
}
|
||||||
|
|
||||||
on(event, callback) {
|
on(event, callback) {
|
||||||
if (!this.events[event]) {
|
if (!this.events[event]) {
|
||||||
this.events[event] = [];
|
this.events[event] = [];
|
||||||
@@ -20,12 +20,12 @@ class EventBus {
|
|||||||
this.events[event].push(callback);
|
this.events[event].push(callback);
|
||||||
return () => this.off(event, callback);
|
return () => this.off(event, callback);
|
||||||
}
|
}
|
||||||
|
|
||||||
off(event, callback) {
|
off(event, callback) {
|
||||||
if (!this.events[event]) return;
|
if (!this.events[event]) return;
|
||||||
this.events[event] = this.events[event].filter(cb => cb !== callback);
|
this.events[event] = this.events[event].filter(cb => cb !== callback);
|
||||||
}
|
}
|
||||||
|
|
||||||
emit(event, data) {
|
emit(event, data) {
|
||||||
if (!this.events[event]) return;
|
if (!this.events[event]) return;
|
||||||
this.events[event].forEach(callback => callback(data));
|
this.events[event].forEach(callback => callback(data));
|
||||||
@@ -49,13 +49,27 @@ class SearchService {
|
|||||||
if (doc.type === 'folder') {
|
if (doc.type === 'folder') {
|
||||||
const currentPath = parentPath ? `${parentPath} / ${doc.title}` : doc.title;
|
const currentPath = parentPath ? `${parentPath} / ${doc.title}` : doc.title;
|
||||||
if (doc.path) {
|
if (doc.path) {
|
||||||
this.searchIndex.push({
|
if (doc.showfolderpage !== 'false') {
|
||||||
title: doc.title,
|
this.searchIndex.push({
|
||||||
path: doc.path,
|
title: doc.title,
|
||||||
slug: doc.slug,
|
path: doc.path,
|
||||||
location: currentPath,
|
slug: doc.slug,
|
||||||
type: 'folder'
|
location: currentPath,
|
||||||
});
|
type: 'folder'
|
||||||
|
});
|
||||||
|
}
|
||||||
|
|
||||||
|
if (doc.headers) {
|
||||||
|
doc.headers.forEach(header => {
|
||||||
|
this.searchIndex.push({
|
||||||
|
title: header,
|
||||||
|
path: doc.path,
|
||||||
|
slug: `${doc.slug}#${header.toLowerCase().replace(/[^\w\s-]/g, '').replace(/\s+/g, '-')}`,
|
||||||
|
location: `${currentPath} / ${doc.title}`,
|
||||||
|
type: 'header'
|
||||||
|
});
|
||||||
|
});
|
||||||
|
}
|
||||||
}
|
}
|
||||||
if (doc.items) {
|
if (doc.items) {
|
||||||
this.processDocuments(doc.items, currentPath);
|
this.processDocuments(doc.items, currentPath);
|
||||||
@@ -68,6 +82,18 @@ class SearchService {
|
|||||||
location: parentPath,
|
location: parentPath,
|
||||||
type: 'file'
|
type: 'file'
|
||||||
});
|
});
|
||||||
|
|
||||||
|
if (doc.headers) {
|
||||||
|
doc.headers.forEach(header => {
|
||||||
|
this.searchIndex.push({
|
||||||
|
title: header,
|
||||||
|
path: doc.path,
|
||||||
|
slug: `${doc.slug}#${header.toLowerCase().replace(/[^\w\s-]/g, '').replace(/\s+/g, '-')}`,
|
||||||
|
location: `${parentPath} / ${doc.title}`,
|
||||||
|
type: 'header'
|
||||||
|
});
|
||||||
|
});
|
||||||
|
}
|
||||||
}
|
}
|
||||||
});
|
});
|
||||||
}
|
}
|
||||||
@@ -75,23 +101,25 @@ class SearchService {
|
|||||||
search(query) {
|
search(query) {
|
||||||
if (!query) return [];
|
if (!query) return [];
|
||||||
query = query.toLowerCase();
|
query = query.toLowerCase();
|
||||||
|
|
||||||
return this.searchIndex
|
return this.searchIndex
|
||||||
.filter(item => {
|
.map(item => {
|
||||||
const titleMatch = item.title.toLowerCase().includes(query);
|
const titleLower = item.title.toLowerCase();
|
||||||
const pathMatch = item.path.toLowerCase().includes(query);
|
let score = 0;
|
||||||
const locationMatch = item.location.toLowerCase().includes(query);
|
|
||||||
return titleMatch || pathMatch || locationMatch;
|
if (titleLower === query) score = 100;
|
||||||
|
else if (titleLower.startsWith(query)) score = 80;
|
||||||
|
else if (titleLower.includes(query)) score = 60;
|
||||||
|
else if (item.path.toLowerCase().includes(query)) score = 40;
|
||||||
|
else if (item.location.toLowerCase().includes(query)) score = 20;
|
||||||
|
|
||||||
|
if (item.type === 'header') score += 5;
|
||||||
|
|
||||||
|
return { ...item, score };
|
||||||
})
|
})
|
||||||
.sort((a, b) => {
|
.filter(item => item.score > 0)
|
||||||
// Prioritize exact matches in title
|
.sort((a, b) => b.score - a.score)
|
||||||
const aTitle = a.title.toLowerCase();
|
.slice(0, 10);
|
||||||
const bTitle = b.title.toLowerCase();
|
|
||||||
if (aTitle === query) return -1;
|
|
||||||
if (bTitle === query) return 1;
|
|
||||||
return aTitle.localeCompare(bTitle);
|
|
||||||
})
|
|
||||||
.slice(0, 10); // Limit to 10 results
|
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -112,9 +140,9 @@ class IndexService {
|
|||||||
if (doc.type === 'folder') {
|
if (doc.type === 'folder') {
|
||||||
const found = this.findDocumentByTitle(doc.items, title);
|
const found = this.findDocumentByTitle(doc.items, title);
|
||||||
if (found) return found;
|
if (found) return found;
|
||||||
} else if (doc.title === title ||
|
} else if (doc.title === title ||
|
||||||
doc.path.endsWith(title + '.md') ||
|
doc.path.endsWith(title + '.md') ||
|
||||||
doc.slug === title.toLowerCase().replace(/ /g, '-')) {
|
doc.slug === title.toLowerCase().replace(/ /g, '-')) {
|
||||||
return doc;
|
return doc;
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
@@ -131,7 +159,7 @@ class IndexService {
|
|||||||
}
|
}
|
||||||
return false;
|
return false;
|
||||||
});
|
});
|
||||||
|
|
||||||
if (found) {
|
if (found) {
|
||||||
parentFolders.push(doc);
|
parentFolders.push(doc);
|
||||||
doc.items.forEach(item => {
|
doc.items.forEach(item => {
|
||||||
@@ -156,19 +184,19 @@ class DOMService {
|
|||||||
titleText: document.querySelector('.title-text .page-title'),
|
titleText: document.querySelector('.title-text .page-title'),
|
||||||
leftSidebar: document.querySelector('.left-sidebar'),
|
leftSidebar: document.querySelector('.left-sidebar'),
|
||||||
menuButton: document.querySelector('.menu-button'),
|
menuButton: document.querySelector('.menu-button'),
|
||||||
header: document.querySelector('title-bar'), // Add header element
|
header: document.querySelector('title-bar'),
|
||||||
searchInput: document.getElementById('search-input'),
|
searchInput: document.getElementById('search-input'),
|
||||||
searchResults: document.getElementById('search-results'),
|
searchResults: document.getElementById('search-results'),
|
||||||
clearSearch: document.getElementById('clear-search')
|
clearSearch: document.getElementById('clear-search')
|
||||||
};
|
};
|
||||||
this.headerOffset = 60; // Fixed header heightfsetHeight || 0; // Get header height
|
this.headerOffset = 60;
|
||||||
}
|
}
|
||||||
|
|
||||||
setupMobileMenu() {
|
setupMobileMenu() {
|
||||||
this.elements.menuButton.addEventListener('click', () =>
|
this.elements.menuButton.addEventListener('click', () =>
|
||||||
this.elements.leftSidebar.classList.toggle('show'));
|
this.elements.leftSidebar.classList.toggle('show'));
|
||||||
|
|
||||||
this.elements.content.addEventListener('click', () =>
|
this.elements.content.addEventListener('click', () =>
|
||||||
this.elements.leftSidebar.classList.remove('show'));
|
this.elements.leftSidebar.classList.remove('show'));
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -196,19 +224,29 @@ class DOMService {
|
|||||||
|
|
||||||
const folderHeader = document.createElement('div');
|
const folderHeader = document.createElement('div');
|
||||||
folderHeader.className = 'folder-header';
|
folderHeader.className = 'folder-header';
|
||||||
|
|
||||||
const iconClass = doc.icon || `fas fa-folder${doc.defaultOpen !== false ? '-open' : ''}`;
|
const iconClass = doc.icon || `fas fa-folder${doc.defaultOpen !== false ? '-open' : ''}`;
|
||||||
|
|
||||||
folderHeader.innerHTML = doc.path ?
|
|
||||||
this.createFolderHeaderWithFile(iconClass, doc) :
|
|
||||||
this.createFolderHeaderBasic(iconClass, doc);
|
|
||||||
|
|
||||||
this.setupFolderListeners(folderDiv, folderHeader, doc);
|
// Only add folder click handler if showfolderpage is not false
|
||||||
|
if (doc.path && doc.metadata?.showfolderpage !== false) {
|
||||||
|
folderHeader.innerHTML = this.createFolderHeaderWithFile(iconClass, doc);
|
||||||
|
this.setupFolderListeners(folderDiv, folderHeader, doc);
|
||||||
|
} else {
|
||||||
|
folderHeader.innerHTML = this.createFolderHeaderBasic(iconClass, doc);
|
||||||
|
// Only setup the folder open/close functionality
|
||||||
|
folderHeader.addEventListener('click', () => {
|
||||||
|
folderDiv.classList.toggle('open');
|
||||||
|
if (!doc.icon) {
|
||||||
|
const icon = folderHeader.querySelector('.folder-icon');
|
||||||
|
icon.classList.toggle('fa-folder-closed');
|
||||||
|
icon.classList.toggle('fa-folder-open');
|
||||||
|
}
|
||||||
|
});
|
||||||
|
}
|
||||||
|
|
||||||
const folderContent = document.createElement('div');
|
const folderContent = document.createElement('div');
|
||||||
folderContent.className = 'folder-content';
|
folderContent.className = 'folder-content';
|
||||||
doc.items.forEach(item => this.createFileIndexItem(item, folderContent, level + 1));
|
doc.items.forEach(item => this.createFileIndexItem(item, folderContent, level + 1));
|
||||||
|
|
||||||
folderDiv.appendChild(folderHeader);
|
folderDiv.appendChild(folderHeader);
|
||||||
folderDiv.appendChild(folderContent);
|
folderDiv.appendChild(folderContent);
|
||||||
container.appendChild(folderDiv);
|
container.appendChild(folderDiv);
|
||||||
@@ -223,7 +261,7 @@ class DOMService {
|
|||||||
link.textContent = doc.title || doc.path.split('/').pop().replace('.md', '');
|
link.textContent = doc.title || doc.path.split('/').pop().replace('.md', '');
|
||||||
link.dataset.path = doc.path;
|
link.dataset.path = doc.path;
|
||||||
link.style.paddingLeft = `${(level * 0.6) + 0.8}rem`; // Add base padding of 0.8rem
|
link.style.paddingLeft = `${(level * 0.6) + 0.8}rem`; // Add base padding of 0.8rem
|
||||||
|
|
||||||
link.onclick = (e) => {
|
link.onclick = (e) => {
|
||||||
e.preventDefault();
|
e.preventDefault();
|
||||||
this.eventBus.emit('navigation:requested', { slug: doc.slug });
|
this.eventBus.emit('navigation:requested', { slug: doc.slug });
|
||||||
@@ -232,7 +270,7 @@ class DOMService {
|
|||||||
this.elements.leftSidebar.classList.remove('show');
|
this.elements.leftSidebar.classList.remove('show');
|
||||||
}
|
}
|
||||||
};
|
};
|
||||||
|
|
||||||
container.appendChild(link);
|
container.appendChild(link);
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -245,14 +283,14 @@ class DOMService {
|
|||||||
createOutline(headings) {
|
createOutline(headings) {
|
||||||
this.elements.outline.innerHTML = '';
|
this.elements.outline.innerHTML = '';
|
||||||
const headingLinks = new Map();
|
const headingLinks = new Map();
|
||||||
|
|
||||||
headings.forEach(heading => {
|
headings.forEach(heading => {
|
||||||
if (!heading.id) {
|
if (!heading.id) {
|
||||||
heading.id = heading.textContent.toLowerCase()
|
heading.id = heading.textContent.toLowerCase()
|
||||||
.replace(/[^\w\s-]/g, '')
|
.replace(/[^\w\s-]/g, '')
|
||||||
.replace(/\s+/g, '-');
|
.replace(/\s+/g, '-');
|
||||||
}
|
}
|
||||||
|
|
||||||
const link = this.createOutlineLink(heading);
|
const link = this.createOutlineLink(heading);
|
||||||
headingLinks.set(heading, link);
|
headingLinks.set(heading, link);
|
||||||
this.elements.outline.appendChild(link);
|
this.elements.outline.appendChild(link);
|
||||||
@@ -263,14 +301,16 @@ class DOMService {
|
|||||||
}
|
}
|
||||||
|
|
||||||
createFolderHeaderWithFile(iconClass, doc) {
|
createFolderHeaderWithFile(iconClass, doc) {
|
||||||
|
const showFolderPage = doc.showfolderpage !== 'false';
|
||||||
return `
|
return `
|
||||||
<div class="folder-icons">
|
<div class="folder-icons">
|
||||||
<i class="${iconClass} folder-icon"></i>
|
<i class="${iconClass} folder-icon"></i>
|
||||||
</div>
|
</div>
|
||||||
<span>${doc.title}</span>
|
<span>${doc.title}</pan>
|
||||||
<a href="?${doc.slug}" class="folder-link" title="View folder page">
|
${showFolderPage ? `
|
||||||
<i class="fas fa-file-alt"></i>
|
<a href="?${doc.slug}" class="folder-link" title="View folder page">
|
||||||
</a>`;
|
<i class="fas fa-file-alt"></i>
|
||||||
|
</a>` : ''}`;
|
||||||
}
|
}
|
||||||
|
|
||||||
createFolderHeaderBasic(iconClass, doc) {
|
createFolderHeaderBasic(iconClass, doc) {
|
||||||
@@ -292,7 +332,7 @@ class DOMService {
|
|||||||
}
|
}
|
||||||
return;
|
return;
|
||||||
}
|
}
|
||||||
|
|
||||||
folderDiv.classList.toggle('open');
|
folderDiv.classList.toggle('open');
|
||||||
if (!doc.icon) {
|
if (!doc.icon) {
|
||||||
const icon = folderHeader.querySelector('.folder-icon');
|
const icon = folderHeader.querySelector('.folder-icon');
|
||||||
@@ -307,7 +347,7 @@ class DOMService {
|
|||||||
const rect = element.getBoundingClientRect();
|
const rect = element.getBoundingClientRect();
|
||||||
const absoluteElementTop = rect.top + window.scrollY;
|
const absoluteElementTop = rect.top + window.scrollY;
|
||||||
const middle = absoluteElementTop - (this.headerOffset + 20); // Add extra padding
|
const middle = absoluteElementTop - (this.headerOffset + 20); // Add extra padding
|
||||||
|
|
||||||
window.scrollTo({
|
window.scrollTo({
|
||||||
top: middle,
|
top: middle,
|
||||||
behavior: 'smooth'
|
behavior: 'smooth'
|
||||||
@@ -319,7 +359,7 @@ class DOMService {
|
|||||||
link.href = `${window.location.pathname}${window.location.search}#${heading.id}`;
|
link.href = `${window.location.pathname}${window.location.search}#${heading.id}`;
|
||||||
link.textContent = heading.textContent;
|
link.textContent = heading.textContent;
|
||||||
link.style.paddingLeft = (heading.tagName[1] * 15) + 'px';
|
link.style.paddingLeft = (heading.tagName[1] * 15) + 'px';
|
||||||
|
|
||||||
link.onclick = (e) => {
|
link.onclick = (e) => {
|
||||||
e.preventDefault();
|
e.preventDefault();
|
||||||
history.pushState(null, '', link.href);
|
history.pushState(null, '', link.href);
|
||||||
@@ -328,7 +368,7 @@ class DOMService {
|
|||||||
void heading.offsetWidth;
|
void heading.offsetWidth;
|
||||||
heading.classList.add('highlight');
|
heading.classList.add('highlight');
|
||||||
};
|
};
|
||||||
|
|
||||||
return link;
|
return link;
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -342,16 +382,16 @@ class DOMService {
|
|||||||
toggleBtn.style.marginLeft = '0.5em';
|
toggleBtn.style.marginLeft = '0.5em';
|
||||||
toggleBtn.style.display = 'inline-flex';
|
toggleBtn.style.display = 'inline-flex';
|
||||||
toggleBtn.style.alignItems = 'center';
|
toggleBtn.style.alignItems = 'center';
|
||||||
|
|
||||||
toggleBtn.addEventListener('click', (e) => {
|
toggleBtn.addEventListener('click', (e) => {
|
||||||
e.stopPropagation();
|
e.stopPropagation();
|
||||||
const svg = toggleBtn.querySelector('svg');
|
const svg = toggleBtn.querySelector('svg');
|
||||||
const isFolded = svg.style.transform === 'rotate(90deg)';
|
const isFolded = svg.style.transform === 'rotate(90deg)';
|
||||||
svg.style.transform = isFolded ? 'rotate(0deg)' : 'rotate(90deg)';
|
svg.style.transform = isFolded ? 'rotate(0deg)' : 'rotate(90deg)';
|
||||||
|
|
||||||
let next = heading.nextElementSibling;
|
let next = heading.nextElementSibling;
|
||||||
const currentLevel = parseInt(heading.tagName[1]);
|
const currentLevel = parseInt(heading.tagName[1]);
|
||||||
|
|
||||||
while (next) {
|
while (next) {
|
||||||
if (!/^H[1-6]$/.test(next.tagName)) {
|
if (!/^H[1-6]$/.test(next.tagName)) {
|
||||||
next.style.display = isFolded ? 'none' : '';
|
next.style.display = isFolded ? 'none' : '';
|
||||||
@@ -364,17 +404,17 @@ class DOMService {
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
});
|
});
|
||||||
|
|
||||||
heading.appendChild(toggleBtn);
|
heading.appendChild(toggleBtn);
|
||||||
}
|
}
|
||||||
|
|
||||||
setupSearch(searchService) {
|
setupSearch(searchService) {
|
||||||
let searchTimeout;
|
let searchTimeout;
|
||||||
|
|
||||||
this.elements.searchInput.addEventListener('input', (e) => {
|
this.elements.searchInput.addEventListener('input', (e) => {
|
||||||
clearTimeout(searchTimeout);
|
clearTimeout(searchTimeout);
|
||||||
const query = e.target.value;
|
const query = e.target.value;
|
||||||
|
|
||||||
searchTimeout = setTimeout(() => {
|
searchTimeout = setTimeout(() => {
|
||||||
const results = searchService.search(query);
|
const results = searchService.search(query);
|
||||||
this.renderSearchResults(results);
|
this.renderSearchResults(results);
|
||||||
@@ -391,7 +431,7 @@ class DOMService {
|
|||||||
renderSearchResults(results) {
|
renderSearchResults(results) {
|
||||||
const container = this.elements.searchResults;
|
const container = this.elements.searchResults;
|
||||||
container.innerHTML = '';
|
container.innerHTML = '';
|
||||||
|
|
||||||
if (results.length === 0 || !this.elements.searchInput.value) {
|
if (results.length === 0 || !this.elements.searchInput.value) {
|
||||||
container.style.display = 'none';
|
container.style.display = 'none';
|
||||||
return;
|
return;
|
||||||
@@ -400,10 +440,12 @@ class DOMService {
|
|||||||
results.forEach(result => {
|
results.forEach(result => {
|
||||||
const div = document.createElement('div');
|
const div = document.createElement('div');
|
||||||
div.className = 'search-result';
|
div.className = 'search-result';
|
||||||
|
|
||||||
const icon = document.createElement('i');
|
const icon = document.createElement('i');
|
||||||
icon.className = result.type === 'folder' ? 'fas fa-folder' : 'fas fa-file-alt';
|
icon.className = result.type === 'folder' ? 'fas fa-folder' :
|
||||||
|
result.type === 'header' ? 'fas fa-hashtag' :
|
||||||
|
'fas fa-file-alt';
|
||||||
|
|
||||||
const link = document.createElement('a');
|
const link = document.createElement('a');
|
||||||
link.href = `?${result.slug}`;
|
link.href = `?${result.slug}`;
|
||||||
link.innerHTML = `
|
link.innerHTML = `
|
||||||
@@ -413,19 +455,24 @@ class DOMService {
|
|||||||
<div class="search-result-path">${result.location}</div>
|
<div class="search-result-path">${result.location}</div>
|
||||||
</div>
|
</div>
|
||||||
`;
|
`;
|
||||||
|
|
||||||
link.addEventListener('click', (e) => {
|
link.addEventListener('click', (e) => {
|
||||||
e.preventDefault();
|
e.preventDefault();
|
||||||
this.elements.searchInput.value = '';
|
this.elements.searchInput.value = '';
|
||||||
container.style.display = 'none';
|
container.style.display = 'none';
|
||||||
|
const [baseSlug, hash] = result.slug.split('#');
|
||||||
history.pushState(null, '', link.href);
|
history.pushState(null, '', link.href);
|
||||||
this.eventBus.emit('navigation:requested', { slug: result.slug });
|
this.eventBus.emit('navigation:requested', {
|
||||||
|
slug: baseSlug,
|
||||||
|
hash: hash ? `#${hash}` : '',
|
||||||
|
fromSearch: true // Add this flag
|
||||||
|
});
|
||||||
});
|
});
|
||||||
|
|
||||||
div.appendChild(link);
|
div.appendChild(link);
|
||||||
container.appendChild(div);
|
container.appendChild(div);
|
||||||
});
|
});
|
||||||
|
|
||||||
container.style.display = 'block';
|
container.style.display = 'block';
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
@@ -448,7 +495,7 @@ class DocumentService {
|
|||||||
|
|
||||||
const renderer = new marked.Renderer();
|
const renderer = new marked.Renderer();
|
||||||
this.setupRenderer(renderer);
|
this.setupRenderer(renderer);
|
||||||
|
|
||||||
marked.setOptions({
|
marked.setOptions({
|
||||||
breaks: true,
|
breaks: true,
|
||||||
gfm: true,
|
gfm: true,
|
||||||
@@ -460,7 +507,7 @@ class DocumentService {
|
|||||||
|
|
||||||
setupRenderer(renderer) {
|
setupRenderer(renderer) {
|
||||||
const originalLink = renderer.link.bind(renderer);
|
const originalLink = renderer.link.bind(renderer);
|
||||||
|
|
||||||
renderer.code = this.renderCode;
|
renderer.code = this.renderCode;
|
||||||
renderer.link = (href, title, text) => {
|
renderer.link = (href, title, text) => {
|
||||||
const isExternal = href.startsWith('http');
|
const isExternal = href.startsWith('http');
|
||||||
@@ -471,16 +518,15 @@ class DocumentService {
|
|||||||
}
|
}
|
||||||
return link.replace(/^<a /, `<a${attrs} `);
|
return link.replace(/^<a /, `<a${attrs} `);
|
||||||
};
|
};
|
||||||
|
|
||||||
// Add custom heading renderer to make headers clickable - without link icon
|
|
||||||
const originalHeading = renderer.heading.bind(renderer);
|
const originalHeading = renderer.heading.bind(renderer);
|
||||||
renderer.heading = (text, level) => {
|
renderer.heading = (text, level) => {
|
||||||
const escapedText = text.toLowerCase()
|
const escapedText = text.toLowerCase()
|
||||||
.replace(/[^\w\s-]/g, '')
|
.replace(/[^\w\s-]/g, '')
|
||||||
.replace(/\s+/g, '-');
|
.replace(/\s+/g, '-');
|
||||||
|
|
||||||
const id = escapedText;
|
const id = escapedText;
|
||||||
|
|
||||||
return `<h${level} id="${id}" class="clickable-header">
|
return `<h${level} id="${id}" class="clickable-header">
|
||||||
${text}
|
${text}
|
||||||
</h${level}>`;
|
</h${level}>`;
|
||||||
@@ -528,17 +574,17 @@ class DocumentService {
|
|||||||
fetch(path),
|
fetch(path),
|
||||||
this.markedPromise
|
this.markedPromise
|
||||||
]);
|
]);
|
||||||
|
|
||||||
let rawContent = await response.text();
|
let rawContent = await response.text();
|
||||||
const { metadata, content } = this.extractMetadata(rawContent);
|
const { metadata, content } = this.extractMetadata(rawContent);
|
||||||
const basePath = path.substring(0, path.lastIndexOf('/'));
|
const basePath = path.substring(0, path.lastIndexOf('/'));
|
||||||
const indexDoc = this.findDocInIndex(path);
|
const indexDoc = this.findDocInIndex(path);
|
||||||
|
|
||||||
let processedContent = this.processWikiLinks(content);
|
let processedContent = this.processWikiLinks(content);
|
||||||
processedContent = this.processImages(processedContent, basePath);
|
processedContent = this.processImages(processedContent, basePath);
|
||||||
const titleContent = metadata.title || indexDoc?.title || path.split('/').pop().replace('.md', '');
|
const titleContent = metadata.title || indexDoc?.title || path.split('/').pop().replace('.md', '');
|
||||||
processedContent = this.ensureTitle(processedContent, titleContent);
|
processedContent = this.ensureTitle(processedContent, titleContent);
|
||||||
|
|
||||||
return {
|
return {
|
||||||
content: processedContent,
|
content: processedContent,
|
||||||
metadata,
|
metadata,
|
||||||
@@ -552,7 +598,7 @@ class DocumentService {
|
|||||||
|
|
||||||
findDocInIndex(path) {
|
findDocInIndex(path) {
|
||||||
let doc = window._indexData.documents.find(d => d.path === path);
|
let doc = window._indexData.documents.find(d => d.path === path);
|
||||||
|
|
||||||
if (!doc) {
|
if (!doc) {
|
||||||
for (const d of window._indexData.documents) {
|
for (const d of window._indexData.documents) {
|
||||||
if (d.type === 'folder' && d.items) {
|
if (d.type === 'folder' && d.items) {
|
||||||
@@ -577,7 +623,7 @@ class DocumentService {
|
|||||||
}
|
}
|
||||||
|
|
||||||
const doc = this.indexService.findDocumentByTitle(
|
const doc = this.indexService.findDocumentByTitle(
|
||||||
window._indexData.documents,
|
window._indexData.documents,
|
||||||
targetTitle
|
targetTitle
|
||||||
);
|
);
|
||||||
return doc ? `[${displayText || doc.title}](?${doc.slug})` : match;
|
return doc ? `[${displayText || doc.title}](?${doc.slug})` : match;
|
||||||
@@ -587,14 +633,14 @@ class DocumentService {
|
|||||||
processImages(content, basePath) {
|
processImages(content, basePath) {
|
||||||
return content.replace(/!\[\[(.*?)\]\]/g, (match, filename) => {
|
return content.replace(/!\[\[(.*?)\]\]/g, (match, filename) => {
|
||||||
const mediaPath = `./docs/images/${filename}`;
|
const mediaPath = `./docs/images/${filename}`;
|
||||||
|
|
||||||
if (filename.toLowerCase().endsWith('.mp4')) {
|
if (filename.toLowerCase().endsWith('.mp4')) {
|
||||||
return `\n<video controls width="100%">
|
return `\n<video controls width="100%">
|
||||||
<source src="${mediaPath}" type="video/mp4">
|
<source src="${mediaPath}" type="video/mp4">
|
||||||
Your browser does not support the video tag.
|
Your browser does not support the video tag.
|
||||||
</video>\n\n`;
|
</video>\n\n`;
|
||||||
}
|
}
|
||||||
|
|
||||||
return `\n\n\n`;
|
return `\n\n\n`;
|
||||||
});
|
});
|
||||||
}
|
}
|
||||||
@@ -610,15 +656,12 @@ class NavigationService {
|
|||||||
setupEventListeners() {
|
setupEventListeners() {
|
||||||
window.addEventListener('popstate', async () => {
|
window.addEventListener('popstate', async () => {
|
||||||
const search = window.location.search;
|
const search = window.location.search;
|
||||||
// If no search params or just '?', use default page
|
const hash = window.location.hash;
|
||||||
const slug = (search === '' || search === '?') ?
|
const slug = (search === '' || search === '?') ?
|
||||||
window._indexData.defaultPage :
|
window._indexData.defaultPage :
|
||||||
search.replace(/^\?/, '');
|
search.replace(/^\?/, '').split('#')[0];
|
||||||
|
|
||||||
this.eventBus.emit('navigation:requested', {
|
this.eventBus.emit('navigation:requested', { slug, hash });
|
||||||
slug,
|
|
||||||
hash: window.location.hash
|
|
||||||
});
|
|
||||||
});
|
});
|
||||||
|
|
||||||
document.addEventListener('click', async (e) => {
|
document.addEventListener('click', async (e) => {
|
||||||
@@ -626,7 +669,6 @@ class NavigationService {
|
|||||||
if (target) {
|
if (target) {
|
||||||
e.preventDefault();
|
e.preventDefault();
|
||||||
const slug = target.href.split('?').pop();
|
const slug = target.href.split('?').pop();
|
||||||
// Use clean URL format without equal sign
|
|
||||||
history.pushState(null, '', `?${slug}`);
|
history.pushState(null, '', `?${slug}`);
|
||||||
this.eventBus.emit('navigation:requested', { slug });
|
this.eventBus.emit('navigation:requested', { slug });
|
||||||
}
|
}
|
||||||
@@ -642,14 +684,14 @@ class Documentation {
|
|||||||
this.domService = new DOMService(this.eventBus);
|
this.domService = new DOMService(this.eventBus);
|
||||||
this.documentService = new DocumentService(this.eventBus, this.indexService);
|
this.documentService = new DocumentService(this.eventBus, this.indexService);
|
||||||
this.navigationService = new NavigationService(this.eventBus, this.documentService);
|
this.navigationService = new NavigationService(this.eventBus, this.documentService);
|
||||||
|
|
||||||
this.setupEventListeners();
|
this.setupEventListeners();
|
||||||
}
|
}
|
||||||
|
|
||||||
setupEventListeners() {
|
setupEventListeners() {
|
||||||
this.eventBus.on('navigation:requested', async ({ slug }) => {
|
this.eventBus.on('navigation:requested', async ({ slug, hash }) => {
|
||||||
slug = slug.replace(/^[?=]/, '');
|
slug = slug.replace(/^[?=]/, '');
|
||||||
await this.loadDocumentBySlug(slug);
|
await this.loadDocumentBySlug(slug, hash);
|
||||||
});
|
});
|
||||||
|
|
||||||
this.eventBus.on('document:load', async ({ path }) => {
|
this.eventBus.on('document:load', async ({ path }) => {
|
||||||
@@ -676,30 +718,29 @@ class Documentation {
|
|||||||
try {
|
try {
|
||||||
const response = await fetch('index.json');
|
const response = await fetch('index.json');
|
||||||
if (!response.ok) throw new Error(`HTTP error! status: ${response.status}`);
|
if (!response.ok) throw new Error(`HTTP error! status: ${response.status}`);
|
||||||
|
|
||||||
const data = await response.json();
|
const data = await response.json();
|
||||||
this.indexData = data;
|
this.indexData = data;
|
||||||
window._indexData = data;
|
window._indexData = data;
|
||||||
|
|
||||||
this.searchService.buildSearchIndex(this.indexData.documents);
|
this.searchService.buildSearchIndex(this.indexData.documents);
|
||||||
this.domService.setupSearch(this.searchService);
|
this.domService.setupSearch(this.searchService);
|
||||||
|
|
||||||
this.populateAuthorInfo(data.author);
|
this.populateAuthorInfo(data.author);
|
||||||
window.originalDocTitle = data.metadata.site_name || 'Documentation';
|
window.originalDocTitle = data.metadata.site_name || 'Documentation';
|
||||||
document.title = window.originalDocTitle;
|
document.title = window.originalDocTitle;
|
||||||
|
|
||||||
this.domService.elements.fileIndex.innerHTML = '';
|
this.domService.elements.fileIndex.innerHTML = '';
|
||||||
this.indexData.documents.forEach(doc =>
|
this.indexData.documents.forEach(doc =>
|
||||||
this.domService.createFileIndexItem(doc, this.domService.elements.fileIndex));
|
this.domService.createFileIndexItem(doc, this.domService.elements.fileIndex));
|
||||||
|
|
||||||
// Simplified URL parameter handling
|
|
||||||
const search = window.location.search;
|
const search = window.location.search;
|
||||||
const slug = search === '' || search === '?'
|
const slug = search === '' || search === '?'
|
||||||
? this.indexData.defaultPage
|
? this.indexData.defaultPage
|
||||||
: search.replace(/^\?/, '');
|
: search.replace(/^\?/, '');
|
||||||
|
|
||||||
await this.loadDocumentBySlug(slug);
|
await this.loadDocumentBySlug(slug);
|
||||||
|
|
||||||
if (window.location.hash) {
|
if (window.location.hash) {
|
||||||
setTimeout(() => {
|
setTimeout(() => {
|
||||||
const element = document.getElementById(window.location.hash.slice(1));
|
const element = document.getElementById(window.location.hash.slice(1));
|
||||||
@@ -735,45 +776,44 @@ class Documentation {
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
async loadDocumentBySlug(slug) {
|
async loadDocumentBySlug(slug, hash) {
|
||||||
const doc = this.indexService.findDocumentBySlug(this.indexData.documents, slug);
|
const [baseSlug] = slug.split('#');
|
||||||
|
const doc = this.indexService.findDocumentBySlug(this.indexData.documents, baseSlug);
|
||||||
|
|
||||||
if (!doc) {
|
if (!doc) {
|
||||||
this.domService.setError(`Document not found: ${slug}`);
|
this.domService.setError(`Document not found: ${baseSlug}`);
|
||||||
return;
|
return;
|
||||||
}
|
}
|
||||||
|
|
||||||
if (doc.type === 'folder') {
|
if (doc.type === 'folder') {
|
||||||
if (doc.path) {
|
if (doc.path) {
|
||||||
await this.loadDocument(doc.path);
|
await this.loadDocument(doc.path, hash);
|
||||||
} else if (doc.items?.length > 0) {
|
} else if (doc.items?.length > 0) {
|
||||||
await this.loadDocument(doc.items[0].path);
|
await this.loadDocument(doc.items[0].path, hash);
|
||||||
} else {
|
} else {
|
||||||
this.domService.setError('This folder is empty.');
|
this.domService.setError('This folder is empty.');
|
||||||
}
|
}
|
||||||
return;
|
return;
|
||||||
}
|
}
|
||||||
|
|
||||||
await this.loadDocument(doc.path);
|
await this.loadDocument(doc.path, hash);
|
||||||
}
|
}
|
||||||
|
|
||||||
async loadDocument(path) {
|
async loadDocument(path, hash, fromSearch = false) {
|
||||||
try {
|
try {
|
||||||
const { content, metadata, marked, title } = await this.documentService.loadDocument(path);
|
const { content, metadata, marked, title } = await this.documentService.loadDocument(path);
|
||||||
|
|
||||||
this.domService.setTitle(title);
|
this.domService.setTitle(title);
|
||||||
this.domService.setContent(marked.parse(content));
|
this.domService.setContent(marked.parse(content));
|
||||||
this.domService.updateActiveDocument(path);
|
this.domService.updateActiveDocument(path);
|
||||||
|
|
||||||
const headings = document.querySelectorAll('h2, h3, h4, h5, h6');
|
const headings = document.querySelectorAll('h2, h3, h4, h5, h6');
|
||||||
const headingLinks = this.domService.createOutline(headings);
|
const headingLinks = this.domService.createOutline(headings);
|
||||||
|
|
||||||
// Add click handlers to all headers
|
|
||||||
headings.forEach(heading => {
|
headings.forEach(heading => {
|
||||||
heading.addEventListener('click', (e) => {
|
heading.addEventListener('click', (e) => {
|
||||||
// Don't trigger if clicking on fold toggle
|
|
||||||
if (e.target.closest('svg') || e.target.closest('.header-anchor')) return;
|
if (e.target.closest('svg') || e.target.closest('.header-anchor')) return;
|
||||||
|
|
||||||
const id = heading.id;
|
const id = heading.id;
|
||||||
if (id) {
|
if (id) {
|
||||||
history.pushState(null, '', `${window.location.pathname}${window.location.search}#${id}`);
|
history.pushState(null, '', `${window.location.pathname}${window.location.search}#${id}`);
|
||||||
@@ -784,17 +824,21 @@ class Documentation {
|
|||||||
}
|
}
|
||||||
});
|
});
|
||||||
});
|
});
|
||||||
|
|
||||||
this.setupScrollObserver(headings, headingLinks);
|
this.setupScrollObserver(headings, headingLinks);
|
||||||
|
|
||||||
window._currentPath = path;
|
window._currentPath = path;
|
||||||
|
|
||||||
if (window.location.hash) {
|
if (hash) {
|
||||||
const element = document.getElementById(window.location.hash.slice(1));
|
const element = document.getElementById(hash.slice(1));
|
||||||
if (element) {
|
if (element) {
|
||||||
|
const delay = fromSearch ? 300 : 100;
|
||||||
setTimeout(() => {
|
setTimeout(() => {
|
||||||
this.domService.scrollToElement(element);
|
this.domService.scrollToElement(element);
|
||||||
}, 100);
|
element.classList.remove('highlight');
|
||||||
|
void element.offsetWidth;
|
||||||
|
element.classList.add('highlight');
|
||||||
|
}, delay);
|
||||||
}
|
}
|
||||||
} else {
|
} else {
|
||||||
window.scrollTo({ top: 0, behavior: 'smooth' });
|
window.scrollTo({ top: 0, behavior: 'smooth' });
|
||||||
@@ -815,7 +859,7 @@ class Documentation {
|
|||||||
this.domService.elements.outline
|
this.domService.elements.outline
|
||||||
.querySelectorAll('a')
|
.querySelectorAll('a')
|
||||||
.forEach(a => a.classList.remove('active'));
|
.forEach(a => a.classList.remove('active'));
|
||||||
|
|
||||||
const link = headingLinks.get(visibleHeadings[0].target);
|
const link = headingLinks.get(visibleHeadings[0].target);
|
||||||
if (link) link.classList.add('active');
|
if (link) link.classList.add('active');
|
||||||
}
|
}
|
||||||
|
|||||||
Reference in New Issue
Block a user