Update app.js
This commit is contained in:
parent
aa45352f0d
commit
ea59a32544
1 changed files with 105 additions and 176 deletions
251
public/app.js
251
public/app.js
|
|
@ -1,191 +1,120 @@
|
||||||
// Elements
|
let INDEX, CURRENT_PATH=null, PATH_TO_EL=new Map();
|
||||||
const sidebar = document.getElementById("sidebar");
|
|
||||||
const treeEl=document.getElementById("tree");
|
const treeEl=document.getElementById("tree");
|
||||||
const metaEl = document.getElementById("meta");
|
|
||||||
const mdView=document.getElementById("mdView");
|
const mdView=document.getElementById("mdView");
|
||||||
const htmlView = document.getElementById("htmlView");
|
const iframe=document.getElementById("htmlView");
|
||||||
const errorBox = document.getElementById("errorBox");
|
const metaLine=document.getElementById("meta");
|
||||||
const sortSel = document.getElementById("sortSel");
|
const sortSel=document.getElementById("sort");
|
||||||
const filterSel = document.getElementById("filterSel");
|
const filterSel=document.getElementById("filter");
|
||||||
const searchBox = document.getElementById("searchBox");
|
const searchBox=document.getElementById("search");
|
||||||
const navToggle = document.getElementById("navToggle");
|
const prevBtn=document.getElementById("prev");
|
||||||
const backdrop = document.getElementById("backdrop");
|
const nextBtn=document.getElementById("next");
|
||||||
|
|
||||||
// State
|
|
||||||
let INDEX = null;
|
|
||||||
let CURRENT_PATH = null;
|
|
||||||
let PATH_TO_EL = new Map();
|
|
||||||
|
|
||||||
// Drawer controls (mobile)
|
|
||||||
navToggle.addEventListener("click", () => sidebar.classList.toggle("open"));
|
|
||||||
backdrop.addEventListener("click", () => sidebar.classList.remove("open"));
|
|
||||||
|
|
||||||
// -------- Boot --------
|
|
||||||
window.addEventListener("DOMContentLoaded", async () => {
|
|
||||||
await loadIndex();
|
|
||||||
if (!INDEX) return;
|
|
||||||
|
|
||||||
sortSel.addEventListener("change", rebuildTree);
|
|
||||||
filterSel.addEventListener("change", rebuildTree);
|
|
||||||
searchBox.addEventListener("input", rebuildTree);
|
|
||||||
|
|
||||||
window.addEventListener("popstate", () => {
|
|
||||||
const hp = location.hash.startsWith("#=") ? location.hash.slice(2) : null;
|
|
||||||
if (hp) openPath(hp, {push:false});
|
|
||||||
});
|
|
||||||
|
|
||||||
const initial = location.hash.startsWith("#=") ? location.hash.slice(2) : null;
|
|
||||||
if (initial) openPath(initial, {push:false});
|
|
||||||
else autoOpenLatest();
|
|
||||||
});
|
|
||||||
|
|
||||||
// -------- Data loading --------
|
|
||||||
async function loadIndex(){
|
async function loadIndex(){
|
||||||
try{
|
const res=await fetch("/index.json",{cache:"no-store"});
|
||||||
const res = await fetch("index.json",{cache:"no-store"});
|
|
||||||
INDEX=await res.json();
|
INDEX=await res.json();
|
||||||
|
populateFilters();
|
||||||
rebuildTree();
|
rebuildTree();
|
||||||
}catch(e){
|
window.addEventListener("popstate",()=>{const hp=location.hash.slice(2);if(hp)openPath(hp);});
|
||||||
treeEl.innerHTML = "<p style='color:#ff7a7a'>index.json missing. run the build.</p>";
|
const init=location.hash.slice(2)||INDEX.flat.sort((a,b)=>b.mtime-a.mtime)[0].path;
|
||||||
|
openPath(init);
|
||||||
}
|
}
|
||||||
|
function populateFilters(){
|
||||||
|
const cats=new Set(INDEX.sections);
|
||||||
|
filterSel.innerHTML='<option value="all">All</option>';
|
||||||
|
for(const c of cats){const o=document.createElement("option");o.value=c;o.textContent=c;filterSel.appendChild(o);}
|
||||||
}
|
}
|
||||||
|
|
||||||
// -------- Tree building / sorting / filtering --------
|
|
||||||
function rebuildTree(){
|
function rebuildTree(){
|
||||||
if (!INDEX) return;
|
|
||||||
PATH_TO_EL.clear();
|
|
||||||
treeEl.innerHTML="";
|
treeEl.innerHTML="";
|
||||||
|
|
||||||
const sort = sortSel.value;
|
|
||||||
const filter=filterSel.value;
|
const filter=filterSel.value;
|
||||||
const query = searchBox.value.trim().toLowerCase();
|
const sort=sortSel.value;
|
||||||
|
const query=searchBox.value.toLowerCase();
|
||||||
const roots = INDEX.tree
|
for(const dir of INDEX.tree){
|
||||||
.filter(d => filter==="all" || d.name===filter)
|
if(filter!=="all"&&dir.name!==filter)continue;
|
||||||
.map(d => deepClone(d));
|
treeEl.appendChild(renderNode(dir,sort,query));
|
||||||
|
|
||||||
roots.forEach(r => {
|
|
||||||
applySort(r, sort);
|
|
||||||
const filtered = applySearch(r, query);
|
|
||||||
if (filtered) treeEl.appendChild(renderNode(filtered));
|
|
||||||
});
|
|
||||||
|
|
||||||
// Auto-expand top dirs
|
|
||||||
treeEl.querySelectorAll(".dir").forEach(d => d.classList.add("open"));
|
|
||||||
}
|
}
|
||||||
|
|
||||||
function deepClone(obj){ return JSON.parse(JSON.stringify(obj)); }
|
|
||||||
function getDate(n){ return n.mtime || 0; }
|
|
||||||
|
|
||||||
function applySort(dir, sort) {
|
|
||||||
if (dir.type !== "dir") return;
|
|
||||||
const cmp =
|
|
||||||
sort==="alpha" ? (a,b)=> (a.title||a.name).localeCompare(b.title||b.name) :
|
|
||||||
sort==="old" ? (a,b)=> getDate(a)-getDate(b) :
|
|
||||||
(a,b)=> getDate(b)-getDate(a);
|
|
||||||
dir.children.sort((a,b)=>{
|
|
||||||
if (a.type!==b.type){ return a.type==="dir" ? -1 : 1; } // dirs first
|
|
||||||
return cmp(a,b);
|
|
||||||
});
|
|
||||||
dir.children.forEach(c => c.type==="dir" && applySort(c, sort));
|
|
||||||
}
|
}
|
||||||
|
function renderNode(node,sort,query){
|
||||||
function applySearch(node, q) {
|
|
||||||
if (!q) return node;
|
|
||||||
if (node.type==="file"){
|
|
||||||
const t = (node.title||node.name).toLowerCase();
|
|
||||||
return t.includes(q)? node : null;
|
|
||||||
}
|
|
||||||
const kids = node.children.map(c=>applySearch(c,q)).filter(Boolean);
|
|
||||||
if (!kids.length) return null;
|
|
||||||
node.children = kids;
|
|
||||||
return node;
|
|
||||||
}
|
|
||||||
|
|
||||||
// Recursive renderer
|
|
||||||
function renderNode(node){
|
|
||||||
if(node.type==="dir"){
|
if(node.type==="dir"){
|
||||||
const wrap = document.createElement("div");
|
const div=document.createElement("div");
|
||||||
wrap.className = "dir";
|
div.className="dir";div.setAttribute("aria-expanded","false");
|
||||||
wrap.setAttribute("role","treeitem");
|
const lbl=document.createElement("span");
|
||||||
const lbl = document.createElement("div");
|
lbl.className="label";lbl.textContent=node.name;
|
||||||
lbl.className = "label";
|
lbl.addEventListener("click",()=>{
|
||||||
lbl.textContent = node.name;
|
const idx=node.children.find(c=>/^index\.(md|html)$/.test(c.name));
|
||||||
lbl.addEventListener("click", () => wrap.classList.toggle("open"));
|
if(idx)openPath(idx.path);
|
||||||
const kids = document.createElement("div");
|
else div.classList.toggle("open");
|
||||||
kids.className = "children";
|
});
|
||||||
node.children.forEach(c => kids.appendChild(renderNode(c)));
|
div.appendChild(lbl);
|
||||||
wrap.append(lbl, kids);
|
const kids=document.createElement("div");kids.className="children";
|
||||||
return wrap;
|
const sorted=[...node.children].sort((a,b)=>{
|
||||||
} else {
|
if(sort==="name")return a.name.localeCompare(b.name);
|
||||||
|
return sort==="old"?a.mtime-b.mtime:b.mtime-a.mtime;
|
||||||
|
});
|
||||||
|
for(const c of sorted){
|
||||||
|
if(c.type==="file"){
|
||||||
|
if(query&&!c.title.toLowerCase().includes(query))continue;
|
||||||
const a=document.createElement("a");
|
const a=document.createElement("a");
|
||||||
a.className = "file";
|
a.className="file";a.textContent=c.title;
|
||||||
a.setAttribute("role","treeitem");
|
a.addEventListener("click",e=>{e.preventDefault();openPath(c.path);});
|
||||||
a.href = `#=${node.path}`;
|
PATH_TO_EL.set(c.path,a);
|
||||||
a.innerHTML = `${node.pinned?'<span class="pin">PIN</span> ':''}${escapeHtml(node.title||node.name)}`;
|
kids.appendChild(a);
|
||||||
a.addEventListener("click", e => { e.preventDefault(); openPath(node.path); });
|
}else kids.appendChild(renderNode(c,sort,query));
|
||||||
PATH_TO_EL.set(node.path, a);
|
|
||||||
return a;
|
|
||||||
}
|
}
|
||||||
|
div.appendChild(kids);
|
||||||
|
return div;
|
||||||
|
}
|
||||||
|
return document.createTextNode("");
|
||||||
}
|
}
|
||||||
|
|
||||||
function escapeHtml(s){ return s.replace(/[&<>"']/g,c=>({ "&":"&","<":"<",">":">","\"":""","'":"'" }[c])); }
|
async function openPath(path){
|
||||||
|
|
||||||
// -------- Opening / rendering files --------
|
|
||||||
function autoOpenLatest(){
|
|
||||||
if (!INDEX?.flat?.length) return;
|
|
||||||
const latest = [...INDEX.flat].sort((a,b)=>getDate(b)-getDate(a))[0];
|
|
||||||
if (latest) openPath(latest.path,{push:false});
|
|
||||||
}
|
|
||||||
|
|
||||||
async function openPath(path,{push=true}={}){
|
|
||||||
if (!INDEX) return;
|
|
||||||
if(path===CURRENT_PATH)return;
|
if(path===CURRENT_PATH)return;
|
||||||
const f = INDEX.flat.find(x=>x.path===path);
|
|
||||||
if (!f){ showError("File not found."); return; }
|
|
||||||
|
|
||||||
CURRENT_PATH=path;
|
CURRENT_PATH=path;
|
||||||
if (push && location.hash!==`#=${path}`) history.pushState(null,"",`#=${path}`);
|
if(location.hash!==`#=${path}`)history.pushState(null,"",`#=${path}`);
|
||||||
|
let f=INDEX.flat.find(x=>x.path===path);
|
||||||
hideError();
|
if(!f){metaLine.textContent="Not found";return;}
|
||||||
|
metaLine.textContent=`${f.pinned?"📌 ":""}${new Date(f.mtime).toISOString().slice(0,10)} • ${f.name}`;
|
||||||
|
if(f.ext===".md")await renderMarkdown(f.path);
|
||||||
|
else renderHTML(f.path);
|
||||||
setActive(path);
|
setActive(path);
|
||||||
metaEl.textContent = `${f.pinned?"Pinned • ":""}${new Date(getDate(f)).toISOString().slice(0,10)} • ${f.title||f.name}`;
|
updatePager();
|
||||||
|
if(window.innerWidth<900)document.querySelector(".sidebar").classList.remove("open");
|
||||||
if (f.ext === ".md") {
|
|
||||||
await renderMarkdown(path);
|
|
||||||
} else {
|
|
||||||
renderHTML(path);
|
|
||||||
}
|
}
|
||||||
|
|
||||||
// close drawer on mobile
|
|
||||||
if (window.innerWidth < 900) sidebar.classList.remove("open");
|
|
||||||
}
|
|
||||||
|
|
||||||
async function renderMarkdown(path){
|
async function renderMarkdown(path){
|
||||||
htmlView.style.display="none";
|
const res=await fetch(path);
|
||||||
mdView.style.display="block";
|
if(!res.ok){mdView.innerHTML="<p>File not found</p>";return;}
|
||||||
try{
|
const text=await res.text();
|
||||||
const res = await fetch(path,{cache:"no-store"});
|
const html=(window.marked?window.marked.parse(text):text);
|
||||||
if (!res.ok) throw new Error(res.statusText);
|
const safe=(window.DOMPurify?window.DOMPurify.sanitize(html):html);
|
||||||
const txt = await res.text();
|
mdView.innerHTML=safe;
|
||||||
const html = window.DOMPurify?.sanitize(window.marked?.parse(txt) || txt) || txt;
|
iframe.style.display="none";mdView.style.display="block";
|
||||||
mdView.innerHTML = html;
|
|
||||||
}catch(e){
|
|
||||||
showError("Failed to load Markdown.");
|
|
||||||
}
|
}
|
||||||
}
|
|
||||||
|
|
||||||
function renderHTML(path){
|
function renderHTML(path){
|
||||||
mdView.style.display="none";
|
iframe.src=path;
|
||||||
htmlView.style.display="block";
|
iframe.style.display="block";mdView.style.display="none";
|
||||||
htmlView.src = path;
|
|
||||||
}
|
}
|
||||||
|
|
||||||
function setActive(path){
|
function setActive(path){
|
||||||
document.querySelectorAll(".file.active").forEach(el=>el.classList.remove("active"));
|
document.querySelectorAll(".file.active").forEach(el=>el.classList.remove("active"));
|
||||||
const el=PATH_TO_EL.get(path);
|
const el=PATH_TO_EL.get(path);
|
||||||
if (el) el.classList.add("active");
|
if(el){el.classList.add("active");let p=el.parentElement;while(p&&p!==treeEl){if(p.classList.contains("children"))p.parentElement.classList.add("open");p=p.parentElement;}}
|
||||||
}
|
}
|
||||||
|
function updatePager(){
|
||||||
function showError(msg){ errorBox.textContent = msg; errorBox.hidden = false; }
|
const list=INDEX.flat.filter(f=>f.ext===".md"||f.ext===".html").sort((a,b)=>b.mtime-a.mtime);
|
||||||
function hideError(){ errorBox.hidden = true; }
|
const i=list.findIndex(x=>x.path===CURRENT_PATH);
|
||||||
|
prevBtn.disabled=i<=0;nextBtn.disabled=i>=list.length-1;
|
||||||
|
prevBtn.onclick=()=>{if(i>0)openPath(list[i-1].path);};
|
||||||
|
nextBtn.onclick=()=>{if(i<list.length-1)openPath(list[i+1].path);};
|
||||||
|
}
|
||||||
|
let searchTimer;
|
||||||
|
searchBox.addEventListener("input",()=>{clearTimeout(searchTimer);searchTimer=setTimeout(rebuildTree,300);});
|
||||||
|
sortSel.addEventListener("change",rebuildTree);
|
||||||
|
filterSel.addEventListener("change",rebuildTree);
|
||||||
|
document.body.addEventListener("click",e=>{
|
||||||
|
const a=e.target.closest("a[href]");
|
||||||
|
if(!a)return;
|
||||||
|
const href=a.getAttribute("href");
|
||||||
|
if(href.startsWith("/")&&!href.startsWith("//")&&!a.target){
|
||||||
|
e.preventDefault();
|
||||||
|
openPath(href.replace(/^\//,""));
|
||||||
|
}
|
||||||
|
});
|
||||||
|
window.addEventListener("DOMContentLoaded",loadIndex);
|
||||||
Loading…
Add table
Add a link
Reference in a new issue