first commit

This commit is contained in:
Matt Kane
2026-04-01 10:44:22 +01:00
commit 43fcb9a131
1789 changed files with 395041 additions and 0 deletions

View File

@@ -0,0 +1,12 @@
<!doctype html>
<html lang="en">
<head>
<meta charset="UTF-8" />
<meta name="viewport" content="width=device-width, initial-scale=1.0" />
<title>EmDash Block Kit Playground</title>
</head>
<body>
<div id="root"></div>
<script type="module" src="/src/main.tsx"></script>
</body>
</html>

View File

@@ -0,0 +1,30 @@
{
"name": "@emdashcms/blocks-playground",
"version": "0.0.0",
"private": true,
"type": "module",
"scripts": {
"dev": "vite",
"build": "vite build",
"preview": "vite preview"
},
"dependencies": {
"@emdashcms/blocks": "workspace:*",
"@cloudflare/kumo": "^1.1.0",
"@phosphor-icons/react": "catalog:",
"react": "catalog:",
"react-dom": "catalog:"
},
"devDependencies": {
"@tailwindcss/vite": "^4.1.11",
"@types/react": "catalog:",
"@types/react-dom": "catalog:",
"@vitejs/plugin-react": "^4.6.0",
"tailwindcss": "^4.1.11",
"typescript": "catalog:",
"vite": "^6.3.5",
"wrangler": "^4.63.0"
},
"peerDependencies": {},
"optionalDependencies": {}
}

View File

