Skip to main content

Dashboard Integration Example

This example shows how to integrate Supernal Coding with a web dashboard to display real-time project status and synchronization information.

Overview

We'll create a dashboard that displays:

  • Requirements status
  • Kanban board overview
  • Synchronization status
  • Real-time updates

Backend Setup

1. Express Server

// server.js
const express = require('express');
const { createAPI, createHTTPMiddleware } = require('supernal-code/lib/api');
const path = require('path');

async function createDashboardServer() {
const app = express();
const api = await createAPI({
projectRoot: process.cwd(),
});

// Middleware
app.use(express.json());
app.use(express.static(path.join(__dirname, 'public')));
app.use('/api', createHTTPMiddleware(api));

// Requirements endpoints
app.get('/api/requirements', async (req, res) => {
try {
const requirements = await req.supernalCoding.listRequirements(req.query);
req.supernalCoding.sendJSON(requirements);
} catch (error) {
req.supernalCoding.sendError(error);
}
});

app.get('/api/requirements/stats', async (req, res) => {
try {
const all = await req.supernalCoding.listRequirements();

const stats = {
total: all.length,
byStatus: {},
byPriority: {},
byCategory: {},
};

all.forEach((req) => {
stats.byStatus[req.status] = (stats.byStatus[req.status] || 0) + 1;
stats.byPriority[req.priority] =
(stats.byPriority[req.priority] || 0) + 1;
stats.byCategory[req.category] =
(stats.byCategory[req.category] || 0) + 1;
});

req.supernalCoding.sendJSON(stats);
} catch (error) {
req.supernalCoding.sendError(error);
}
});

// Kanban endpoints
app.get('/api/kanban', async (req, res) => {
try {
const boards = await req.supernalCoding.getAllKanbanBoards();
req.supernalCoding.sendJSON(boards);
} catch (error) {
req.supernalCoding.sendError(error);
}
});

app.get('/api/kanban/stats', async (req, res) => {
try {
const boards = await req.supernalCoding.getAllKanbanBoards();

const stats = {};
Object.entries(boards).forEach(([board, tasks]) => {
stats[board] = tasks.length;
});

req.supernalCoding.sendJSON(stats);
} catch (error) {
req.supernalCoding.sendError(error);
}
});

// Sync endpoints
app.get('/api/sync/status', async (req, res) => {
try {
const status = await req.supernalCoding.getSyncStatus();
req.supernalCoding.sendJSON(status);
} catch (error) {
req.supernalCoding.sendError(error);
}
});

app.post('/api/sync/push', async (req, res) => {
try {
const result = await req.supernalCoding.pushChanges(
req.body.force || false
);
req.supernalCoding.sendJSON(result);
} catch (error) {
req.supernalCoding.sendError(error);
}
});

app.post('/api/sync/pull', async (req, res) => {
try {
const result = await req.supernalCoding.pullChanges(
req.body.force || false
);
req.supernalCoding.sendJSON(result);
} catch (error) {
req.supernalCoding.sendError(error);
}
});

return { app, api };
}

// Start server
createDashboardServer().then(({ app, api }) => {
const PORT = process.env.PORT || 3000;

app.listen(PORT, () => {
console.log(`Dashboard server running on http://localhost:${PORT}`);
});

// Cleanup on shutdown
process.on('SIGINT', async () => {
console.log('Shutting down...');
await api.cleanup();
process.exit(0);
});
});

Frontend Dashboard

2. HTML Structure

<!-- public/dashboard.html -->
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8" />
<meta name="viewport" content="width=device-width, initial-scale=1.0" />
<title>Supernal Coding Dashboard</title>
<link rel="stylesheet" href="dashboard.css" />
</head>
<body>
<div class="dashboard">
<header>
<h1>Supernal Coding Dashboard</h1>
<div class="sync-indicator" id="syncIndicator">
<span class="status-dot"></span>
<span class="status-text">Not Configured</span>
</div>
</header>

<div class="dashboard-grid">
<!-- Requirements Stats -->
<section class="card">
<h2>Requirements</h2>
<div id="requirementsStats" class="stats-grid">
<div class="stat">
<div class="stat-value" id="totalRequirements">-</div>
<div class="stat-label">Total</div>
</div>
<div class="stat">
<div class="stat-value" id="criticalRequirements">-</div>
<div class="stat-label">Critical</div>
</div>
<div class="stat">
<div class="stat-value" id="inProgressRequirements">-</div>
<div class="stat-label">In Progress</div>
</div>
</div>
</section>

<!-- Kanban Stats -->
<section class="card">
<h2>Kanban Boards</h2>
<div id="kanbanStats" class="kanban-boards">
<!-- Dynamically populated -->
</div>
</section>

