Interactive Demos
Explore the full capabilities of the <code-block> component. Each demo shows the markup and the rendered result.
Basic Usage
The simplest usage - just wrap your code in a <code-block> element with a language attribute.
Usage
<code-block language="javascript">
const greeting = "Hello, World!";
console.log(greeting);
</code-block>
Result
const greeting = "Hello, World!";
console.log(greeting);
External File Loading
Load code from an external URL using the src attribute. The language and filename are auto-detected from the URL.
Usage
<!-- Load code from a URL - language auto-detected from extension -->
<code-block src="examples/greeting.js"></code-block>
<!-- Override auto-detected language -->
<code-block src="examples/greeting.js" language="typescript"></code-block>
Result
Features
- Auto-detection: Language and filename are automatically detected from the URL
- Loading state: Shows a spinner while fetching
- Error handling: Displays error message with retry button if fetch fails
- Events: Dispatches
code-loaded and code-load-error events
Listening for Events
const codeBlock = document.querySelector('code-block[src]');
codeBlock.addEventListener('code-loaded', (e) => {
console.log('Loaded from:', e.detail.url);
console.log('Code:', e.detail.code);
});
codeBlock.addEventListener('code-load-error', (e) => {
console.error('Failed to load:', e.detail.url);
console.error('Error:', e.detail.error);
});
Filename Display
Add a filename attribute to show a filename in the header.
Usage
<code-block language="javascript" filename="app.js">
export function init() {
console.log('App initialized');
}
</code-block>
Result
export function init() {
console.log('App initialized');
}
Line Numbers
Add line numbers with the show-lines attribute.
Usage
<code-block language="javascript" show-lines filename="fibonacci.js">
function fibonacci(n) {
if (n <= 1) return n;
return fibonacci(n - 1) + fibonacci(n - 2);
}
for (let i = 0; i < 10; i++) {
console.log(`F(${i}) = ${fibonacci(i)}`);
}
</code-block>
Result
function fibonacci(n) {
if (n <= 1) return n;
return fibonacci(n - 1) + fibonacci(n - 2);
}
for (let i = 0; i < 10; i++) {
console.log(`F(${i}) = ${fibonacci(i)}`);
}
Custom Starting Line
Use start-line to begin numbering from a specific line (useful for showing excerpts).
Usage
<code-block language="javascript" show-lines start-line="42" filename="app.js:42-50">
// Continuing from line 42...
function handleSubmit(event) {
event.preventDefault();
const formData = new FormData(event.target);
const data = Object.fromEntries(formData);
submitToAPI(data);
}
</code-block>
Result
// Continuing from line 42...
function handleSubmit(event) {
event.preventDefault();
const formData = new FormData(event.target);
const data = Object.fromEntries(formData);
submitToAPI(data);
}
Line Highlighting
Draw attention to specific lines with highlight-lines. Supports individual lines and ranges.
Single Lines
Usage
<code-block language="javascript" show-lines highlight-lines="3,7">
async function fetchUser(id) {
try {
const response = await fetch(`/api/users/${id}`);
if (!response.ok) {
throw new Error('User not found');
}
return await response.json();
} catch (error) {
console.error('Failed:', error);
}
}
</code-block>
Result
async function fetchUser(id) {
try {
const response = await fetch(`/api/users/${id}`);
if (!response.ok) {
throw new Error('User not found');
}
return await response.json();
} catch (error) {
console.error('Failed:', error);
}
}
Line Ranges
Usage
<code-block language="javascript" show-lines highlight-lines="2-4,9-11">
class Calculator {
add(a, b) {
return a + b;
}
subtract(a, b) {
return a - b;
}
multiply(a, b) {
return a * b;
}
}
</code-block>
Result
class Calculator {
add(a, b) {
return a + b;
}
subtract(a, b) {
return a - b;
}
multiply(a, b) {
return a * b;
}
}
Focus Mode
Combine focus-mode with highlight-lines to dim non-highlighted lines, drawing attention to specific code.
Usage
<code-block language="javascript" show-lines highlight-lines="3-5" focus-mode>
async function fetchUser(id) {
try {
const response = await fetch(`/api/users/${id}`);
const data = await response.json();
return data;
} catch (error) {
console.error('Failed:', error);
return null;
}
}
</code-block>
Result
async function fetchUser(id) {
try {
const response = await fetch(`/api/users/${id}`);
const data = await response.json();
return data;
} catch (error) {
console.error('Failed:', error);
return null;
}
}
Comparison: Without vs With Focus Mode
Without Focus Mode
class Calculator {
add(a, b) {
return a + b;
}
subtract(a, b) {
return a - b;
}
}
With Focus Mode
class Calculator {
add(a, b) {
return a + b;
}
subtract(a, b) {
return a - b;
}
}
Customizing Focus Intensity
Adjust the dimming with CSS custom properties:
/* Subtle dim */
.subtle-focus {
--cb-focus-dim-opacity: 0.6;
--cb-focus-blur: 0;
}
/* Heavy dim */
.heavy-focus {
--cb-focus-dim-opacity: 0.2;
--cb-focus-blur: 1px;
}
Multi-File Tabs
Group related files with <code-block-group> for a tabbed interface. Each child needs a filename.
Usage
<code-block-group>
<code-block language="html" filename="index.html">
<!DOCTYPE html>
<html>
<head><link rel="stylesheet" href="styles.css"></head>
<body><h1>Hello</h1></body>
</html>
</code-block>
<code-block language="css" filename="styles.css">
body {
font-family: system-ui, sans-serif;
margin: 0;
padding: 2rem;
}
</code-block>
</code-block-group>
Result
<!DOCTYPE html>
<html>
<head><link rel="stylesheet" href="styles.css"></head>
<body><h1>Hello</h1></body>
</html>
body {
font-family: system-ui, sans-serif;
margin: 0;
padding: 2rem;
}
Collapsible Code
Long code blocks can be collapsed by default with the collapsed attribute. Click to expand.
Usage
<code-block language="javascript" collapsed filename="utils.js">
// This content is collapsed by default
export function chunk(array, size) {
const chunks = [];
for (let i = 0; i < array.length; i += size) {
chunks.push(array.slice(i, i + size));
}
return chunks;
}
export function unique(array) {
return [...new Set(array)];
}
</code-block>
Result
// This content is collapsed by default
export function chunk(array, size) {
const chunks = [];
for (let i = 0; i < array.length; i += size) {
chunks.push(array.slice(i, i + size));
}
return chunks;
}
export function unique(array) {
return [...new Set(array)];
}
Theme Support
Set a specific theme with the theme attribute. Values: light, dark, or auto.
Usage
<!-- Force light theme -->
<code-block language="javascript" theme="light">
const theme = 'light';
</code-block>
<!-- Force dark theme -->
<code-block language="javascript" theme="dark">
const theme = 'dark';
</code-block>
Result
Light Theme
const theme = 'light';
document.body.classList.add(theme);
Dark Theme
const theme = 'dark';
document.body.classList.add(theme);
Diff Support
Use language="diff" to show code changes. Lines with + are additions, - are removals.
Usage
<code-block language="diff" filename="changes.diff">
function greet(name) {
- console.log('Hello ' + name);
+ console.log(`Hello, ${name}!`);
}
-greet('world');
+greet('World');
</code-block>
Result
function greet(name) {
- console.log('Hello ' + name);
+ console.log(`Hello, ${name}!`);
}
-greet('world');
+greet('World');
Hide Copy Button
Use no-copy to hide the copy button and prevent text selection.
Usage
<code-block language="javascript" no-copy>
// This block has no copy button
const secret = 'hidden';
</code-block>
Result
// This block has no copy button
const secret = 'hidden';
Custom Styling
Customize appearance with CSS custom properties.
Usage
<style>
.ocean-theme {
--cb-border-radius: 16px;
--cb-header-bg: #1e3a5f;
--cb-code-bg: #0f1c2e;
--cb-text-color: #e0f0ff;
--cb-keyword: #ff7eb6;
--cb-string: #7ee787;
--cb-function: #79c0ff;
}
</style>
<code-block language="javascript" class="ocean-theme">
function hello() {
return "Custom themed!";
}
</code-block>
Result
// Custom ocean theme
function createGradient(colors) {
const stops = colors.map((c, i) =>
`${c} ${(i / (colors.length - 1)) * 100}%`
);
return `linear-gradient(90deg, ${stops.join(', ')})`;
}
const gradient = createGradient(['#ff0080', '#7928ca']);
console.log(gradient);
Supported Languages
Examples of syntax highlighting for various languages.
Python
import asyncio
from dataclasses import dataclass
from typing import List, Optional
@dataclass
class DataRecord:
id: int
value: str
metadata: Optional[dict] = None
async def process_records(records: List[DataRecord]) -> List[str]:
"""Process a list of records asynchronously."""
tasks = [process_single(r) for r in records]
return await asyncio.gather(*tasks)
TypeScript
interface User {
id: string;
name: string;
email: string;
roles: Role[];
}
type Role = 'admin' | 'editor' | 'viewer';
function hasPermission(user: User, role: Role): boolean {
return user.roles.includes(role);
}
CSS
:root {
--primary: #0969da;
--background: #ffffff;
}
.card {
background: var(--background);
border-radius: 8px;
box-shadow: 0 2px 8px rgba(0, 0, 0, 0.1);
transition: transform 0.2s ease;
}
.card:hover {
transform: translateY(-2px);
}
YAML
name: CI Pipeline
on:
push:
branches: [main]
jobs:
test:
runs-on: ubuntu-latest
steps:
- uses: actions/checkout@v4
- run: npm ci
- run: npm test
Bash
#!/bin/bash
set -e
echo "Building project..."
npm run build
echo "Running tests..."
npm test
echo "Deploying..."
rsync -avz dist/ server:/var/www/app/