@@ -0,0 +1,419 @@
import { Sun, Moon, Share, Check, Trash, CaretDown, Warning, Plus } from "@phosphor-icons/react";
import { BlockRenderer, validateBlocks } from "@emdashcms/blocks";
import type { Block, BlockInteraction } from "@emdashcms/blocks";
import { useCallback, useEffect, useMemo, useRef, useState } from "react";
import { blockCatalog } from "./block-defaults";
import { templates } from "./templates";
import { useResizable } from "./useResizable";
// ── Types ────────────────────────────────────────────────────────────────────
interface ActionLogEntry {
id: number;
timestamp: Date;
interaction: BlockInteraction;
}
// ── Hash sharing ─────────────────────────────────────────────────────────────
function encodeToHash(blocks: Block[]): string {
try {
const json = JSON.stringify(blocks);
return btoa(encodeURIComponent(json));
} catch {
return "";
}
}
function decodeFromHash(hash: string): Block[] | null {
try {
const json = decodeURIComponent(atob(hash));
const parsed: unknown = JSON.parse(json);
if (!Array.isArray(parsed)) return null;
const result = validateBlocks(parsed);
if (!result.valid) return null;
return parsed as Block[];
} catch {
return null;
}
}
// ── Drag handle ──────────────────────────────────────────────────────────────
function DragHandle({
onMouseDown,
isDragging,
}: {
onMouseDown: (e: React.MouseEvent) => void;
isDragging: boolean;
}) {
return (
<div
className={`group relative w-[5px] shrink-0 cursor-col-resize ${isDragging ? "bg-kumo-info/40" : ""}`}
onMouseDown={onMouseDown}
>
{/* Visible border line */}
<div className="absolute inset-y-0 left-1/2 w-px -translate-x-1/2 bg-kumo-line group-hover:bg-kumo-info/50" />
</div>
);
}
// ── Component ────────────────────────────────────────────────────────────────
export function Playground() {
const [theme, setTheme] = useState<"light" | "dark">(() => {
if (
typeof window !== "undefined" &&
window.matchMedia("(prefers-color-scheme: dark)").matches
) {
return "dark";
}
return "light";
});
// Load initial blocks from hash or first template
const [blocks, setBlocks] = useState<Block[]>(() => {
if (typeof window !== "undefined" && window.location.hash.length > 1) {
const decoded = decodeFromHash(window.location.hash.slice(1));
if (decoded) return decoded;
}
return templates[0]?.blocks ?? [];
});
const [editorText, setEditorText] = useState(() => JSON.stringify(blocks, null, 2));
const [parseError, setParseError] = useState<string | null>(null);
const [validationErrors, setValidationErrors] = useState<string[]>([]);
const [actionLog, setActionLog] = useState<ActionLogEntry[]>([]);
const [copied, setCopied] = useState(false);
const [templateMenuOpen, setTemplateMenuOpen] = useState(false);
const logEndRef = useRef<HTMLDivElement>(null);
const nextId = useRef(0);
const templateMenuRef = useRef<HTMLDivElement>(null);
// Resizable panels
const catalog = useResizable({ initial: 220, min: 160, max: 320 });
const editor = useResizable({ initial: 480, min: 300, max: 800 });
// Apply theme
useEffect(() => {
document.documentElement.setAttribute("data-theme", theme);
}, [theme]);
// Close template menu on outside click
useEffect(() => {
function handleClick(e: MouseEvent) {
if (templateMenuRef.current && !templateMenuRef.current.contains(e.target as Node)) {
setTemplateMenuOpen(false);
}
}
if (templateMenuOpen) {
document.addEventListener("mousedown", handleClick);
return () => document.removeEventListener("mousedown", handleClick);
}
}, [templateMenuOpen]);
// Auto-scroll log
useEffect(() => {
logEndRef.current?.scrollIntoView({ behavior: "smooth" });
}, [actionLog]);
// Parse editor text into blocks
const updateFromText = useCallback((text: string) => {
setEditorText(text);
try {
const parsed: unknown = JSON.parse(text);
setParseError(null);
if (!Array.isArray(parsed)) {
setParseError("Root must be an array of blocks");
return;
}
const result = validateBlocks(parsed);
const validated = parsed as Block[];
if (!result.valid) {
setValidationErrors(result.errors.map((e) => `${e.path}: ${e.message}`));
// Still render what we can
setBlocks(validated);
} else {
setValidationErrors([]);
setBlocks(validated);
}
} catch (err) {
setParseError(err instanceof Error ? err.message : "Invalid JSON");
}
}, []);
// Handle block interactions
const handleAction = useCallback((interaction: BlockInteraction) => {
setActionLog((prev) => [...prev, { id: nextId.current++, timestamp: new Date(), interaction }]);
}, []);
// Load a template
const loadTemplate = useCallback((index: number) => {
const template = templates[index];
if (!template) return;
const text = JSON.stringify(template.blocks, null, 2);
setEditorText(text);
setBlocks(template.blocks);
setParseError(null);
setValidationErrors([]);
setTemplateMenuOpen(false);
}, []);
// Insert a block from the catalog
const insertBlock = useCallback(
(catalogIndex: number) => {
const entry = blockCatalog[catalogIndex];
if (!entry) return;
const newBlock = entry.create();
const updated = [...blocks, newBlock];
const text = JSON.stringify(updated, null, 2);
setBlocks(updated);
setEditorText(text);
setParseError(null);
setValidationErrors([]);
},
[blocks],
);
// Share URL
const shareUrl = useCallback(async () => {
const hash = encodeToHash(blocks);
const url = `${window.location.origin}${window.location.pathname}#${hash}`;
window.history.replaceState(null, "", `#${hash}`);
try {
await navigator.clipboard.writeText(url);
setCopied(true);
setTimeout(setCopied, 2000, false);
} catch {
// Fallback: just update the URL
}
}, [blocks]);
// Error count for status bar
const errorCount = useMemo(() => {
let count = 0;
if (parseError) count++;
count += validationErrors.length;
return count;
}, [parseError, validationErrors]);
return (
<div className="flex h-screen flex-col" style={{ colorScheme: theme }}>
{/* ── Toolbar ─────────────────────────────────────── */}
<header className="flex h-11 shrink-0 items-center gap-2 border-b border-kumo-line bg-kumo-bg px-3">
<span className="text-sm font-semibold text-kumo-text">Block Kit Playground</span>
<div className="ml-auto flex items-center gap-1.5">
{/* Template picker */}
<div className="relative" ref={templateMenuRef}>
<button
type="button"
onClick={() => setTemplateMenuOpen((v) => !v)}
className="flex items-center gap-1 rounded-md px-2.5 py-1.5 text-xs font-medium text-kumo-text-secondary hover:bg-kumo-tint"
>
Templates
<CaretDown size={12} weight="bold" />
</button>
{templateMenuOpen && (
<div
className="absolute right-0 top-full z-50 mt-1 w-64 rounded-lg border border-kumo-line p-1 shadow-lg"
style={{ backgroundColor: "var(--kumo-bg, Canvas)" }}
>
{templates.map((t, i) => (
<button
key={t.name}
type="button"
onClick={() => loadTemplate(i)}
className="flex w-full flex-col items-start rounded-md px-3 py-2 text-left hover:bg-kumo-tint"
>
<span className="text-sm font-medium text-kumo-text">{t.name}</span>
<span className="text-xs text-kumo-text-secondary">{t.description}</span>
</button>
))}
</div>
)}
</div>
{/* Share */}
<button
type="button"
onClick={shareUrl}
className="flex items-center gap-1 rounded-md px-2.5 py-1.5 text-xs font-medium text-kumo-text-secondary hover:bg-kumo-tint"
>
{copied ? <Check size={14} /> : <Share size={14} />}
{copied ? "Copied!" : "Share"}
</button>
{/* Theme toggle */}
<button
type="button"
onClick={() => setTheme((t) => (t === "light" ? "dark" : "light"))}
className="rounded-md p-1.5 text-kumo-text-secondary hover:bg-kumo-tint"
aria-label="Toggle theme"
>
{theme === "light" ? <Moon size={16} /> : <Sun size={16} />}
</button>
</div>
</header>
{/* ── Three-column layout ─────────────────────────── */}
<div className="flex min-h-0 flex-1">
{/* ── Left: Block catalog ──────────────────────── */}
<div className="flex shrink-0 flex-col" style={{ width: catalog.width }}>
<div className="flex h-8 items-center border-b border-kumo-line bg-kumo-tint/50 px-3">
<span className="text-[11px] font-medium uppercase tracking-wide text-kumo-text-secondary">
Add Block
</span>
</div>
<div className="min-h-0 flex-1 overflow-auto p-1.5">
{blockCatalog.map((entry, i) => (
<button
key={entry.type}
type="button"
onClick={() => insertBlock(i)}
className="flex w-full items-start gap-2 rounded-md px-2.5 py-2 text-left hover:bg-kumo-tint"
>
<Plus
size={14}
weight="bold"
className="mt-0.5 shrink-0 text-kumo-text-secondary"
/>
<div className="min-w-0">
<div className="text-xs font-medium text-kumo-text">{entry.label}</div>
<div className="text-[11px] leading-tight text-kumo-text-secondary">
{entry.description}
</div>
</div>
</button>
))}
</div>
</div>
<DragHandle onMouseDown={catalog.handleMouseDown} isDragging={catalog.isDragging} />
{/* ── Center: JSON editor ──────────────────────── */}
<div className="flex shrink-0 flex-col" style={{ width: editor.width }}>
<div className="flex h-8 items-center border-b border-kumo-line bg-kumo-tint/50 px-3">
<span className="text-[11px] font-medium uppercase tracking-wide text-kumo-text-secondary">
JSON Editor
</span>
{errorCount > 0 && (
<span className="ml-auto flex items-center gap-1 text-[11px] font-medium text-kumo-warning">
<Warning size={12} weight="fill" />
{errorCount} {errorCount === 1 ? "error" : "errors"}
</span>
)}
</div>
<textarea
className="editor-textarea min-h-0 flex-1 border-none bg-kumo-bg p-3 text-kumo-text outline-none"
value={editorText}
onChange={(e: React.ChangeEvent<HTMLTextAreaElement>) => updateFromText(e.target.value)}
spellCheck={false}
autoCapitalize="off"
autoCorrect="off"
/>
{/* Error display */}
{(parseError ?? validationErrors.length > 0) && (
<div className="max-h-32 shrink-0 overflow-auto border-t border-kumo-line bg-kumo-danger/5 p-2">
{parseError && <p className="text-xs text-kumo-danger">{parseError}</p>}
{validationErrors.map((err, i) => (
<p key={i} className="text-xs text-kumo-warning">
{err}
</p>
))}
</div>
)}
</div>
<DragHandle onMouseDown={editor.handleMouseDown} isDragging={editor.isDragging} />
{/* ── Right: Preview + Action log ──────────────── */}
<div className="flex min-w-0 flex-1 flex-col">
{/* Preview */}
<div className="flex h-8 items-center border-b border-kumo-line bg-kumo-tint/50 px-3">
<span className="text-[11px] font-medium uppercase tracking-wide text-kumo-text-secondary">
Preview
</span>
</div>
<div className="min-h-0 flex-1 overflow-auto p-4">
<div className="mx-auto max-w-2xl">
{!parseError && blocks.length > 0 ? (
<BlockRenderer blocks={blocks} onAction={handleAction} />
) : (
<div className="flex h-full items-center justify-center">
<p className="text-sm text-kumo-text-secondary">
{parseError
? "Fix JSON errors to see preview"
: "Enter block JSON to see preview"}
</p>
</div>
)}
</div>
</div>
{/* Action log */}
<div className="flex h-48 shrink-0 flex-col border-t border-kumo-line">
<div className="flex h-8 items-center border-b border-kumo-line bg-kumo-tint/50 px-3">
<span className="text-[11px] font-medium uppercase tracking-wide text-kumo-text-secondary">
Action Log
</span>
<span className="ml-1.5 rounded-full bg-kumo-tint px-1.5 py-0.5 text-[10px] font-medium text-kumo-text-secondary">
{actionLog.length}
</span>
{actionLog.length > 0 && (
<button
type="button"
onClick={() => setActionLog([])}
className="ml-auto rounded-md p-1 text-kumo-text-secondary hover:bg-kumo-tint"
aria-label="Clear log"
>
<Trash size={12} />
</button>
)}
</div>
<div className="min-h-0 flex-1 overflow-auto p-2">
{actionLog.length === 0 ? (
<p className="p-2 text-xs text-kumo-text-secondary">
Interact with the preview to see actions logged here.
</p>
) : (
actionLog.map((entry) => (
<div
key={entry.id}
className="action-log-entry border-b border-kumo-line/50 px-2 py-1.5 last:border-b-0"
>
<div className="flex items-baseline gap-2">
<span className="shrink-0 text-kumo-text-secondary">
{entry.timestamp.toLocaleTimeString()}
</span>
<span className="rounded bg-kumo-tint px-1 py-0.5 text-[10px] font-semibold uppercase text-kumo-text-secondary">
{entry.interaction.type}
</span>
{"action_id" in entry.interaction && (
<span className="font-medium text-kumo-text">
{entry.interaction.action_id}
</span>
)}
</div>
{"values" in entry.interaction && (
<pre className="mt-1 text-[11px] text-kumo-text-secondary">
{JSON.stringify(entry.interaction.values, null, 2)}
</pre>
)}
{"value" in entry.interaction && entry.interaction.value !== undefined && (
<pre className="mt-1 text-[11px] text-kumo-text-secondary">
{JSON.stringify(entry.interaction.value)}
</pre>
)}
</div>
))
)}
<div ref={logEndRef} />
</div>
</div>
</div>
</div>
</div>
);
}

