diff --git a/app/a/[slug]/page.tsx b/app/a/[slug]/page.tsx index 3be2a66..069bd2e 100644 --- a/app/a/[slug]/page.tsx +++ b/app/a/[slug]/page.tsx @@ -1,15 +1,16 @@ -import { BlogPost, getPostBySlug, getAllPosts } from "@/lib/blog" +import { getPostBySlugServer } from "@/lib/blog-server" import BlogPostPage from "./BlogPostClient" import { notFound } from "next/navigation" +import articlesIndex from '../../../public/articles/articles-index.json' export async function generateStaticParams() { - const posts = getAllPosts() - return posts.map((post) => ({ slug: post.slug })) + // Use articles-index.json directly for static generation + return articlesIndex.articles.map((article) => ({ slug: article.slug })) } export default async function Page(props: { params: { slug: string } }) { - const { slug } = props.params - const post = getPostBySlug(slug) + const { slug } = await props.params + const post = getPostBySlugServer(slug) if (!post) { notFound() diff --git a/components/pagination.tsx b/components/pagination.tsx index 59fa085..d3da3ec 100644 --- a/components/pagination.tsx +++ b/components/pagination.tsx @@ -1,13 +1,14 @@ "use client" import { ChevronLeft, ChevronRight } from "lucide-react" +import Link from "next/link" interface PaginationProps { currentPage: number totalPages: number hasNextPage: boolean hasPrevPage: boolean - onPageChange: (page: number) => void + onPageChange?: (page: number) => void } export default function Pagination({ @@ -38,69 +39,120 @@ export default function Pagination({ return pages } - const handlePageClick = (page: number) => { - // Always call onPageChange, even if it's the same page (for consistency) - onPageChange(page) - } + // If onPageChange is provided, use it for client-side navigation + if (onPageChange) { + return ( +
+ {/* Previous Button */} + - const handlePrevious = () => { - if (hasPrevPage && currentPage > 1) { - onPageChange(currentPage - 1) - } - } + {/* Page Numbers */} +
+ {getPageNumbers().map((pageNum) => ( + + ))} +
- const handleNext = () => { - if (hasNextPage && currentPage < totalPages) { - onPageChange(currentPage + 1) - } + {/* Next Button */} + +
+ ) } + // Otherwise, use Link for server-side navigation return (
{/* Previous Button */} - + {hasPrevPage && currentPage > 1 ? ( + + + Previous + + ) : ( + + )} {/* Page Numbers */}
{getPageNumbers().map((pageNum) => ( - + pageNum === currentPage ? ( + + {pageNum} + + ) : ( + + {pageNum} + + ) ))}
{/* Next Button */} - + {hasNextPage && currentPage < totalPages ? ( + + Next + + + ) : ( + + )}
) } diff --git a/lib/blog-data.json b/lib/blog-data.json deleted file mode 100644 index 7157dfc..0000000 --- a/lib/blog-data.json +++ /dev/null @@ -1,184 +0,0 @@ -{ - "posts": [ - { - "slug": "sustainable-living-tips", - "title": "10 Simple Tips for Sustainable Living", - "author": "Emma Green", - "date": "2024-01-15", - "image": "/images/sustainable-living.jpg", - "excerpt": "Discover practical ways to reduce your environmental footprint and live more sustainably without breaking the bank.", - "featured": true, - "content": "# 10 Simple Tips for Sustainable Living\n\nLiving sustainably doesn't have to be overwhelming or expensive. Here are ten practical tips that anyone can implement to reduce their environmental impact.\n\n![Sustainable living concept](/images/eco-home.jpg)\n\n## 1. Reduce Single-Use Plastics\n\nStart by replacing single-use items with reusable alternatives:\n- Use a reusable water bottle\n- Bring your own shopping bags\n- Choose glass or metal containers for food storage\n\n## 2. Embrace Minimalism\n\nBuy less, choose better. Focus on quality over quantity when making purchases.\n\n> \"The best thing you can do for the environment is to buy less stuff.\" - Environmental Expert\n\n## 3. Energy Efficiency at Home\n\nSimple changes can make a big difference:\n- Switch to LED light bulbs\n- Unplug electronics when not in use\n- Use a programmable thermostat\n\n## 4. Sustainable Transportation\n\nConsider walking, biking, or using public transportation when possible. If you need a car, consider carpooling or electric vehicles.\n\n## 5. Grow Your Own Food\n\nEven a small herb garden on your windowsill can reduce packaging waste and provide fresh ingredients.\n\n![Home garden](/images/home-garden.jpg)\n\n## 6. Reduce Food Waste\n\nPlan your meals, store food properly, and compost organic waste.\n\n## 7. Choose Sustainable Products\n\nLook for products with minimal packaging and those made from recycled or sustainable materials.\n\n## 8. Water Conservation\n\nFix leaks promptly, take shorter showers, and collect rainwater for plants.\n\n## 9. Support Local Businesses\n\nBuying local reduces transportation emissions and supports your community.\n\n## 10. Educate and Inspire Others\n\nShare your sustainable living journey with friends and family to multiply your impact.\n\nRemember, every small action counts. Start with one or two tips and gradually incorporate more sustainable practices into your daily routine." - }, - { - "slug": "future-of-renewable-energy", - "title": "The Future of Renewable Energy: What to Expect in 2024", - "author": "Dr. Sarah Johnson", - "date": "2024-01-10", - "image": "/images/solar-panels.jpg", - "excerpt": "Explore the latest developments in renewable energy technology and what they mean for our sustainable future.", - "featured": false, - "content": "# The Future of Renewable Energy: What to Expect in 2024\n\nThe renewable energy sector is experiencing unprecedented growth, with technological advances making clean energy more accessible and affordable than ever before.\n\n![Solar panel installation](/images/solar-installation.jpg)\n\n## Solar Power Revolution\n\nSolar technology continues to improve with higher efficiency panels and better energy storage solutions. The cost of solar installations has dropped by over 70% in the past decade.\n\n### Key Developments:\n- Perovskite solar cells showing promise for higher efficiency\n- Floating solar farms expanding to new markets\n- Integration with smart grid technology\n\n## Wind Energy Expansion\n\nWind power is becoming increasingly competitive, with offshore wind farms leading the charge in many coastal regions.\n\n> \"Wind energy could provide up to 20% of global electricity by 2030.\" - International Energy Agency\n\n## Energy Storage Breakthroughs\n\nBattery technology improvements are solving the intermittency challenge of renewable energy sources.\n\n![Battery storage facility](/images/battery-storage.jpg)\n\n## Government Policies and Incentives\n\nMany countries are implementing ambitious renewable energy targets and providing incentives for clean energy adoption.\n\n## Challenges Ahead\n\nDespite the progress, challenges remain:\n- Grid infrastructure upgrades needed\n- Raw material supply chains for batteries\n- Balancing energy supply and demand\n\n## The Path Forward\n\nThe transition to renewable energy is not just an environmental imperative but also an economic opportunity. As technology continues to advance and costs decrease, we can expect renewable energy to become the dominant source of power globally.\n\nThe future is bright for renewable energy, and 2024 promises to be a pivotal year in this transformation." - }, - { - "slug": "mindful-technology-use", - "title": "Mindful Technology Use in the Digital Age", - "author": "Alex Chen", - "date": "2024-01-05", - "image": "/images/digital-wellness.jpg", - "excerpt": "Learn how to maintain a healthy relationship with technology while staying connected in our digital world.", - "featured": true, - "content": "# Mindful Technology Use in the Digital Age\n\n[Test Link](https://www.google.com).\n\nIn our hyperconnected world, finding balance with technology has become more important than ever. Here's how to use technology mindfully while maintaining your well-being.\n\n![Person meditating with phone nearby](/images/digital-meditation.jpg)\n\n## Understanding Digital Overwhelm\n\nThe constant stream of notifications, emails, and social media updates can lead to:\n- Increased stress and anxiety\n- Difficulty concentrating\n- Sleep disruption\n- Reduced face-to-face social interactions\n\n## Strategies for Mindful Tech Use\n\n### 1. Create Tech-Free Zones\n\nDesignate certain areas of your home as technology-free spaces:\n- Bedroom for better sleep\n- Dining room for mindful eating\n- A reading nook for focused activities\n\n### 2. Practice Digital Minimalism\n\n> \"Digital minimalism is a philosophy of technology use in which you focus your online time on a small number of carefully selected and optimized activities.\" - Cal Newport\n\n### 3. Use Technology Intentionally\n\nBefore picking up your device, ask yourself:\n- What is my specific purpose?\n- How long do I plan to use this?\n- Is this the best tool for this task?\n\n![Smartphone with mindfulness app](/images/mindfulness-app.jpg)\n\n## Setting Healthy Boundaries\n\n### Notification Management\n- Turn off non-essential notifications\n- Use \"Do Not Disturb\" modes\n- Schedule specific times for checking messages\n\n### Social Media Mindfulness\n- Curate your feeds to include positive content\n- Set time limits for social media use\n- Practice the \"pause before you post\" rule\n\n## The Benefits of Mindful Technology Use\n\nWhen we use technology more intentionally, we experience:\n- Improved focus and productivity\n- Better sleep quality\n- Stronger real-world relationships\n- Reduced anxiety and stress\n- More time for meaningful activities\n\n## Tools for Digital Wellness\n\nSeveral apps and features can help you maintain a healthy relationship with technology:\n- Screen time tracking apps\n- Website blockers during focused work\n- Meditation and mindfulness apps\n- Blue light filters for evening use\n\n## Finding Your Balance\n\nRemember, the goal isn't to eliminate technology but to use it in ways that enhance rather than detract from your life. Start small, be patient with yourself, and gradually build habits that support your well-being.\n\nTechnology should serve you, not the other way around. By practicing mindful technology use, you can harness the benefits of our digital tools while maintaining your mental health and personal connections." - }, - { - "slug": "climate-change-solutions", - "title": "Climate Change Solutions for the Modern World", - "author": "Dr. Michael Torres", - "date": "2024-01-20", - "image": "/images/solar-panels.jpg", - "excerpt": "Exploring innovative approaches to combat climate change through technology and policy.", - "featured": true, - "content": "# Climate Change Solutions for the Modern World\n\nClimate change represents one of the most pressing challenges of our time. However, innovative solutions are emerging that offer hope for a sustainable future.\n\n## Technological Innovations\n\nFrom carbon capture technology to advanced renewable energy systems, science is providing us with powerful tools to address climate change.\n\n## Policy and Governance\n\nEffective climate action requires coordinated policy responses at local, national, and international levels.\n\nThe path forward requires collaboration between governments, businesses, and individuals to create meaningful change." - }, - { - "slug": "urban-gardening-guide", - "title": "Urban Gardening: Growing Food in Small Spaces", - "author": "Lisa Martinez", - "date": "2024-01-18", - "image": "/images/home-garden.jpg", - "excerpt": "Learn how to create a thriving garden in urban environments with limited space.", - "featured": false, - "content": "# Urban Gardening: Growing Food in Small Spaces\n\nUrban gardening is revolutionizing how city dwellers connect with their food sources and contribute to sustainability.\n\n![Urban garden setup](/images/home-garden.jpg)\n\n## Getting Started\n\nEven the smallest balcony or windowsill can become a productive growing space with the right approach.\n\n## Best Plants for Urban Gardens\n\n- Herbs like basil, mint, and parsley\n- Leafy greens such as lettuce and spinach\n- Compact vegetables like cherry tomatoes\n\nUrban gardening not only provides fresh food but also improves air quality and mental well-being." - }, - { - "slug": "digital-detox-benefits", - "title": "The Science Behind Digital Detox", - "author": "Dr. Rachel Kim", - "date": "2024-01-16", - "image": "/images/digital-wellness.jpg", - "excerpt": "Understanding how taking breaks from technology can improve mental health and productivity.", - "featured": false, - "content": "# The Science Behind Digital Detox\n\nResearch shows that regular breaks from digital devices can significantly improve our mental and physical well-being.\n\n## Mental Health Benefits\n\nDigital detoxes have been linked to reduced anxiety, improved sleep quality, and better focus.\n\n## Practical Strategies\n\n- Implement device-free meal times\n- Create technology-free zones in your home\n- Practice mindful consumption of digital content\n\n![Digital wellness concept](/images/digital-meditation.jpg)\n\nSmall changes in our digital habits can lead to significant improvements in overall life satisfaction." - }, - { - "slug": "renewable-energy-trends", - "title": "2024 Renewable Energy Trends to Watch", - "author": "James Wilson", - "date": "2024-01-14", - "image": "/images/solar-installation.jpg", - "excerpt": "The latest developments in renewable energy technology and market adoption.", - "featured": true, - "content": "# 2024 Renewable Energy Trends to Watch\n\nThe renewable energy sector continues to evolve rapidly, with exciting developments across multiple technologies.\n\n## Solar Power Advances\n\nNew photovoltaic technologies are achieving higher efficiency rates while reducing costs.\n\n## Wind Energy Growth\n\nOffshore wind farms are expanding globally, providing clean energy at unprecedented scales.\n\n![Solar installation](/images/solar-installation.jpg)\n\n## Energy Storage Solutions\n\nBattery technology improvements are solving the intermittency challenges of renewable sources.\n\nThe future of energy is increasingly renewable, sustainable, and accessible." - }, - { - "slug": "sustainable-fashion-tips", - "title": "Sustainable Fashion: Style with Purpose", - "author": "Sofia Chen", - "date": "2024-01-12", - "image": "/images/eco-home.jpg", - "excerpt": "How to build a sustainable wardrobe without sacrificing style or breaking the bank.", - "featured": false, - "content": "# Sustainable Fashion: Style with Purpose\n\nThe fashion industry is transforming as consumers demand more sustainable and ethical clothing options.\n\n## Building a Sustainable Wardrobe\n\nFocus on quality pieces that will last for years rather than fast fashion trends.\n\n## Sustainable Shopping Tips\n\n- Buy from ethical brands\n- Shop secondhand and vintage\n- Invest in versatile, timeless pieces\n\nSustainable fashion is about making conscious choices that reflect our values while expressing personal style." - }, - { - "slug": "mindfulness-productivity", - "title": "Mindfulness and Productivity: Finding Balance", - "author": "David Park", - "date": "2024-01-08", - "image": "/images/mindfulness-app.jpg", - "excerpt": "How mindfulness practices can enhance productivity while maintaining work-life balance.", - "featured": false, - "content": "# Mindfulness and Productivity: Finding Balance\n\nContrary to popular belief, slowing down through mindfulness can actually increase our productivity and effectiveness.\n\n![Mindfulness practice](/images/mindfulness-app.jpg)\n\n## The Mindful Approach to Work\n\nMindfulness helps us focus on what truly matters, reducing time spent on unproductive activities.\n\n## Simple Practices\n\n- Take mindful breaks throughout the day\n- Practice single-tasking instead of multitasking\n- Use breathing exercises to manage stress\n\nIntegrating mindfulness into our work routine creates sustainable productivity that doesn't lead to burnout." - }, - { - "slug": "green-building-design", - "title": "Green Building Design: Architecture for the Future", - "author": "Maria Rodriguez", - "date": "2024-01-06", - "image": "/images/eco-home.jpg", - "excerpt": "Exploring sustainable architecture principles that reduce environmental impact.", - "featured": false, - "content": "# Green Building Design: Architecture for the Future\n\nSustainable architecture is reshaping how we design and construct buildings for minimal environmental impact.\n\n## Key Principles\n\nGreen building design focuses on energy efficiency, sustainable materials, and harmony with natural environments.\n\n## Benefits\n\n- Reduced energy consumption\n- Lower operating costs\n- Improved indoor air quality\n- Smaller carbon footprint\n\n![Eco-friendly home](/images/eco-home.jpg)\n\nThe future of construction lies in buildings that work with nature rather than against it." - }, - { - "slug": "electric-vehicle-adoption", - "title": "Electric Vehicle Adoption: Accelerating Change", - "author": "Thomas Anderson", - "date": "2024-01-04", - "image": "/images/battery-storage.jpg", - "excerpt": "The rapid growth of electric vehicles and their impact on transportation and energy.", - "featured": true, - "content": "# Electric Vehicle Adoption: Accelerating Change\n\nElectric vehicles are moving from niche to mainstream as technology improves and costs decrease.\n\n## Market Growth\n\nEV sales are growing exponentially worldwide, driven by environmental concerns and government incentives.\n\n## Infrastructure Development\n\nCharging networks are expanding rapidly to support the growing number of electric vehicles.\n\n![Battery technology](/images/battery-storage.jpg)\n\n## Environmental Impact\n\nElectric vehicles offer significant reductions in greenhouse gas emissions, especially when powered by renewable energy.\n\nThe transition to electric transportation is accelerating, promising cleaner air and reduced dependence on fossil fuels." - }, - { - "slug": "water-conservation-methods", - "title": "Water Conservation: Every Drop Counts", - "author": "Jennifer Lee", - "date": "2024-01-02", - "image": "/images/home-garden.jpg", - "excerpt": "Practical methods for conserving water at home and in the community.", - "featured": false, - "content": "# Water Conservation: Every Drop Counts\n\nWater scarcity affects billions of people worldwide, making conservation efforts more critical than ever.\n\n## Home Conservation Strategies\n\nSimple changes in daily habits can lead to significant water savings.\n\n## Techniques\n\n- Fix leaks promptly\n- Install low-flow fixtures\n- Collect rainwater for gardening\n- Use drought-resistant plants\n\n![Water-wise gardening](/images/home-garden.jpg)\n\nWater conservation is not just about saving money—it's about preserving this precious resource for future generations." - }, - { - "slug": "circular-economy-principles", - "title": "Understanding the Circular Economy", - "author": "Dr. Robert Kim", - "date": "2023-12-28", - "image": "/images/sustainable-living.jpg", - "excerpt": "How circular economy principles can transform business and reduce waste.", - "featured": false, - "content": "# Understanding the Circular Economy\n\nThe circular economy represents a fundamental shift from the traditional linear \"take-make-dispose\" model.\n\n## Core Principles\n\n- Design out waste and pollution\n- Keep products and materials in use\n- Regenerate natural systems\n\n## Business Applications\n\nCompanies are finding innovative ways to implement circular economy principles while maintaining profitability.\n\n![Sustainable practices](/images/sustainable-living.jpg)\n\nThe circular economy offers a pathway to sustainable growth that benefits both business and the environment." - }, - { - "slug": "smart-home-energy", - "title": "Smart Home Technology for Energy Efficiency", - "author": "Kevin Zhang", - "date": "2023-12-25", - "image": "/images/digital-wellness.jpg", - "excerpt": "How smart home devices can reduce energy consumption and costs.", - "featured": false, - "content": "# Smart Home Technology for Energy Efficiency\n\nSmart home technology is making it easier than ever to monitor and reduce energy consumption.\n\n## Smart Devices\n\n- Programmable thermostats\n- Smart lighting systems\n- Energy monitoring plugs\n- Automated window treatments\n\n## Benefits\n\nSmart homes can reduce energy consumption by up to 30% through automated optimization and user awareness.\n\nThe integration of smart technology with sustainable practices creates homes that are both comfortable and environmentally responsible." - }, - { - "slug": "plant-based-nutrition", - "title": "Plant-Based Nutrition: Health and Sustainability", - "author": "Dr. Amanda Foster", - "date": "2023-12-22", - "image": "/images/home-garden.jpg", - "excerpt": "The health and environmental benefits of plant-based eating.", - "featured": true, - "content": "# Plant-Based Nutrition: Health and Sustainability\n\nPlant-based diets offer significant benefits for both personal health and environmental sustainability.\n\n## Health Benefits\n\nResearch shows that plant-based diets can reduce the risk of chronic diseases and improve overall well-being.\n\n## Environmental Impact\n\nPlant-based foods generally require fewer resources and produce lower greenhouse gas emissions than animal products.\n\n![Fresh vegetables](/images/home-garden.jpg)\n\n## Getting Started\n\nTransitioning to a plant-based diet doesn't have to be all-or-nothing—even small changes can make a difference.\n\nPlant-based nutrition represents a powerful way to improve personal health while contributing to environmental sustainability." - }, - { - "slug": "waste-reduction-strategies", - "title": "Zero Waste Living: Practical Strategies", - "author": "Sarah Thompson", - "date": "2023-12-20", - "image": "/images/eco-home.jpg", - "excerpt": "Practical approaches to reducing waste and living more sustainably.", - "featured": false, - "content": "# Zero Waste Living: Practical Strategies\n\nZero waste living is about minimizing the amount of waste we send to landfills through conscious consumption choices.\n\n## The 5 R's\n\n- Refuse what you don't need\n- Reduce what you do need\n- Reuse what you consume\n- Recycle what you cannot refuse, reduce, or reuse\n- Rot (compost) the rest\n\n## Starting Small\n\nBegin with simple swaps like reusable bags, water bottles, and food containers.\n\nZero waste living is a journey, not a destination—every small step contributes to a more sustainable future." - }, - { - "slug": "green-transportation", - "title": "Green Transportation Options for Urban Areas", - "author": "Miguel Santos", - "date": "2023-12-18", - "image": "/images/digital-meditation.jpg", - "excerpt": "Exploring sustainable transportation alternatives in cities.", - "featured": false, - "content": "# Green Transportation Options for Urban Areas\n\nCities worldwide are implementing innovative transportation solutions to reduce emissions and improve air quality.\n\n## Sustainable Options\n\n- Public transit systems\n- Bike-sharing programs\n- Electric scooters\n- Walking and cycling infrastructure\n\n## Benefits\n\nGreen transportation reduces pollution, decreases traffic congestion, and promotes healthier lifestyles.\n\n![Urban mobility](/images/digital-meditation.jpg)\n\nThe future of urban transportation is multimodal, sustainable, and accessible to all residents." - }, - { - "slug": "renewable-energy-storage", - "title": "Energy Storage: The Key to Renewable Success", - "author": "Dr. Elena Petrov", - "date": "2023-12-15", - "image": "/images/battery-storage.jpg", - "excerpt": "How energy storage technology is enabling the renewable energy transition.", - "featured": false, - "content": "# Energy Storage: The Key to Renewable Success\n\nEnergy storage technology is solving the intermittency challenge that has long limited renewable energy adoption.\n\n## Storage Technologies\n\n- Lithium-ion batteries\n- Pumped hydro storage\n- Compressed air energy storage\n- Emerging technologies like hydrogen storage\n\n![Energy storage systems](/images/battery-storage.jpg)\n\n## Grid Stability\n\nEnergy storage systems help maintain grid stability while enabling higher penetration of renewable energy sources.\n\nAs storage costs continue to decline, renewable energy becomes increasingly viable as a primary power source." - } - ] -} diff --git a/lib/blog-server.ts b/lib/blog-server.ts new file mode 100644 index 0000000..a46d598 --- /dev/null +++ b/lib/blog-server.ts @@ -0,0 +1,53 @@ +import { readFileSync, existsSync } from 'fs' +import { join } from 'path' +import matter from 'gray-matter' +import articlesIndex from '../public/articles/articles-index.json' + +export interface BlogPost { + slug: string + title: string + author: string + date: string + image: string + excerpt: string + content: string + featured: boolean +} + +// Server-side function to get post by slug with actual markdown content +export function getPostBySlugServer(slug: string): BlogPost | null { + try { + const markdownPath = join(process.cwd(), 'public/articles', `${slug}.md`) + + if (existsSync(markdownPath)) { + const fileContents = readFileSync(markdownPath, 'utf8') + const { content } = matter(fileContents) + + // Find the article metadata from the index + const articleMetadata = articlesIndex.articles.find(article => article.slug === slug) + + if (!articleMetadata) { + return null + } + + return { + ...articleMetadata, + content + } + } else { + // Fallback: return post with placeholder content + const articleMetadata = articlesIndex.articles.find(article => article.slug === slug) + if (!articleMetadata) { + return null + } + + return { + ...articleMetadata, + content: `# ${articleMetadata.title}\n\nThis is a placeholder content for ${articleMetadata.title}. The full content would be loaded from the markdown file.` + } + } + } catch (error) { + console.error(`Error reading markdown file for ${slug}:`, error) + return null + } +} \ No newline at end of file diff --git a/lib/blog.ts b/lib/blog.ts index 3787d8d..d7d7025 100644 --- a/lib/blog.ts +++ b/lib/blog.ts @@ -1,4 +1,4 @@ -import blogData from "./blog-data.json" +import articlesIndex from '../public/articles/articles-index.json' export interface BlogPost { slug: string @@ -11,10 +11,15 @@ export interface BlogPost { featured: boolean } -// Get all posts from static data +// Get all posts from articles index (client-safe) export function getAllPosts(): BlogPost[] { + const posts: BlogPost[] = articlesIndex.articles.map(article => ({ + ...article, + content: `# ${article.title}\n\nThis is a placeholder content for ${article.title}. The full content would be loaded from the markdown file.` + })) + // Sort posts: featured first, then by date (newest first) - const sortedPosts = [...blogData.posts].sort((a, b) => { + const sortedPosts = posts.sort((a, b) => { // If one is featured and the other isn't, featured comes first if (a.featured && !b.featured) return -1 if (!a.featured && b.featured) return 1 diff --git a/lib/markdown-renderer.tsx b/lib/markdown-renderer.tsx index 5485005..5a1d63a 100644 --- a/lib/markdown-renderer.tsx +++ b/lib/markdown-renderer.tsx @@ -2,8 +2,11 @@ interface MarkdownRendererProps { content: string } +// Conditionally set BASE_PATH based on environment +const BASE_PATH = process.env.NODE_ENV === "production" ? "/StableViewpoints" : "" + export function MarkdownRenderer({ content }: MarkdownRendererProps) { - // Simple markdown to HTML conversion + // Enhanced markdown to HTML conversion const renderMarkdown = (text: string) => { let html = text @@ -16,27 +19,44 @@ export function MarkdownRenderer({ content }: MarkdownRendererProps) { html = html.replace(/\*\*(.*?)\*\*/g, "$1") html = html.replace(/\*(.*?)\*/g, "$1") - // Images + // Code blocks + html = html.replace( + /```([\s\S]*?)```/g, + '
$1
' + ) + + // Inline code + html = html.replace(/`([^`]+)`/g, '$1') + + // Images - handle base path for GitHub Pages html = html.replace( /!\[(.*?)\]\((.*?)\)/gim, - '
$1
', + (match, alt, src) => { + // Add base path to image src if it starts with / + const imageSrc = src.startsWith('/') ? `${BASE_PATH}${src}` : src + return `
${alt}
` + } ) // Links html = html.replace( /\[(.*?)\]\((.*?)\)/gim, - '$1', + '$1', ) // Blockquotes html = html.replace( /^> (.*$)/gim, - '
$1
', + '
$1
', ) + // Horizontal rules + html = html.replace(/^---$/gm, '
') + // Lists - improved list handling const lines = html.split("\n") let inList = false + let inOrderedList = false const processedLines: string[] = [] for (let i = 0; i < lines.length; i++) { @@ -45,15 +65,25 @@ export function MarkdownRenderer({ content }: MarkdownRendererProps) { if (trimmed.startsWith("- ")) { if (!inList) { - processedLines.push('") } + if (inOrderedList) { + processedLines.push("") + } html = processedLines.join("\n") @@ -74,9 +107,14 @@ export function MarkdownRenderer({ content }: MarkdownRendererProps) { trimmed.startsWith("") || + trimmed.startsWith("") || trimmed.startsWith("