SEB'S DEV

← Back to home

Testing Syntax Highlighting

demosyntax-highlightingcode

This post demonstrates the new syntax highlighting capabilities using rehype-pretty-code and Shiki.

TypeScript Example

Here's a TypeScript function with type annotations:

interface User {
  id: number;
  name: string;
  email: string;
  createdAt: Date;
}
 
async function fetchUser(userId: number): Promise<User | null> {
  try {
    const response = await fetch(`/api/users/${userId}`);
    if (!response.ok) {
      throw new Error(`HTTP error! status: ${response.status}`);
    }
    const user: User = await response.json();
    return user;
  } catch (error) {
    console.error("Failed to fetch user:", error);
    return null;
  }
}

JavaScript with Highlighted Lines

The following code highlights lines 2 and 4-5:

function calculateTotal(items) {
  const subtotal = items.reduce((sum, item) => sum + item.price, 0);
  const tax = subtotal * 0.08;
  const shipping = subtotal > 50 ? 0 : 5.99;
  const total = subtotal + tax + shipping;
  return total;
}

Python Example

Here's a Python class with methods:

class BlogPost:
    def __init__(self, title, content, author):
        self.title = title
        self.content = content
        self.author = author
        self.published = False
 
    def publish(self):
        if not self.published:
            self.published = True
            print(f"Published: {self.title} by {self.author}")
        else:
            print("Post is already published")
 
    def __str__(self):
        status = "Published" if self.published else "Draft"
        return f"{self.title} ({status})"

React Component

A functional React component with hooks:

import { useState, useEffect } from "react";
 
interface Props {
  initialCount?: number;
}
 
export function Counter({ initialCount = 0 }: Props) {
  const [count, setCount] = useState(initialCount);
  const [isEven, setIsEven] = useState(initialCount % 2 === 0);
 
  useEffect(() => {
    setIsEven(count % 2 === 0);
  }, [count]);
 
  return (
    <div className="counter">
      <h2>Count: {count}</h2>
      <p>The count is {isEven ? "even" : "odd"}</p>
      <button onClick={() => setCount(count + 1)}>Increment</button>
      <button onClick={() => setCount(count - 1)}>Decrement</button>
    </div>
  );
}

CSS Styling

Some modern CSS with custom properties:

:root {
  --primary-color: #3b82f6;
  --secondary-color: #8b5cf6;
  --text-color: #1f2937;
  --border-radius: 0.5rem;
}
 
.card {
  background: linear-gradient(
    135deg,
    var(--primary-color),
    var(--secondary-color)
  );
  color: white;
  padding: 2rem;
  border-radius: var(--border-radius);
  box-shadow: 0 10px 15px -3px rgba(0, 0, 0, 0.1);
  transition: transform 0.3s ease;
}
 
.card:hover {
  transform: translateY(-5px);
}

SQL Query

A database query example:

SELECT
  u.id,
  u.name,
  u.email,
  COUNT(p.id) as post_count,
  MAX(p.created_at) as last_post_date
FROM users u
LEFT JOIN posts p ON u.id = p.author_id
WHERE u.active = true
GROUP BY u.id, u.name, u.email
HAVING COUNT(p.id) > 5
ORDER BY post_count DESC
LIMIT 10;

Inline Code

You can also use inline code like const message = "Hello World" or npm install react within paragraphs.

Conclusion

The syntax highlighting system now supports:

All code blocks are rendered at build time with no client-side JavaScript required!