<!-- Sync Status -->
<section class="card">
<h2>Synchronization</h2>
<div id="syncStatus" class="sync-status">
<div class="sync-info">
<span class="label">Status:</span>
<span id="syncEnabled">-</span>
</div>
<div class="sync-info">
<span class="label">Last Sync:</span>
<span id="lastSync">-</span>
</div>
<div class="sync-info">
<span class="label">Pending:</span>
<span id="pendingChanges">-</span>
</div>
<div class="sync-actions">
<button id="pushBtn" class="btn">Push Changes</button>
<button id="pullBtn" class="btn">Pull Updates</button>
<button id="syncBtn" class="btn btn-primary">Sync Now</button>
</div>
</div>
</section>

<!-- Recent Activity -->
<section class="card full-width">
<h2>Recent Activity</h2>
<div id="recentActivity" class="activity-list">
<!-- Dynamically populated -->
</div>
</section>
</div>
</div>

<script src="dashboard.js"></script>
</body>
</html>

3. JavaScript Logic

// public/dashboard.js
class SupernalDashboard {
constructor() {
this.refreshInterval = 30000; // 30 seconds
this.init();
}

async init() {
await this.loadAll();
this.setupEventListeners();
this.startAutoRefresh();
}

async loadAll() {
await Promise.all([
this.loadRequirementsStats(),
this.loadKanbanStats(),
this.loadSyncStatus(),
]);
}

async loadRequirementsStats() {
try {
const response = await fetch('/api/requirements/stats');
const data = await response.json();

if (data.success) {
const stats = data.data;
document.getElementById('totalRequirements').textContent = stats.total;
document.getElementById('criticalRequirements').textContent =
stats.byPriority.Critical || 0;
document.getElementById('inProgressRequirements').textContent =
stats.byStatus['In Progress'] || 0;
}
} catch (error) {
console.error('Failed to load requirements stats:', error);
}
}

async loadKanbanStats() {
try {
const response = await fetch('/api/kanban/stats');
const data = await response.json();

if (data.success) {
const stats = data.data;
const container = document.getElementById('kanbanStats');

container.innerHTML = Object.entries(stats)
.map(
([board, count]) => `
<div class="kanban-board">
<div class="board-name">${board}</div>
<div class="board-count">${count}</div>
</div>
`
)
.join('');
}
} catch (error) {
console.error('Failed to load kanban stats:', error);
}
}

async loadSyncStatus() {
try {
const response = await fetch('/api/sync/status');
const data = await response.json();

if (data.success) {
const status = data.data;

// Update sync indicator
const indicator = document.getElementById('syncIndicator');
const statusDot = indicator.querySelector('.status-dot');
const statusText = indicator.querySelector('.status-text');

if (status.enabled) {
statusDot.className = 'status-dot active';
statusText.textContent = 'Sync Active';
} else {
statusDot.className = 'status-dot';
statusText.textContent = 'Sync Disabled';
}

// Update sync details
document.getElementById('syncEnabled').textContent = status.enabled
? 'Enabled'
: 'Disabled';
document.getElementById('lastSync').textContent = status.lastSync
? new Date(status.lastSync).toLocaleString()
: 'Never';
document.getElementById('pendingChanges').textContent =
status.state?.pendingChanges?.length || 0;

// Enable/disable buttons
const pushBtn = document.getElementById('pushBtn');
const pullBtn = document.getElementById('pullBtn');
const syncBtn = document.getElementById('syncBtn');

[pushBtn, pullBtn, syncBtn].forEach((btn) => {
btn.disabled = !status.enabled;
});
}
} catch (error) {
console.error('Failed to load sync status:', error);
}
}

setupEventListeners() {
document
.getElementById('pushBtn')
.addEventListener('click', () => this.handlePush());
document
.getElementById('pullBtn')
.addEventListener('click', () => this.handlePull());
document
.getElementById('syncBtn')
.addEventListener('click', () => this.handleSync());
}

async handlePush() {
try {
const response = await fetch('/api/sync/push', {
method: 'POST',
headers: { 'Content-Type': 'application/json' },
body: JSON.stringify({ force: false }),
});

const data = await response.json();

if (data.success) {
alert(`Pushed ${data.data.pushed} changes successfully`);
await this.loadSyncStatus();
}
} catch (error) {
alert('Push failed: ' + error.message);
}
}

async handlePull() {
try {
const response = await fetch('/api/sync/pull', {
method: 'POST',
headers: { 'Content-Type': 'application/json' },
body: JSON.stringify({ force: false }),
});

const data = await response.json();

if (data.success) {
alert(`Pulled ${data.data.pulled} changes successfully`);
await this.loadAll();
}
} catch (error) {
alert('Pull failed: ' + error.message);
}
}

async handleSync() {
try {
// Pull first
await this.handlePull();
// Then push
await this.handlePush();
} catch (error) {
alert('Sync failed: ' + error.message);
}
}

startAutoRefresh() {
setInterval(() => {
this.loadAll();
}, this.refreshInterval);
}
}

