This commit is contained in:
Mark Randall Havens 2025-11-09 19:58:05 +00:00
parent 480da77bb1
commit 7749e18252

View file

@ -1,60 +1,65 @@
/** /**
* app.js v3.3.3 FIELD COMMENTARY EDITION * app.js v3.3.4 DIAGNOSTIC RESONANCE
* High-coherence, readable, maintainable blueprint. * High-coherence, readable, maintainable.
* No hacks. No surgery. Only truth. * No hacks. No surgery. Only truth.
* Enhanced with modular sanitization, resilient recursion, and inline rationale. * Now with diagnostic overlays for rupture illumination.
*
* ΔFIELD: This script orchestrates the breathing field: navigation, routing, rendering.
* Rationale: Dependency-free; async fetches for dynamic content; stateful only where essential (e.g., sidebar).
* Assumptions: index.json provides metadata; marked.js for MD; DOM elements pre-exist in HTML skeleton.
*/ */
const els = { const els = {
menuBtn: document.getElementById("menuBtn"), /* ΔHORIZON: Toggle for sidebar. */ menuBtn: document.getElementById("menuBtn"),
primaryNav: document.getElementById("primaryNav"), /* ΔHORIZON: Top-level sections. */ primaryNav: document.getElementById("primaryNav"),
subNav: document.getElementById("subNav"), /* ΔRECURSION: Nested sub-horizons. */ subNav: document.getElementById("subNav"),
sectionSelect: document.getElementById("sectionSelect"), /* ΔFIELD: Filter by section. */ sectionSelect: document.getElementById("sectionSelect"),
tagSelect: document.getElementById("tagSelect"), /* ΔFIELD: Multi-tag filter. */ tagSelect: document.getElementById("tagSelect"),
sortSelect: document.getElementById("sortSelect"), /* ΔRHYTHM: Time-based sorting. */ sortSelect: document.getElementById("sortSelect"),
searchMode: document.getElementById("searchMode"), /* ΔTRUTH: Scope of search. */ searchMode: document.getElementById("searchMode"),
searchBox: document.getElementById("searchBox"), /* ΔTRUTH: Query input. */ searchBox: document.getElementById("searchBox"),
postList: document.getElementById("postList"), /* ΔFIELD: Dynamic post enumeration. */ postList: document.getElementById("postList"),
viewer: document.getElementById("viewer"), /* ΔFIELD: Content rendering canvas. */ viewer: document.getElementById("viewer"),
content: document.getElementById("content"), /* ΔHORIZON: Main wrapper for click events. */ content: document.getElementById("content"),
toggleControls: document.getElementById("toggleControls"), /* ΔHORIZON: Filter panel toggle. */ toggleControls: document.getElementById("toggleControls"),
filterPanel: document.getElementById("filterPanel") /* ΔFIELD: Collapsible filters. */ filterPanel: document.getElementById("filterPanel")
}; };
let indexData = null; /* ΔRECURSION: Cached metadata for all operations. */ let indexData = null;
let sidebarOpen = false; /* ΔBREATH: State for mobile sidebar. */ let sidebarOpen = false;
let currentParent = null; /* ΔRECURSION: Track for subnav rendering. */ let currentParent = null;
let indexFiles = null; // Cached index files /* ΔRECURSION: Pre-filtered for quick lookups. */ let indexFiles = null; // Cached index files
// ΔTRUTH: Diagnostic overlay for error/clarity banners.
// Rationale: Fixed red banner for immediate visibility; z-index above topbar.
function showDiagnostic(message) {
const banner = document.createElement('div');
banner.style = 'position: fixed; top: 0; left: 0; width: 100%; background: #ff4d4d; color: white; padding: 10px; z-index: 1001; text-align: center; font-weight: bold;';
banner.innerHTML = message;
document.body.appendChild(banner);
}
// === INITIALIZATION === // === INITIALIZATION ===
/* ΔFIELD: Async init loads data and wires UI; fallback for errors.
* Rationale: Single entry point; console log as harmony affirmation. */
async function init() { async function init() {
try { try {
indexData = await (await fetch("index.json")).json(); /* ΔTRUTH: Source of all content truth. */ indexData = await (await fetch("index.json")).json();
indexFiles = indexData.flat.filter(f => f.isIndex); /* ΔRECURSION: Cache for directory indices. */ if (indexData.flat.length === 0) {
populateNav(); /* ΔHORIZON: Build primary nav from sections. */ showDiagnostic('index.json loaded but no content files found. Add .md or .html files to public/ sections and run node tools/generate-index.mjs.');
populateSections(); /* ΔFIELD: Populate section dropdown. */ }
populateTags(); /* ΔFIELD: Populate tag multi-select. */ indexFiles = indexData.flat.filter(f => f.isIndex);
wireUI(); /* ΔHORIZON: Attach all event listeners. */ populateNav();
renderList(); /* ΔFIELD: Initial post list render. */ populateSections();
handleHash(); /* ΔRECURSION: Process current URL state. */ populateTags();
window.addEventListener("hashchange", handleHash); /* ΔRECURSION: Listen for navigation. */ wireUI();
console.info('%cThe Fold Within: Harmony sustained.', 'color:#e0b84b'); /* ΔFIELD: Dev resonance. */ renderList();
handleHash();
window.addEventListener("hashchange", handleHash);
console.info('%cThe Fold Within: Harmony sustained.', 'color:#e0b84b');
} catch (e) { } catch (e) {
els.viewer.innerHTML = "<h1>Error</h1><p>Failed to load site data.</p>"; /* ΔTRUTH: Graceful failure. */ showDiagnostic('Failed to load index.json. Check Network tab for 404 or console for errors. Ensure deployed from public/ directory and index.json is generated.');
els.viewer.innerHTML = "<h1>Error</h1><p>Failed to load site data. See diagnostic banner for fixes.</p>";
} }
} }
// === NAVIGATION === // === NAVIGATION ===
/* ΔHORIZON: Dynamically build primary nav from unique top-level sections.
* Rationale: Sort for alphabetical order; capitalize for aesthetics. */
function populateNav() { function populateNav() {
els.primaryNav.innerHTML = '<a href="#/">Home</a>'; /* ΔFIELD: Fixed home anchor. */ els.primaryNav.innerHTML = '<a href="#/">Home</a>';
const navSections = [...new Set( const navSections = [...new Set(
indexData.flat indexData.flat
.filter(f => f.isIndex && f.path.split("/").length > 1) .filter(f => f.isIndex && f.path.split("/").length > 1)
@ -65,8 +70,6 @@ function populateNav() {
}); });
} }
/* ΔFIELD: Section dropdown with default to 'posts' if available.
* Rationale: 'all' option for broad views. */
function populateSections() { function populateSections() {
els.sectionSelect.innerHTML = '<option value="all">All Sections</option>'; els.sectionSelect.innerHTML = '<option value="all">All Sections</option>';
indexData.sections.forEach(s => { indexData.sections.forEach(s => {
@ -79,8 +82,6 @@ function populateSections() {
if (defaultSection) els.sectionSelect.value = defaultSection; if (defaultSection) els.sectionSelect.value = defaultSection;
} }
/* ΔFIELD: Tags as multi-select options.
* Rationale: Lowercase normalization in filters for case-insensitivity. */
function populateTags() { function populateTags() {
indexData.tags.forEach(t => { indexData.tags.forEach(t => {
const opt = document.createElement("option"); const opt = document.createElement("option");
@ -90,42 +91,38 @@ function populateTags() {
} }
// === UI WIRING === // === UI WIRING ===
/* ΔHORIZON: Attach listeners for interactivity.
* Rationale: Centralized wiring; mobile-specific sidebar close on content click. */
function wireUI() { function wireUI() {
els.menuBtn.addEventListener("click", () => { els.menuBtn.addEventListener("click", () => {
sidebarOpen = !sidebarOpen; sidebarOpen = !sidebarOpen;
document.body.classList.toggle("sidebar-open", sidebarOpen); /* ΔBREATH: Class toggle for CSS-driven motion. */ document.body.classList.toggle("sidebar-open", sidebarOpen);
}); });
els.toggleControls.addEventListener("click", () => { els.toggleControls.addEventListener("click", () => {
const open = els.filterPanel.open; const open = els.filterPanel.open;
els.filterPanel.open = !open; els.filterPanel.open = !open;
els.toggleControls.textContent = open ? "Filters" : "Hide"; /* ΔFIELD: Dynamic label for state clarity. */ els.toggleControls.textContent = open ? "Filters" : "Hide";
}); });
els.sectionSelect.addEventListener("change", () => { els.sectionSelect.addEventListener("change", () => {
renderList(); renderList();
if (els.sectionSelect.value !== "all") loadDefaultForSection(els.sectionSelect.value); /* ΔRECURSION: Auto-load default on section change. */ if (els.sectionSelect.value !== "all") loadDefaultForSection(els.sectionSelect.value);
}); });
[els.tagSelect, els.sortSelect, els.searchMode].forEach(el => el.addEventListener("change", renderList)); [els.tagSelect, els.sortSelect, els.searchMode].forEach(el => el.addEventListener("change", renderList));
els.searchBox.addEventListener("input", renderList); /* ΔTRUTH: Real-time filtering on input. */ els.searchBox.addEventListener("input", renderList);
// Close sidebar on content click (mobile) // Close sidebar on content click (mobile)
els.content.addEventListener("click", (e) => { els.content.addEventListener("click", (e) => {
if (window.innerWidth < 1024 && document.body.classList.contains("sidebar-open")) { if (window.innerWidth < 1024 && document.body.classList.contains("sidebar-open")) {
if (!e.target.closest("#sidebar")) { if (!e.target.closest("#sidebar")) {
document.body.classList.remove("sidebar-open"); document.body.classList.remove("sidebar-open");
sidebarOpen = false; /* ΔHORIZON: Gesture respect for mobile usability. */ sidebarOpen = false;
} }
} }
}); });
} }
// === LIST RENDERING === // === LIST RENDERING ===
/* ΔFIELD: Dynamic filtering and sorting of posts.
* Rationale: Chainable filters; fallback message; pinned denoted with 'Star'. */
function renderList() { function renderList() {
const section = els.sectionSelect.value; const section = els.sectionSelect.value;
const tags = Array.from(els.tagSelect.selectedOptions).map(o => o.value.toLowerCase()); const tags = Array.from(els.tagSelect.selectedOptions).map(o => o.value.toLowerCase());
@ -133,29 +130,30 @@ function renderList() {
const mode = els.searchMode.value; const mode = els.searchMode.value;
const query = els.searchBox.value.toLowerCase(); const query = els.searchBox.value.toLowerCase();
let posts = indexData.flat.filter(p => !p.isIndex); /* ΔTRUTH: Exclude indices for content focus. */ let posts = indexData.flat.filter(p => !p.isIndex);
if (section !== "all") posts = posts.filter(p => p.path.split('/')[0] === section); if (section !== "all") posts = posts.filter(p => p.path.split('/')[0] === section);
if (tags.length) posts = posts.filter(p => tags.every(t => p.tags.includes(t))); /* ΔFIELD: AND logic for tags. */ if (tags.length) posts = posts.filter(p => tags.every(t => p.tags.includes(t)));
if (query) { if (query) {
posts = posts.filter(p => { posts = posts.filter(p => {
const text = mode === "content" ? p.title + " " + p.excerpt : p.title; const text = mode === "content" ? p.title + " " + p.excerpt : p.title;
return text.toLowerCase().includes(query); /* ΔTRUTH: Scoped search for efficiency. */ return text.toLowerCase().includes(query);
}); });
} }
posts.sort((a, b) => sort === "newest" ? b.mtime - a.mtime : a.mtime - b.mtime); /* ΔRHYTHM: Time-based order. */ posts.sort((a, b) => sort === "newest" ? b.mtime - a.mtime : a.mtime - b.mtime);
els.postList.innerHTML = posts.length ? "" : "<li>No posts found.</li>"; els.postList.innerHTML = posts.length ? "" : "<li>No posts found.</li>";
if (!posts.length) {
showDiagnostic('No posts found in current filters. If persistent, check index.json for flat entries or add content files and regenerate.');
}
posts.forEach(p => { posts.forEach(p => {
const li = document.createElement("li"); const li = document.createElement("li");
const pin = p.isPinned ? "Star " : ""; const pin = p.isPinned ? "Star " : "";
const time = new Date(p.ctime).toLocaleDateString(); /* ΔRHYTHM: Human-readable date. */ const time = new Date(p.ctime).toLocaleDateString();
li.innerHTML = `<a href="#/${p.path}">${pin}${p.title}</a><small>${time}</small>`; li.innerHTML = `<a href="#/${p.path}">${pin}${p.title}</a><small>${time}</small>`;
els.postList.appendChild(li); els.postList.appendChild(li);
}); });
} }
/* ΔRECURSION: Load pinned or latest for section fallback.
* Rationale: Prevents empty states; redirects via hash for routing consistency. */
function loadDefaultForSection(section) { function loadDefaultForSection(section) {
const posts = indexData.flat.filter(p => p.path.split('/')[0] === section && !p.isIndex); const posts = indexData.flat.filter(p => p.path.split('/')[0] === section && !p.isIndex);
if (!posts.length) { if (!posts.length) {
@ -167,14 +165,12 @@ function loadDefaultForSection(section) {
} }
// === SUBNAV (NESTED HORIZON) === // === SUBNAV (NESTED HORIZON) ===
/* ΔRECURSION: Render subnav based on parent hierarchy.
* Rationale: Clear on change; RAF for smooth visible class addition. */
function renderSubNav(parent) { function renderSubNav(parent) {
const subnav = els.subNav; const subnav = els.subNav;
subnav.innerHTML = ""; subnav.innerHTML = "";
subnav.classList.remove("visible"); subnav.classList.remove("visible");
if (!parent || !indexData.hierarchies?.[parent]) return; /* ΔTRUTH: Early exit if no subs. */ if (!parent || !indexData.hierarchies?.[parent]) return;
const subs = indexData.hierarchies[parent]; const subs = indexData.hierarchies[parent];
subs.forEach(child => { subs.forEach(child => {
@ -184,30 +180,28 @@ function renderSubNav(parent) {
subnav.appendChild(link); subnav.appendChild(link);
}); });
requestAnimationFrame(() => subnav.classList.add("visible")); /* ΔBREATH: Deferred for animation prep. */ requestAnimationFrame(() => subnav.classList.add("visible"));
} }
// === HASH ROUTING === // === HASH ROUTING ===
/* ΔRECURSION: Core router; parses hash, renders accordingly.
* Rationale: Resilient to edge cases; recursive via parent tracking; fallbacks to defaults. */
async function handleHash() { async function handleHash() {
els.viewer.innerHTML = ""; /* ΔFIELD: Clear canvas for fresh render. */ els.viewer.innerHTML = "";
const rel = location.hash.replace(/^#\//, ""); const rel = location.hash.replace(/^#\//, "");
const parts = rel.split("/").filter(Boolean); const parts = rel.split("/").filter(Boolean);
const currentParentPath = parts.slice(0, -1).join("/") || parts[0] || null; const currentParentPath = parts.slice(0, -1).join("/") || parts[0] || null;
if (currentParentPath !== currentParent) { if (currentParentPath !== currentParent) {
currentParent = currentParentPath; currentParent = currentParentPath;
renderSubNav(currentParent); /* ΔRECURSION: Update subnav on parent change. */ renderSubNav(currentParent);
} }
const topSection = parts[0] || null; const topSection = parts[0] || null;
if (topSection && indexData.sections.includes(topSection)) { if (topSection && indexData.sections.includes(topSection)) {
els.sectionSelect.value = topSection; els.sectionSelect.value = topSection;
renderList(); /* ΔFIELD: Sync list with section. */ renderList();
} }
if (rel === '' || rel === '#') return renderDefault(); /* ΔRECURSION: Resilient home handling. */ if (rel === '' || rel === '#') return renderDefault();
if (!rel) return renderDefault(); if (!rel) return renderDefault();
@ -215,7 +209,7 @@ async function handleHash() {
const currentPath = parts.join("/"); const currentPath = parts.join("/");
const indexFile = indexFiles.find(f => { const indexFile = indexFiles.find(f => {
const dir = f.path.split("/").slice(0, -1).join("/"); const dir = f.path.split("/").slice(0, -1).join("/");
return dir === currentPath; /* ΔTRUTH: Match directory to index file. */ return dir === currentPath;
}); });
if (indexFile) { if (indexFile) {
@ -226,28 +220,24 @@ async function handleHash() {
} }
} else { } else {
if (topSection) loadDefaultForSection(topSection); if (topSection) loadDefaultForSection(topSection);
else els.viewer.innerHTML = `<h1>${currentPath.split("/").pop()}</h1><p>No content yet.</p>`; /* ΔFIELD: Placeholder for empty dirs. */ else els.viewer.innerHTML = `<h1>${currentPath.split("/").pop()}</h1><p>No content yet.</p>`;
} }
} else { } else {
const file = indexData.flat.find(f => f.path === rel); const file = indexData.flat.find(f => f.path === rel);
if (!file) { if (!file) {
els.viewer.innerHTML = "<h1>404</h1><p>Not found.</p>"; /* ΔTRUTH: Honest error. */ els.viewer.innerHTML = "<h1>404</h1><p>Not found.</p>";
return; return;
} }
file.ext === ".md" ? await renderMarkdown(file.path) : await renderIframe("/" + file.path); /* ΔFIELD: Type-based rendering. */ file.ext === ".md" ? await renderMarkdown(file.path) : await renderIframe("/" + file.path);
} }
} }
/* ΔTRUTH: Fetch and parse Markdown; fallback to 'Untitled'.
* Rationale: Uses marked.js (assumed global); wraps in article for styling. */
async function renderMarkdown(rel) { async function renderMarkdown(rel) {
const src = await fetch(rel).then(r => r.ok ? r.text() : ""); const src = await fetch(rel).then(r => r.ok ? r.text() : "");
els.viewer.innerHTML = `<article class="markdown">${marked.parse(src || "# Untitled")}</article>`; els.viewer.innerHTML = `<article class="markdown">${marked.parse(src || "# Untitled")}</article>`;
} }
// === PREVIEW + PORTAL ENGINE === // === PREVIEW + PORTAL ENGINE ===
/* ΔFIELD: Render sanitized preview with portal button.
* Rationale: Button opens full in new tab for immersion preservation. */
async function renderIframe(rel) { async function renderIframe(rel) {
const preview = await generatePreview(rel); const preview = await generatePreview(rel);
const portalBtn = `<button class="portal-btn" data-src="${rel}">Open Full Experience</button>`; const portalBtn = `<button class="portal-btn" data-src="${rel}">Open Full Experience</button>`;
@ -258,20 +248,16 @@ async function renderIframe(rel) {
`; `;
els.viewer.querySelector(".portal-btn").addEventListener("click", e => { els.viewer.querySelector(".portal-btn").addEventListener("click", e => {
window.open(e.target.dataset.src, "_blank", "noopener,noreferrer"); /* ΔTRUTH: Secure external open. */ window.open(e.target.dataset.src, "_blank", "noopener,noreferrer");
}); });
} }
/* ΔTRUTH: Generate safe, trimmed preview from HTML.
* Rationale: Extract body; sanitize; trim recursively; fallback link on error. */
async function generatePreview(rel) { async function generatePreview(rel) {
try { try {
const res = await fetch(rel); const res = await fetch(rel);
if (!res.ok) throw new Error(); if (!res.ok) throw new Error();
const html = await res.text(); const html = await res.text();
/* ΔTRUTH: Modular sanitizer strips scripts, styles, events, inline CSS; normalizes whitespace.
* Rationale: Prevents injection/XSS; removes phantoms for clean rhythm. */
function sanitizeHTML(html) { function sanitizeHTML(html) {
return html return html
.replace(/<script[\s\S]*?<\/script>/gi, "") .replace(/<script[\s\S]*?<\/script>/gi, "")
@ -289,24 +275,22 @@ async function generatePreview(rel) {
const div = document.createElement("div"); const div = document.createElement("div");
div.innerHTML = content; div.innerHTML = content;
trimPreview(div, 3, 3000); // depth, char limit /* ΔFIELD: Bounds for performance. */ trimPreview(div, 3, 3000); // depth, char limit
return div.innerHTML || `<p>Empty content.</p>`; return div.innerHTML || `<p>Empty content.</p>`;
} catch { } catch {
return `<p>Preview unavailable. <a href="${rel}" target="_blank" rel="noopener">Open directly</a>.</p>`; /* ΔTRUTH: Fallback preserves access. */ return `<p>Preview unavailable. <a href="${rel}" target="_blank" rel="noopener">Open directly</a>.</p>`;
} }
} }
/* ΔRECURSION: Trim DOM tree to depth/char limits.
* Rationale: Cumulative total ensures balanced siblings; removes excess for preview focus. */
function trimPreview(el, maxDepth, charLimit, depth = 0, chars = 0) { function trimPreview(el, maxDepth, charLimit, depth = 0, chars = 0) {
if (depth > maxDepth || chars > charLimit) { if (depth > maxDepth || chars > charLimit) {
el.innerHTML = "..."; /* ΔBREATH: Ellipsis as truncation breath. */ el.innerHTML = "...";
return; return;
} }
let total = chars; let total = chars;
for (const child of [...el.children]) { for (const child of [...el.children]) {
total += child.textContent.length; /* ΔRECURSION: Pre-calculate to avoid bias. */ total += child.textContent.length;
if (total > charLimit || depth > maxDepth) { if (total > charLimit || depth > maxDepth) {
child.remove(); child.remove();
} else { } else {
@ -316,8 +300,6 @@ function trimPreview(el, maxDepth, charLimit, depth = 0, chars = 0) {
} }
// === DEFAULT VIEW === // === DEFAULT VIEW ===
/* ΔFIELD: Render home with default section fallback.
* Rationale: Prioritizes 'posts'; welcoming placeholder if empty. */
function renderDefault() { function renderDefault() {
const defaultSection = indexData.sections.includes("posts") ? "posts" : indexData.sections[0]; const defaultSection = indexData.sections.includes("posts") ? "posts" : indexData.sections[0];
if (defaultSection) { if (defaultSection) {
@ -325,9 +307,10 @@ function renderDefault() {
renderList(); renderList();
loadDefaultForSection(defaultSection); loadDefaultForSection(defaultSection);
} else { } else {
els.viewer.innerHTML = "<h1>Welcome</h1><p>Add content to begin.</p>"; showDiagnostic('No sections detected in index.json. Create folders with .md/.html files in public/ and run node tools/generate-index.mjs to regenerate.');
els.viewer.innerHTML = "<h1>Welcome</h1><p>Add content to begin. See diagnostic banner for details.</p>";
} }
} }
// === START === // === START ===
init(); /* ΔFIELD: Invoke the blueprint's origin. */ init();