Media and Code Demo

January 30, 2024by Your Name

Media and Code Demonstration

This post showcases the enhanced features of our MDX blog including proper syntax highlighting, image embedding, and YouTube video support.

Syntax Highlighting with Sugar-High

Here's a TypeScript React component with beautiful syntax highlighting:

typescript
import { useState, useEffect } from 'react'

interface User {
  id: number
  name: string
  email: string
}

function UserProfile({ userId }: { userId: number }) {
  const [user, setUser] = useState<User | null>(null)
  const [loading, setLoading] = useState(true)

  useEffect(() => {
    async function fetchUser() {
      try {
        const response = await fetch(`/api/users/${userId}`)
        const userData = await response.json()
        setUser(userData)
      } catch (error) {
        console.error('Failed to fetch user:', error)
      } finally {
        setLoading(false)
      }
    }

    fetchUser()
  }, [userId])

  if (loading) {
    return <div className="spinner">Loading...</div>
  }

  return (
    <div className="user-profile">
      <h2>{user?.name}</h2>
      <p>{user?.email}</p>
    </div>
  )
}

export default UserProfile

Python Example

Here's some Python code with syntax highlighting:

python
import asyncio
from typing import List, Optional

class DataProcessor:
    def __init__(self, batch_size: int = 100):
        self.batch_size = batch_size
        self.processed_count = 0
    
    async def process_data(self, data: List[dict]) -> List[dict]:
        """Process data in batches asynchronously."""
        results = []
        
        for i in range(0, len(data), self.batch_size):
            batch = data[i:i + self.batch_size]
            processed_batch = await self._process_batch(batch)
            results.extend(processed_batch)
            self.processed_count += len(processed_batch)
            
        return results
    
    async def _process_batch(self, batch: List[dict]) -> List[dict]:
        # Simulate async processing
        await asyncio.sleep(0.1)
        return [{'processed': True, **item} for item in batch]

# Usage example
async def main():
    processor = DataProcessor(batch_size=50)
    sample_data = [{'id': i, 'value': f'item_{i}'} for i in range(200)]
    
    results = await processor.process_data(sample_data)
    print(f"Processed {len(results)} items")

if __name__ == "__main__":
    asyncio.run(main())

Image Embedding

Using the BlogImage Component

You can embed images with captions using the BlogImage component:

Programming workspace with laptop and code
A modern development workspace

Regular Markdown Image

You can also use regular markdown syntax for images:

Next.js Logo

YouTube Video Embedding

Using Video ID

Using Full URL

JSON Configuration Example

json
{
  "name": "my-blog",
  "version": "1.0.0",
  "scripts": {
    "dev": "next dev",
    "build": "next build",
    "start": "next start",
    "lint": "next lint"
  },
  "dependencies": {
    "@next/mdx": "^15.5.0",
    "@mdx-js/loader": "^3.1.0",
    "sugar-high": "^0.9.3",
    "gray-matter": "^4.0.3"
  }
}

Shell Commands

bash
# Install dependencies
npm install @next/mdx @mdx-js/loader sugar-high

# Build the project
npm run build

# Start development server
npm run dev

# Deploy to production
npm run start

CSS Example

css
.code-block {
  background: #1a1a1a;
  border-radius: 8px;
  padding: 1rem;
  overflow-x: auto;
}

.code-block pre {
  margin: 0;
  font-family: 'JetBrains Mono', 'Fira Code', monospace;
  font-size: 0.875rem;
  line-height: 1.5;
}

@media (max-width: 768px) {
  .code-block {
    font-size: 0.75rem;
  }
}

Conclusion

Our MDX blog now supports:

  1. Rich syntax highlighting with sugar-high
  2. Image embedding with captions and optimization
  3. YouTube video embedding with responsive design
  4. Multiple code languages with proper styling
  5. Responsive media that works on all devices

This creates a much more engaging and feature-rich blogging experience!