https://andrewbaker.ninja/wp-content/themes/twentysixteen/fonts/merriweather-plus-montserrat-plus-inconsolata.css

Code Convert Test Page

CloudScale Code Block Test Page

This page tests the CloudScale Code Block plugin across multiple languages, features, and edge cases.

1 Bash

#!/bin/bash
echo "Hello from CloudScale Code Block"
for i in {1..5}; do
    echo "Iteration $i"
done

# Check if a file exists
if [ -f "/etc/hosts" ]; then
    cat /etc/hosts | grep localhost
fi

2 Python

import json
from datetime import datetime

class CloudScaleTest:
    def __init__(self, name: str):
        self.name = name
        self.created = datetime.now()

    def to_dict(self) -> dict:
        return {
            "name": self.name,
            "created": self.created.isoformat()
        }

if __name__ == "__main__":
    test = CloudScaleTest("highlight test")
    print(json.dumps(test.to_dict(), indent=2))

3 JavaScript

const express = require('express');
const app = express();

app.get('/api/health', async (req, res) => {
    const uptime = process.uptime();
    res.json({
        status: 'ok',
        uptime: Math.floor(uptime),
        timestamp: new Date().toISOString()
    });
});

app.listen(3000, () => console.log('Server running on port 3000'));

4 Java

public class VirtualThreadDemo {
    public static void main(String[] args) throws Exception {
        try (var executor = java.util.concurrent.Executors.newVirtualThreadPerTaskExecutor()) {
            for (int i = 0; i < 10_000; i++) {
                final int id = i;
                executor.submit(() -> {
                    Thread.sleep(java.time.Duration.ofMillis(100));
                    System.out.println("Task " + id + " on " + Thread.currentThread());
                    return null;
                });
            }
        }
    }
}

5 SQL

SELECT
    p.post_title,
    COUNT(cb.block_id) AS code_blocks,
    MAX(cb.language) AS primary_language
FROM wp_posts p
INNER JOIN wp_code_blocks cb ON cb.post_id = p.ID
WHERE p.post_status = 'publish'
    AND cb.block_type = 'cloudscale/code-block'
GROUP BY p.ID, p.post_title
HAVING COUNT(cb.block_id) > 3
ORDER BY code_blocks DESC
LIMIT 20;

6 YAML

apiVersion: apps/v1
kind: Deployment
metadata:
  name: cloudscale-app
  labels:
    app: cloudscale
spec:
  replicas: 3
  selector:
    matchLabels:
      app: cloudscale
  template:
    spec:
      containers:
        - name: app
          image: cloudscale/app:latest
          ports:
            - containerPort: 8080
          env:
            - name: DATABASE_URL
              valueFrom:
                secretKeyRef:
                  name: db-credentials
                  key: url

7 Docker

FROM node:20-alpine AS builder
WORKDIR /app
COPY package*.json ./
RUN npm ci --production
COPY . .
RUN npm run build

FROM node:20-alpine
WORKDIR /app
COPY --from=builder /app/dist ./dist
COPY --from=builder /app/node_modules ./node_modules
EXPOSE 3000
CMD ["node", "dist/server.js"]

8 Go

package main

import (
    "fmt"
    "net/http"
    "sync"
)

func main() {
    var wg sync.WaitGroup
    urls := []string{
        "https://example.com",
        "https://httpbin.org/get",
        "https://jsonplaceholder.typicode.com/posts/1",
    }

    for _, url := range urls {
        wg.Add(1)
        go func(u string) {
            defer wg.Done()
            resp, err := http.Get(u)
            if err != nil {
                fmt.Printf("Error: %s\n", err)
                return
            }
            defer resp.Body.Close()
            fmt.Printf("%s => %d\n", u, resp.StatusCode)
        }(url)
    }
    wg.Wait()
}

9 Rust

use std::collections::HashMap;

