Update main.js
This commit is contained in:
parent
ea6f05e78f
commit
8e3cf7a1c3
1 changed files with 28 additions and 27 deletions
55
main.js
55
main.js
|
|
@ -1,43 +1,44 @@
|
|||
// main.js
|
||||
// Client-side markdown renderer for "The Fold Within"
|
||||
// main.js — dynamic markdown loader for The Fold Within
|
||||
|
||||
document.addEventListener('DOMContentLoaded', async () => {
|
||||
const content = document.querySelector('main');
|
||||
const postsDir = 'posts/';
|
||||
|
||||
// Load Markdown renderer
|
||||
const rendererScript = document.createElement('script');
|
||||
rendererScript.src = 'https://cdn.jsdelivr.net/npm/marked/marked.min.js';
|
||||
document.head.appendChild(rendererScript);
|
||||
document.addEventListener("DOMContentLoaded", async () => {
|
||||
const postsContainer = document.getElementById("posts");
|
||||
const main = document.querySelector("main");
|
||||
|
||||
rendererScript.onload = () => {
|
||||
// Attach click handlers to all articles
|
||||
document.querySelectorAll('article').forEach(article => {
|
||||
article.addEventListener('click', async () => {
|
||||
const slug = article.querySelector('h3').textContent.trim()
|
||||
.toLowerCase().replace(/\s+/g, '-');
|
||||
loadPost(slug);
|
||||
});
|
||||
});
|
||||
};
|
||||
// Load post metadata from posts.json
|
||||
const response = await fetch("posts/posts.json");
|
||||
const posts = await response.json();
|
||||
|
||||
async function loadPost(slug) {
|
||||
// Render index of posts
|
||||
posts.forEach(post => {
|
||||
const article = document.createElement("article");
|
||||
article.innerHTML = `
|
||||
<div class="thumb"></div>
|
||||
<h3>${post.title}</h3>
|
||||
<p class="date">${post.date}</p>
|
||||
<p>${post.excerpt}</p>
|
||||
`;
|
||||
article.addEventListener("click", () => loadPost(post.file));
|
||||
postsContainer.appendChild(article);
|
||||
});
|
||||
|
||||
// Load a markdown post dynamically
|
||||
async function loadPost(filename) {
|
||||
try {
|
||||
const res = await fetch(`${postsDir}${slug}.md`);
|
||||
if (!res.ok) throw new Error('Post not found.');
|
||||
const res = await fetch(`posts/${filename}`);
|
||||
if (!res.ok) throw new Error("Post not found.");
|
||||
const md = await res.text();
|
||||
const html = marked.parse(md);
|
||||
|
||||
content.innerHTML = `
|
||||
main.innerHTML = `
|
||||
<section class="post">
|
||||
<a href="#" id="back">← Back</a>
|
||||
<a href="#" id="back">← Back to Archive</a>
|
||||
<div class="markdown">${html}</div>
|
||||
</section>
|
||||
`;
|
||||
|
||||
document.getElementById('back').addEventListener('click', () => location.reload());
|
||||
document.getElementById("back").addEventListener("click", () => location.reload());
|
||||
} catch (err) {
|
||||
content.innerHTML = `<p class="error">⚠️ ${err.message}</p>`;
|
||||
main.innerHTML = `<p class="error">⚠️ ${err.message}</p>`;
|
||||
}
|
||||
}
|
||||
});
|
||||
Loading…
Add table
Add a link
Reference in a new issue