View File

@@ -0,0 +1,214 @@
import type { Block } from "@emdashcms/blocks";
interface BlockCatalogEntry {
type: Block["type"];
label: string;
description: string;
create: () => Block;
}
let counter = 0;
function nextId(prefix: string): string {
return `${prefix}_${++counter}`;
}
export const blockCatalog: BlockCatalogEntry[] = [
{
type: "header",
label: "Header",
description: "Page or section title",
create: () => ({
type: "header",
text: "New Header",
}),
},
{
type: "section",
label: "Section",
description: "Text paragraph with optional accessory",
create: () => ({
type: "section",
text: "Section text goes here. You can add an accessory element like a button.",
}),
},
{
type: "divider",
label: "Divider",
description: "Horizontal rule between blocks",
create: () => ({
type: "divider",
}),
},
{
type: "fields",
label: "Fields",
description: "Key-value pairs in a grid",
create: () => ({
type: "fields",
fields: [
{ label: "Label", value: "Value" },
{ label: "Another", value: "Value" },
],
}),
},
{
type: "stats",
label: "Stats",
description: "Metric cards with optional trends",
create: () => ({
type: "stats",
items: [
{ label: "Total", value: 100, trend: "up" as const },
{ label: "Active", value: 42 },
],
}),
},
{
type: "table",
label: "Table",
description: "Sortable data grid with pagination",
create: () => ({
type: "table",
columns: [
{ key: "name", label: "Name", sortable: true },
{ key: "status", label: "Status", format: "badge" as const },
],
rows: [
{ name: "Item 1", status: "active" },
{ name: "Item 2", status: "draft" },
],
page_action_id: nextId("page"),
}),
},
{
type: "form",
label: "Form",
description: "Input fields with submit button",
create: () => ({
type: "form",
fields: [
{
type: "text_input" as const,
action_id: nextId("field"),
label: "Text Field",
placeholder: "Enter text...",
},
],
submit: { label: "Submit", action_id: nextId("submit") },
}),
},
{
type: "actions",
label: "Actions",
description: "Row of buttons",
create: () => ({
type: "actions",
elements: [
{
type: "button" as const,
action_id: nextId("btn"),
label: "Click Me",
style: "primary" as const,
},
],
}),
},
{
type: "image",
label: "Image",
description: "Image with alt text and optional title",
create: () => ({
type: "image",
url: "https://images.unsplash.com/photo-1618005182384-a83a8bd57fbe?w=600&h=300&fit=crop",
alt: "Placeholder image",
title: "Image title",
}),
},
{
type: "context",
label: "Context",
description: "Muted supplementary text",
create: () => ({
type: "context",
text: "Supplementary information goes here.",
}),
},
{
type: "banner",
label: "Banner",
description: "Info, warning, or error message",
create: () => ({
type: "banner" as const,
title: "Notice",
description: "This is an informational banner message.",
variant: "default" as const,
}),
},
{
type: "columns",
label: "Columns",
description: "Multi-column layout",
create: () => ({
type: "columns",
columns: [
[{ type: "section" as const, text: "Left column content" }],
[{ type: "section" as const, text: "Right column content" }],
],
}),
},
{
type: "meter",
label: "Meter",
description: "Progress/quota meter bar",
create: () => ({
type: "meter" as const,
label: "Storage used",
value: 65,
custom_value: "6.5 GB / 10 GB",
}),
},
{
type: "code",
label: "Code",
description: "Syntax-highlighted code block",
create: () => ({
type: "code" as const,
code: 'const greeting = "Hello, World!";\nconsole.log(greeting);',
language: "ts" as const,
}),
},
{
type: "chart",
label: "Chart",
description: "Line, bar, or pie chart (ECharts)",
create: () => {
const now = Date.now();
const hour = 3_600_000;
return {
type: "chart" as const,
config: {
chart_type: "timeseries" as const,
series: [
{
name: "Requests",
data: Array.from({ length: 24 }, (_, i) => [
now - (23 - i) * hour,
Math.floor(200 + Math.random() * 300),
]),
},
{
name: "Errors",
data: Array.from({ length: 24 }, (_, i) => [
now - (23 - i) * hour,
Math.floor(Math.random() * 20),
]),
},
],
x_axis_name: "Time",
y_axis_name: "Count",
gradient: true,
},
};
},
},
];