fn word_count(text: &str) -> HashMap<&str, usize> {
    let mut counts = HashMap::new();
    for word in text.split_whitespace() {
        let count = counts.entry(word).or_insert(0);
        *count += 1;
    }
    counts
}

fn main() {
    let text = "the quick brown fox jumps over the lazy fox";
    let counts = word_count(text);
    for (word, count) in &counts {
        println!("{}: {}", word, count);
    }
}

10 TypeScript

interface CodeBlock {
    content: string;
    language: string;
    title?: string;
    theme: 'dark' | 'light';
}

async function migrateBlocks(postId: number): Promise<CodeBlock[]> {
    const response = await fetch(`/wp-json/wp/v2/posts/${postId}`);
    const post = await response.json();

    const blocks: CodeBlock[] = post.content.raw
        .match(/<!-- wp:code -->([\s\S]*?)<!-- \/wp:code -->/g)
        ?.map((block: string) => ({
            content: extractCode(block),
            language: detectLanguage(block),
            theme: 'dark' as const
        })) ?? [];

    return blocks;
}

11 PHP

<?php
function cloudscale_render_code_block(array $attributes): string {
    $content  = $attributes['content'] ?? '';
    $language = $attributes['language'] ?? '';
    $title    = $attributes['title'] ?? '';
    $theme    = get_option('cloudscale_default_theme', 'dark');

    $escaped = htmlspecialchars($content, ENT_QUOTES | ENT_HTML5, 'UTF-8');

    $html  = '<div class="cs-code-block" data-theme="' . esc_attr($theme) . '">';
    $html .= '<pre><code class="language-' . esc_attr($language) . '">';
    $html .= $escaped;
    $html .= '</code></pre>';
    $html .= '</div>';

    return $html;
}

12 CSS

.cs-code-block {
    position: relative;
    margin: 1.5em 0;
    border-radius: 8px;
    overflow: hidden;
    font-family: 'JetBrains Mono', monospace;
}

.cs-code-block[data-theme="dark"] pre {
    background: #282c34;
    color: #abb2bf;
}

.cs-code-block .copy-button {
    position: absolute;
    top: 8px;
    right: 8px;
    opacity: 0;
    transition: opacity 0.2s ease;
}

.cs-code-block:hover .copy-button {
    opacity: 1;
}

13 JSON

{
    "name": "cloudscale-code-block",
    "version": "1.0.0",
    "description": "Syntax highlighting for WordPress",
    "languages": [
        "bash", "python", "javascript", "typescript",
        "java", "go", "rust", "sql", "yaml", "docker",
        "php", "css", "json", "xml", "markdown"
    ],
    "features": {
        "autoDetect": true,
        "copyButton": true,
        "themeToggle": true,
        "lineNumbers": true
    }
}

14 Edge Cases

14.1 Empty Code Block

14.2 Single Line

echo "one liner"

14.3 Long Lines (horizontal scroll test)

curl -X POST https://api.example.com/v1/very/long/endpoint/path/that/should/trigger/horizontal/scrolling/in/the/code/block -H "Authorization: Bearer eyJhbGciOiJSUzI1NiIsInR5cCI6IkpXVCJ9.eyJzdWIiOiIxMjM0NTY3ODkwIiwibmFtZSI6IkFuZHJldyBCYWtlciIsImlhdCI6MTUxNjIzOTAyMn0" -H "Content-Type: application/json" -d '{"key": "value", "nested": {"deep": "object"}}'

14.4 Special Characters

<div class="test">
    <p>Angle brackets &lt;should&gt; render correctly</p>
    <script>alert("XSS test — this should be escaped")</script>
    <a href="https://example.com?foo=bar&baz=qux">Link with ampersands</a>
</div>

14.5 No Language Specified (auto detect test)

const http = require('http');
http.createServer((req, res) => {
    res.writeHead(200);
    res.end('hello');
}).listen(8080);

Done

If all 14 sections above render with syntax highlighting, copy buttons, and theme toggles, the plugin is working correctly.

Leave a Reply

Your email address will not be published. Required fields are marked *