Add menu system built using MD

This commit is contained in:
Raven Scott 2024-09-26 18:13:47 -04:00
parent 56cb62bad7
commit 2d89dcddf6
7 changed files with 77 additions and 159 deletions

2
.gitignore vendored
View File

@ -1,4 +1,4 @@
node_modules
package-lock.json
.env
menu.md

119
app.js
View File

@ -28,6 +28,31 @@ app.use(express.urlencoded({ extended: false }));
// Serve static files (CSS, Images)
app.use(express.static(path.join(__dirname, 'public')));
// Function to load menu items from the markdown file
function loadMenuItems() {
const menuFile = path.join(__dirname, 'menu.md');
const content = fs.readFileSync(menuFile, 'utf-8');
const menuItems = [];
const titleRegex = /<!--\s*title:\s*(.*?)\s*-->/g;
const urlRegex = /<!--\s*url:\s*(.*?)\s*-->/g;
let titleMatch;
let urlMatch;
while ((titleMatch = titleRegex.exec(content)) && (urlMatch = urlRegex.exec(content))) {
menuItems.push({
title: titleMatch[1],
url: urlMatch[1]
});
}
return menuItems;
}
// Load the menu once and make it available to all routes
const menuItems = loadMenuItems();
// Function to load and parse markdown files and extract lead
function loadMarkdownWithLead(file) {
const markdownContent = fs.readFileSync(path.join(__dirname, 'markdown', file), 'utf-8');
@ -54,11 +79,6 @@ function titleToSlug(title) {
.replace(/\s+/g, '-');
}
// Function to convert a slug back into a readable title
function slugToTitle(slug) {
return slug.replace(/-/g, ' ');
}
// Function to load all blog posts with pagination and search support
function getAllBlogPosts(page = 1, postsPerPage = 5, searchQuery = '') {
let blogFiles = fs.readdirSync(path.join(__dirname, 'markdown')).filter(file => file.endsWith('.md'));
@ -117,11 +137,11 @@ app.get('/', (req, res) => {
currentPage: page,
totalPages,
searchQuery, // Pass search query to the view
noResults // Pass this flag to indicate no results found
noResults, // Pass this flag to indicate no results found
menuItems // Pass the menu items to the view
});
});
// About Route (Load markdown and render using EJS)
app.get('/about', (req, res) => {
const aboutMarkdownFile = path.join(__dirname, 'me', 'about.md');
@ -136,72 +156,19 @@ app.get('/about', (req, res) => {
res.render('about', {
title: `About ${process.env.OWNER_NAME}`,
content: aboutContentHtml
content: aboutContentHtml,
menuItems // Pass the menu items to the view
});
});
});
// Display the Request a Quote form
// Contact Route (Render the contact form)
app.get('/contact', (req, res) => {
res.render('contact', { title: `Contact ${process.env.OWNER_NAME}`, msg: undefined });
});
// Handle contact form submission
app.post('/contact', async (req, res) => {
const { name, email, subject, message, 'g-recaptcha-response': captchaToken } = req.body;
if (!name || !email || !subject || !message) {
return res.render('contact', { title: `Contact ${process.env.OWNER_NAME}`, msg: 'All fields are required.' });
}
const captchaSecret = process.env.CAPTCHA_SECRET_KEY;
const captchaVerifyUrl = `https://www.google.com/recaptcha/api/siteverify?secret=${captchaSecret}&response=${captchaToken}`;
try {
const captchaResponse = await axios.post(captchaVerifyUrl);
if (!captchaResponse.data.success) {
return res.render('contact', { title: `Contact ${process.env.OWNER_NAME}`, msg: 'Captcha verification failed. Please try again.' });
}
const output = `
<p>You have a new contact request from <strong>${name}</strong>.</p>
<h3>Contact Details</h3>
<ul>
<li><strong>Name:</strong> ${name}</li>
<li><strong>Email:</strong> ${email}</li>
<li><strong>Subject:</strong> ${subject}</li>
</ul>
<h3>Message</h3>
<p>${message}</p>
`;
let transporter = nodemailer.createTransport({
host: process.env.SMTP_HOST,
port: process.env.SMTP_PORT,
secure: false,
auth: {
user: process.env.EMAIL_USER,
pass: process.env.EMAIL_PASS,
},
tls: { rejectUnauthorized: false },
});
let mailOptions = {
from: `"${name}" <${process.env.RECEIVER_EMAIL}>`,
to: process.env.RECEIVER_EMAIL,
subject: subject,
html: output,
};
transporter.sendMail(mailOptions, (error, info) => {
if (error) {
return res.render('contact', { title: `Contact ${process.env.OWNER_NAME}`, msg: 'An error occurred. Please try again.' });
}
return res.render('contact', { title: `Contact ${process.env.OWNER_NAME}`, msg: 'Your message has been sent successfully!' });
});
} catch (error) {
return res.render('contact', { title: `Contact ${process.env.OWNER_NAME}`, msg: 'An error occurred while verifying CAPTCHA. Please try again.' });
}
res.render('contact', {
title: `Contact ${process.env.OWNER_NAME}`,
msg: undefined,
menuItems // Pass the menu items to the view
});
});
// Blog Post Route
@ -223,14 +190,14 @@ app.get('/blog/:slug', (req, res) => {
content: contentHtml,
lead,
description, // Pass the description to the view
blogPosts
blogPosts,
menuItems // Pass the menu items to the view
});
} else {
res.redirect('/');
}
});
// Sitemap Route
app.get('/sitemap.xml', (req, res) => {
const hostname = req.headers.host || 'http://localhost';
@ -318,19 +285,9 @@ app.get('/rss', (req, res) => {
res.send(rssFeed);
});
// Create a URL object from the environment variable
const blog_URL = new URL(process.env.BLOG_URL);
// Extract just the hostname (e.g., blog.raven-scott.fyi)
const hostname = blog_URL.hostname;
// Global 404 handler for unmatched routes
app.use((req, res) => {
if (req.hostname === hostname) {
res.redirect(process.env.HOST_URL);
} else {
res.redirect('/');
}
res.redirect('/');
});
// Server Listening

8
default.menu.md Normal file
View File

@ -0,0 +1,8 @@
<!-- title: Home -->
<!-- url: / -->
<!-- title: About Me -->
<!-- url: /about -->
<!-- title: Contact -->
<!-- url: /contact -->

View File

@ -23,7 +23,7 @@
<body>
<!-- Navigation Bar -->
<!-- Navbar -->
<nav class="navbar navbar-expand-lg navbar-dark">
<div class="container-fluid">
<a class="navbar-brand" href="<%= process.env.HOST_URL %>"><%= process.env.SITE_NAME %></a>
@ -32,15 +32,11 @@
</button>
<div class="collapse navbar-collapse" id="navbarNav">
<ul class="navbar-nav ms-auto">
<li class="nav-item">
<a class="nav-link active" href="<%= process.env.HOST_URL %>">Home</a>
</li>
<li class="nav-item">
<a class="nav-link" href="<%= process.env.HOST_URL %>/about">About Me</a>
</li>
<li class="nav-item">
<a class="nav-link" href="<%= process.env.HOST_URL %>/contact">Contact</a>
</li>
<% menuItems.forEach(item => { %>
<li class="nav-item">
<a class="nav-link" href="<%= item.url %>"><%= item.title %></a>
</li>
<% }) %>
</ul>
</div>
</div>

View File

@ -30,15 +30,11 @@
</button>
<div class="collapse navbar-collapse" id="navbarNav">
<ul class="navbar-nav ms-auto">
<li class="nav-item">
<a class="nav-link active" href="<%= process.env.HOST_URL %>">Home</a>
</li>
<li class="nav-item">
<a class="nav-link" href="<%= process.env.HOST_URL %>/about">About Me</a>
</li>
<li class="nav-item">
<a class="nav-link" href="<%= process.env.HOST_URL %>/contact">Contact</a>
</li>
<% menuItems.forEach(item => { %>
<li class="nav-item">
<a class="nav-link" href="<%= item.url %>"><%= item.title %></a>
</li>
<% }) %>
</ul>
</div>
</div>

View File

@ -26,7 +26,7 @@
<body class="bg-dark text-white">
<!-- Navigation Bar -->
<!-- Navbar -->
<nav class="navbar navbar-expand-lg navbar-dark">
<div class="container-fluid">
<a class="navbar-brand" href="<%= process.env.HOST_URL %>"><%= process.env.SITE_NAME %></a>
@ -35,15 +35,11 @@
</button>
<div class="collapse navbar-collapse" id="navbarNav">
<ul class="navbar-nav ms-auto">
<li class="nav-item">
<a class="nav-link active" href="<%= process.env.HOST_URL %>">Home</a>
</li>
<li class="nav-item">
<a class="nav-link" href="<%= process.env.HOST_URL %>/about">About Me</a>
</li>
<li class="nav-item">
<a class="nav-link" href="<%= process.env.HOST_URL %>/contact">Contact</a>
</li>
<% menuItems.forEach(item => { %>
<li class="nav-item">
<a class="nav-link" href="<%= item.url %>"><%= item.title %></a>
</li>
<% }) %>
</ul>
</div>
</div>

View File

@ -7,12 +7,6 @@
<title><%= title %></title>
<link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/bootstrap@5.3.0-alpha1/dist/css/bootstrap.min.css">
<link rel="stylesheet" href="<%= process.env.HOST_URL %>/css/styles.css">
<link rel="apple-touch-icon" sizes="180x180" href="<%= process.env.HOST_URL %>/apple-touch-icon.png">
<link rel="icon" type="image/png" sizes="32x32" href="<%= process.env.HOST_URL %>/favicon-32x32.png">
<link rel="icon" type="image/png" sizes="16x16" href="<%= process.env.HOST_URL %>/favicon-16x16.png">
<link rel="manifest" href="<%= process.env.HOST_URL %>/site.webmanifest">
<meta name="msapplication-TileColor" content="#da532c">
<meta name="theme-color" content="#ffffff">
</head>
<body>
<!-- Navbar -->
@ -24,20 +18,17 @@
</button>
<div class="collapse navbar-collapse" id="navbarNav">
<ul class="navbar-nav ms-auto">
<li class="nav-item">
<a class="nav-link active" href="<%= process.env.HOST_URL %>">Home</a>
</li>
<li class="nav-item">
<a class="nav-link" href="<%= process.env.HOST_URL %>/about">About Me</a>
</li>
<li class="nav-item">
<a class="nav-link" href="<%= process.env.HOST_URL %>/contact">Contact</a>
</li>
<% menuItems.forEach(item => { %>
<li class="nav-item">
<a class="nav-link" href="<%= item.url %>"><%= item.title %></a>
</li>
<% }) %>
</ul>
</div>
</div>
</nav>
<!-- Main Content -->
<header class="py-5">
<div class="container text-center">
<h1><%= process.env.FRONT_PAGE_TITLE %></h1>
@ -50,21 +41,20 @@
</div>
</header>
<!-- Search form -->
<!-- Blog Content -->
<section class="py-5">
<div class="container">
<!-- Blog post list -->
<% if (noResults) { %>
<p><CENTER>Sorry, no blog posts found matching "<%= searchQuery %>"</CENTER></p>
<p><center>Sorry, no blog posts found matching "<%= searchQuery %>"</center></p>
<% } else { %>
<h2><%= searchQuery ? 'Search results for "' + searchQuery + '"' : 'Recent Posts' %></h2>
<h2><%= searchQuery ? 'Search results for "' + searchQuery + '"' : 'Recent Posts' %></h2>
<% } %>
<ul class="list-group list-group-flush">
<% blogPosts.forEach(post => { %>
<li class="list-group-item d-flex justify-content-between align-items-center py-4">
<div>
<h5 class="mb-1"><a href="<%= process.env.BLOG_URL %><%= post.slug %>"> <%= post.title %> </a></h5>
<h5 class="mb-1"><a href="<%= process.env.BLOG_URL %><%= post.slug %>"><%= post.title %></a></h5>
<p class="mb-1 text-muted">Posted on
<%= new Date(post.dateCreated).toLocaleDateString('en-US', {
year: 'numeric',
@ -86,13 +76,13 @@
<a class="page-link" href="?page=<%= currentPage - 1 %>">Previous</a>
</li>
<% } %>
<% for (let i = 1; i <= totalPages; i++) { %>
<li class="page-item <%= currentPage === i ? 'active' : '' %>">
<a class="page-link" href="?page=<%= i %>"><%= i %></a>
</li>
<% } %>
<% if (currentPage < totalPages) { %>
<li class="page-item">
<a class="page-link" href="?page=<%= currentPage + 1 %>">Next</a>
@ -105,35 +95,10 @@
<footer class="text-white text-center py-4">
<div class="container">
<h4 class="footer-logo mb-3"><%= process.env.FOOTER_TAGLINE %></h4>
<p class="footer-links mb-3">
<a href="/" class="text-white text-decoration-none me-3">Home</a>
<a href="/about" class="text-white text-decoration-none me-3">About</a>
<a href="/contact" class="text-white text-decoration-none me-3">Contact</a>
<a href="<%= process.env.HOST_URL %>/sitemap.xml" class="text-white text-decoration-none me-3">Sitemap</a>
<a href="<%= process.env.HOST_URL %>/rss" class="text-white text-decoration-none">RSS Feed</a>
</p>
<p class="mb-0">&copy; 2024 <%= process.env.OWNER_NAME %>. All rights reserved.</p>
</div>
</footer>
<script src="https://cdn.jsdelivr.net/npm/bootstrap@5.3.0-alpha1/dist/js/bootstrap.bundle.min.js"></script>
<script>
let typingTimer; // Timer identifier
const doneTypingInterval = 500; // Time in ms, adjust for desired delay
const searchInput = document.getElementById('search-input');
searchInput.addEventListener('input', function() {
clearTimeout(typingTimer);
typingTimer = setTimeout(function() {
searchInput.form.submit();
}, doneTypingInterval);
});
searchInput.addEventListener('keydown', function() {
clearTimeout(typingTimer);
});
</script>
</body>
</html>