View File

@@ -0,0 +1,11 @@
import { StrictMode } from "react";
import { createRoot } from "react-dom/client";
import "./styles.css";
import { Playground } from "./Playground";
createRoot(document.getElementById("root")!).render(
<StrictMode>
<Playground />
</StrictMode>,
);

View File

@@ -0,0 +1,47 @@
@import "tailwindcss";
@import "@cloudflare/kumo/styles/tailwind";
/* Scan kumo components for utility classes */
@source "../../node_modules/@cloudflare/kumo/dist";
/* Scan blocks source for utility classes */
@source "../../src";
:root {
color-scheme: light dark;
}
:root[data-theme="light"] {
color-scheme: light;
}
:root[data-theme="dark"] {
color-scheme: dark;
}
body {
margin: 0;
font-family:
system-ui,
-apple-system,
BlinkMacSystemFont,
"Segoe UI",
sans-serif;
background-color: light-dark(#f5f5f5, #111);
}
/* Editor textarea */
.editor-textarea {
font-family: "SF Mono", "Fira Code", "JetBrains Mono", ui-monospace, monospace;
font-size: 13px;
line-height: 1.5;
tab-size: 2;
resize: none;
}
/* Action log entries */
.action-log-entry {
font-family: "SF Mono", "Fira Code", "JetBrains Mono", ui-monospace, monospace;
font-size: 12px;
line-height: 1.4;
}

View File

@@ -0,0 +1,560 @@
import type { Block, ChartSeries } from "@emdashcms/blocks";
export interface Template {
name: string;
description: string;
blocks: Block[];
}
// ── Sample data generators ───────────────────────────────────────────────────
const HOUR = 3_600_000;
function generateTrafficSeries(): ChartSeries[] {
const now = Date.now();
return [
{
name: "Page Views",
data: Array.from({ length: 24 }, (_, i) => [
now - (23 - i) * HOUR,
Math.floor(400 + Math.sin(i / 4) * 200 + Math.random() * 80),
]),
color: "#086FFF",
},
{
name: "Unique Visitors",
data: Array.from({ length: 24 }, (_, i) => [
now - (23 - i) * HOUR,
Math.floor(150 + Math.sin(i / 4) * 80 + Math.random() * 40),
]),
color: "#CF7EE9",
},
];
}
function generateErrorSeries(): ChartSeries[] {
const now = Date.now();
return [
{
name: "4xx",
data: Array.from({ length: 12 }, (_, i) => [
now - (11 - i) * HOUR * 2,
Math.floor(Math.random() * 15),
]),
color: "#F8A054",
},
{
name: "5xx",
data: Array.from({ length: 12 }, (_, i) => [
now - (11 - i) * HOUR * 2,
Math.floor(Math.random() * 5),
]),
color: "#FC574A",
},
];
}
export const templates: Template[] = [
{
name: "Plugin Settings",
description: "Form with conditional fields and text inputs",
blocks: [
{
type: "header",
text: "SEO Plugin Settings",
block_id: "settings-header",
},
{
type: "section",
text: "Configure how your site appears in search results. Enable auto-generation to let the plugin create meta tags from your content.",
},
{ type: "divider" },
{
type: "form",
block_id: "seo-settings",
fields: [
{
type: "text_input",
action_id: "site_title",
label: "Site Title",
placeholder: "My Awesome Site",
initial_value: "EmDash CMS",
},
{
type: "text_input",
action_id: "meta_description",
label: "Default Meta Description",
placeholder: "A brief description of your site...",
multiline: true,
},
{
type: "toggle",
action_id: "auto_generate",
label: "Auto-generate meta tags",
description: "Generate meta descriptions from content when not manually set",
initial_value: true,
},
{
type: "number_input",
action_id: "max_length",
label: "Max description length",
initial_value: 160,
min: 50,
max: 300,
condition: { field: "auto_generate", eq: true },
},
{
type: "select",
action_id: "ai_model",
label: "AI Model",
options: [
{ label: "GPT-4o Mini", value: "gpt-4o-mini" },
{ label: "Claude Haiku", value: "claude-haiku" },
{ label: "None (extractive)", value: "none" },
],
initial_value: "none",
condition: { field: "auto_generate", eq: true },
},
{
type: "radio",
action_id: "default_status",
label: "Default publish status",
options: [
{ label: "Draft", value: "draft" },
{ label: "Published", value: "published" },
{ label: "Scheduled", value: "scheduled" },
],
initial_value: "draft",
},
{
type: "checkbox",
action_id: "collections",
label: "Apply to collections",
options: [
{ label: "Posts", value: "posts" },
{ label: "Pages", value: "pages" },
{ label: "Products", value: "products" },
],
initial_value: ["posts", "pages"],
},
{
type: "secret_input",
action_id: "api_key",
label: "API Key",
placeholder: "sk-...",
condition: { field: "ai_model", neq: "none" },
},
{
type: "date_input",
action_id: "embargo_date",
label: "Embargo date",
placeholder: "Select a date",
},
{
type: "combobox",
action_id: "timezone",
label: "Timezone",
placeholder: "Search timezones...",
options: [
{ label: "UTC", value: "UTC" },
{ label: "US/Eastern", value: "US/Eastern" },
{ label: "US/Central", value: "US/Central" },
{ label: "US/Mountain", value: "US/Mountain" },
{ label: "US/Pacific", value: "US/Pacific" },
{ label: "Europe/London", value: "Europe/London" },
{ label: "Europe/Paris", value: "Europe/Paris" },
{ label: "Europe/Berlin", value: "Europe/Berlin" },
{ label: "Asia/Tokyo", value: "Asia/Tokyo" },
{ label: "Asia/Shanghai", value: "Asia/Shanghai" },
{ label: "Australia/Sydney", value: "Australia/Sydney" },
],
initial_value: "UTC",
},
],
submit: { label: "Save Settings", action_id: "save_seo_settings" },
},
],
},
{
name: "Analytics Dashboard",
description: "Charts, stats, and data table",
blocks: [
{
type: "header",
text: "Content Analytics",
},
{
type: "stats",
items: [
{ label: "Total Views", value: "12,847", trend: "up", description: "+14% vs last week" },
{
label: "Unique Visitors",
value: "3,291",
trend: "up",
description: "+8% vs last week",
},
{
label: "Bounce Rate",
value: "34.2%",
trend: "down",
description: "-2.1% vs last week",
},
{ label: "Avg. Time on Page", value: "2m 48s", trend: "neutral" },
],
},
{
type: "chart",
block_id: "traffic-chart",
config: {
chart_type: "timeseries",
series: generateTrafficSeries(),
x_axis_name: "Time",
y_axis_name: "Requests",
gradient: true,
},
},
{
type: "columns",
columns: [
[
{
type: "chart",
block_id: "content-breakdown",
config: {
chart_type: "custom",
options: {
series: [
{
type: "pie",
radius: ["40%", "70%"],
data: [
{ value: 42, name: "Published" },
{ value: 7, name: "Draft" },
{ value: 3, name: "Scheduled" },
{ value: 2, name: "Archived" },
],
},
],
},
height: 250,
},
},
],
[
{
type: "chart",
block_id: "errors-chart",
config: {
chart_type: "timeseries",
series: generateErrorSeries(),
y_axis_name: "Errors",
style: "bar",
height: 250,
},
},
],
],
},
{ type: "divider" },
{
type: "table",
block_id: "content-table",
columns: [
{ key: "title", label: "Title", sortable: true },
{ key: "status", label: "Status", format: "badge" },
{ key: "views", label: "Views", format: "number", sortable: true },
{ key: "updated", label: "Last Updated", format: "relative_time", sortable: true },
],
rows: [
{
title: "Getting Started with EmDash",
status: "published",
views: 4521,
updated: new Date(Date.now() - 2 * 60 * 60 * 1000).toISOString(),
},
{
title: "Advanced Content Modeling",
status: "published",
views: 2103,
updated: new Date(Date.now() - 24 * 60 * 60 * 1000).toISOString(),
},
{
title: "Plugin Development Guide",
status: "draft",
views: 891,
updated: new Date(Date.now() - 3 * 24 * 60 * 60 * 1000).toISOString(),
},
{
title: "Deployment to Cloudflare",
status: "published",
views: 3187,
updated: new Date(Date.now() - 7 * 24 * 60 * 60 * 1000).toISOString(),
},
{
title: "Media Management",
status: "scheduled",
views: 0,
updated: new Date(Date.now() - 30 * 60 * 1000).toISOString(),
},
],
page_action_id: "load_more_content",
next_cursor: "eyJpZCI6IjUifQ",
},
],
},
{
name: "Dashboard Widget",
description: "Compact stats with context line",
blocks: [
{
type: "stats",
items: [
{ label: "Published", value: 42 },
{ label: "Drafts", value: 7 },
{ label: "Scheduled", value: 3 },
],
},
{
type: "context",
text: "Last published 2 hours ago \u2022 Next scheduled in 4 hours",
},
],
},
{
name: "Admin Page",
description: "Two-column layout with sidebar and main content",
blocks: [
{
type: "header",
text: "Site Configuration",
},
{
type: "columns",
columns: [
[
{
type: "section",
text: "General settings for your site. These values are used across all pages unless overridden at the content level.",
},
{
type: "form",
block_id: "general-settings",
fields: [
{
type: "text_input",
action_id: "site_name",
label: "Site Name",
initial_value: "My Site",
},
{
type: "text_input",
action_id: "tagline",
label: "Tagline",
placeholder: "A short description of your site",
},
{
type: "select",
action_id: "timezone",
label: "Timezone",
options: [
{ label: "UTC", value: "UTC" },
{ label: "US/Eastern", value: "US/Eastern" },
{ label: "US/Pacific", value: "US/Pacific" },
{ label: "Europe/London", value: "Europe/London" },
],
initial_value: "UTC",
},
],
submit: { label: "Save", action_id: "save_general" },
},
],
[
{
type: "fields",
fields: [
{ label: "Plan", value: "Pro" },
{ label: "Storage", value: "2.4 GB / 10 GB" },
{ label: "API Calls", value: "12,847 / 100,000" },
{ label: "Next Billing", value: "Mar 15, 2026" },
],
},
{ type: "divider" },
{
type: "actions",
elements: [
{
type: "button",
action_id: "export_data",
label: "Export Data",
style: "secondary",
},
{
type: "button",
action_id: "danger_zone",
label: "Delete Site",
style: "danger",
confirm: {
title: "Delete Site?",
text: "This action cannot be undone. All content and media will be permanently deleted.",
confirm: "Delete Everything",
deny: "Cancel",
style: "danger",
},
},
],
},
],
],
},
],
},
{
name: "All Blocks",
description: "Showcase of every block type",
blocks: [
{ type: "header", text: "Block Kit Showcase" },
{
type: "section",
text: "This template demonstrates every block type available in the Block Kit. Each block maps to a Kumo component.",
accessory: {
type: "button",
action_id: "learn_more",
label: "Learn More",
style: "primary",
},
},
{
type: "banner",
title: "Information",
description: "This is a default informational banner.",
variant: "default",
},
{
type: "banner",
title: "Warning",
description: "Something requires your attention.",
variant: "alert",
},
{
type: "banner",
title: "Error",
description: "An error occurred while processing your request.",
variant: "error",
},
{ type: "divider" },
{
type: "fields",
fields: [
{ label: "Version", value: "0.1.0" },
{ label: "Blocks", value: "15 types" },
{ label: "Elements", value: "10 types" },
{ label: "License", value: "MIT" },
],
},
{
type: "stats",
items: [
{ label: "Components", value: 26, trend: "up" },
{ label: "Tests", value: 60, trend: "up" },
{ label: "Bundle Size", value: "6.7 KB", description: "gzipped" },
],
},
{
type: "meter",
label: "Storage",
value: 65,
custom_value: "6.5 GB / 10 GB",
},
{ type: "divider" },
{
type: "chart",
block_id: "demo-timeseries",
config: {
chart_type: "timeseries",
series: generateTrafficSeries(),
x_axis_name: "Time",
y_axis_name: "Views",
gradient: true,
},
},
{
type: "chart",
block_id: "demo-pie",
config: {
chart_type: "custom",
options: {
series: [
{
type: "pie",
radius: ["40%", "70%"],
data: [
{ value: 335, name: "Published" },
{ value: 234, name: "Draft" },
{ value: 120, name: "Scheduled" },
{ value: 48, name: "Archived" },
],
},
],
},
height: 280,
},
},
{ type: "divider" },
{
type: "image",
url: "https://images.unsplash.com/photo-1618005182384-a83a8bd57fbe?w=800&h=400&fit=crop",
alt: "Abstract colorful gradient",
title: "Image blocks support URLs, alt text, and optional titles",
},
{
type: "code",
code: 'import { blocks } from "@emdashcms/blocks";\n\nconst page = [\n\tblocks.header("Hello"),\n\tblocks.section("Welcome to EmDash."),\n];',
language: "ts",
},
{ type: "divider" },
{
type: "table",
block_id: "demo-table",
columns: [
{ key: "block", label: "Block Type" },
{ key: "purpose", label: "Purpose" },
{ key: "status", label: "Status", format: "badge" },
],
rows: [
{ block: "header", purpose: "Page or section title", status: "stable" },
{ block: "section", purpose: "Text with optional accessory", status: "stable" },
{ block: "form", purpose: "Input fields with submit", status: "stable" },
{ block: "table", purpose: "Sortable data grid", status: "stable" },
{ block: "chart", purpose: "Timeseries, bar, pie charts", status: "stable" },
{ block: "columns", purpose: "Multi-column layout", status: "stable" },
],
page_action_id: "demo_page",
},
{ type: "divider" },
{
type: "actions",
elements: [
{ type: "button", action_id: "primary_action", label: "Primary", style: "primary" },
{ type: "button", action_id: "secondary_action", label: "Secondary", style: "secondary" },
{
type: "button",
action_id: "danger_action",
label: "Danger",
style: "danger",
confirm: {
title: "Are you sure?",
text: "This is a destructive action demo.",
confirm: "Yes, proceed",
deny: "Cancel",
style: "danger",
},
},
],
},
{
type: "context",
text: "This is a context block \u2014 used for supplementary information, timestamps, or footnotes.",
},
],
},
];

View File

@@ -0,0 +1,54 @@
import { useCallback, useRef, useState } from "react";
interface UseResizableOptions {
/** Initial width in pixels */
initial: number;
/** Minimum width */
min: number;
/** Maximum width */
max: number;
}
interface UseResizableReturn {
width: number;
isDragging: boolean;
handleMouseDown: (e: React.MouseEvent) => void;
}
export function useResizable({ initial, min, max }: UseResizableOptions): UseResizableReturn {
const [width, setWidth] = useState(initial);
const [isDragging, setIsDragging] = useState(false);
const startX = useRef(0);
const startWidth = useRef(0);
const handleMouseDown = useCallback(
(e: React.MouseEvent) => {
e.preventDefault();
startX.current = e.clientX;
startWidth.current = width;
setIsDragging(true);
function onMouseMove(moveEvent: MouseEvent) {
const delta = moveEvent.clientX - startX.current;
const newWidth = Math.min(max, Math.max(min, startWidth.current + delta));
setWidth(newWidth);
}
function onMouseUp() {
setIsDragging(false);
document.removeEventListener("mousemove", onMouseMove);
document.removeEventListener("mouseup", onMouseUp);
document.body.style.cursor = "";
document.body.style.userSelect = "";
}
document.body.style.cursor = "col-resize";
document.body.style.userSelect = "none";
document.addEventListener("mousemove", onMouseMove);
document.addEventListener("mouseup", onMouseUp);
},
[width, min, max],
);
return { width, isDragging, handleMouseDown };
}

View File

@@ -0,0 +1,14 @@
{
"compilerOptions": {
"target": "ES2022",
"module": "preserve",
"moduleResolution": "bundler",
"jsx": "react-jsx",
"strict": true,
"noUncheckedIndexedAccess": true,
"lib": ["ES2023", "DOM", "DOM.Iterable"],
"skipLibCheck": true,
"verbatimModuleSyntax": true
},
"include": ["src/**/*"]
}

View File

@@ -0,0 +1,13 @@
import tailwindcss from "@tailwindcss/vite";
import react from "@vitejs/plugin-react";
import { defineConfig } from "vite";
export default defineConfig({
plugins: [react(), tailwindcss()],
resolve: {
alias: {
// Resolve @emdashcms/blocks from source for HMR
"@emdashcms/blocks": new URL("../src/index.ts", import.meta.url).pathname,
},
},
});

View File

@@ -0,0 +1,7 @@
{
"name": "emdash-blocks",
"compatibility_date": "2026-02-25",
"assets": {
"directory": "./dist",
},
}