// Initialize dashboard when DOM is ready
document.addEventListener('DOMContentLoaded', () => {
new SupernalDashboard();
});

4. CSS Styling

/* public/dashboard.css */
* {
margin: 0;
padding: 0;
box-sizing: border-box;
}

body {
font-family:
-apple-system, BlinkMacSystemFont, 'Segoe UI', Roboto, Oxygen, Ubuntu,
Cantarell, sans-serif;
background: #f5f7fa;
color: #2c3e50;
}

.dashboard {
max-width: 1400px;
margin: 0 auto;
padding: 20px;
}

header {
display: flex;
justify-content: space-between;
align-items: center;
padding: 20px;
background: white;
border-radius: 8px;
margin-bottom: 20px;
box-shadow: 0 2px 4px rgba(0, 0, 0, 0.1);
}

h1 {
font-size: 24px;
color: #2c3e50;
}

.sync-indicator {
display: flex;
align-items: center;
gap: 8px;
}

.status-dot {
width: 12px;
height: 12px;
border-radius: 50%;
background: #95a5a6;
}

.status-dot.active {
background: #27ae60;
animation: pulse 2s infinite;
}

@keyframes pulse {
0%,
100% {
opacity: 1;
}
50% {
opacity: 0.5;
}
}

.dashboard-grid {
display: grid;
grid-template-columns: repeat(auto-fit, minmax(300px, 1fr));
gap: 20px;
}

.card {
background: white;
border-radius: 8px;
padding: 20px;
box-shadow: 0 2px 4px rgba(0, 0, 0, 0.1);
}

.card.full-width {
grid-column: 1 / -1;
}

.card h2 {
font-size: 18px;
margin-bottom: 16px;
color: #2c3e50;
}

.stats-grid {
display: grid;
grid-template-columns: repeat(3, 1fr);
gap: 16px;
}

.stat {
text-align: center;
}

.stat-value {
font-size: 32px;
font-weight: bold;
color: #3498db;
}

.stat-label {
font-size: 14px;
color: #7f8c8d;
margin-top: 4px;
}

.kanban-boards {
display: flex;
flex-wrap: wrap;
gap: 12px;
}

.kanban-board {
flex: 1;
min-width: 80px;
text-align: center;
padding: 12px;
background: #ecf0f1;
border-radius: 4px;
}

.board-name {
font-size: 12px;
color: #7f8c8d;
margin-bottom: 8px;
}

.board-count {
font-size: 24px;
font-weight: bold;
color: #2c3e50;
}

.sync-status {
display: flex;
flex-direction: column;
gap: 12px;
}

.sync-info {
display: flex;
justify-content: space-between;
padding: 8px 0;
border-bottom: 1px solid #ecf0f1;
}

.sync-info .label {
font-weight: 600;
color: #7f8c8d;
}

.sync-actions {
display: flex;
gap: 8px;
margin-top: 12px;
}

.btn {
flex: 1;
padding: 10px 16px;
border: 1px solid #3498db;
background: white;
color: #3498db;
border-radius: 4px;
cursor: pointer;
font-size: 14px;
transition: all 0.2s;
}

.btn:hover {
background: #3498db;
color: white;
}

.btn:disabled {
opacity: 0.5;
cursor: not-allowed;
}

.btn-primary {
background: #3498db;
color: white;
}

.btn-primary:hover {
background: #2980b9;
}

Usage

Start the Server

node server.js

Access the Dashboard

Open browser to http://localhost:3000/dashboard.html

Features

  • Real-time Stats: Requirements and kanban statistics
  • Sync Control: Push/pull/sync buttons
  • Auto-refresh: Updates every 30 seconds
  • Visual Indicators: Sync status indicator

Integration with Existing Dashboard

If you have an existing dashboard system:

// Integrate into existing Express app
const { createAPI, createHTTPMiddleware } = require('supernal-code/lib/api');

async function addSupernalCodingAPI(app) {
const api = await createAPI();
app.use('/api/supernal', createHTTPMiddleware(api));

// Your existing routes continue to work
// app.get('/api/other-stuff', ...);

return api;
}

Next Steps