The user wants a dynamic data visualization dashboard using D3.js and SvelteKit with live updates. Since this is a SvelteKit project (not vanilla HTML), I'll create a complete SvelteKit project structure with multiple components.
Let me plan this out:
-
Project Structure:
src/routes/+page.svelte - Main dashboard page
src/lib/components/ - Reusable chart components
src/lib/stores/ - Svelte stores for state management
src/lib/utils/ - Utility functions for data generation
-
Features:
- Real-time data updates using setInterval
- Multiple chart types (line chart, bar chart, pie chart, area chart)
- Animated transitions
- Responsive design
- Interactive tooltips
- Dark theme with good contrast
- Particle background for visual appeal
-
D3.js Integration:
- Use D3 for scales, shapes, and transitions
- Svelte for DOM rendering and reactivity
- Smooth animations on data updates
-
Visual Design:
- Modern dark theme with cyan/teal accents
- Glowing effects
- Grid background
- Floating particles
Let me create this comprehensive dashboard:
Dynamic Data Visualization Dashboard with D3.js & SvelteKit
This is a comprehensive real-time dashboard with multiple chart types, live data updates, and smooth D3.js animations.
Project Structure
src/
├── routes/
│ └── +page.svelte # Main dashboard page
├── lib/
│ ├── components/
│ │ ├── LineChart.svelte # Real-time line chart
│ │ ├── BarChart.svelte # Animated bar chart
│ │ ├── PieChart.svelte # Donut chart
│ │ ├── AreaChart.svelte # Area chart with gradient
│ │ └── StatsCard.svelte # Metric cards
│ ├── stores/
│ │ └── dataStore.js # Svelte stores for data
│ └── utils/
│ └── dataGenerator.js # Mock data generation
└── app.html
Installation
npm create svelte@latest dashboard
cd dashboard
npm install d3
npm run dev
File: src/app.html
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8" />
<link rel="icon" href="%sveltekit.assets%/favicon.png" />
<meta name="viewport" content="width=device-width, initial-scale=1" />
%sveltekit.head%
</head>
<body data-sveltekit-preload-data="hover" data-theme="dark">
<div style="display: contents">%sveltekit.body%</div>
</body>
</html>
<style>
:global(*, *::before, *::after) {
box-sizing: border-box;
margin: 0;
padding: 0;
}
:global(body) {
font-family: 'Segoe UI', system-ui, -apple-system, sans-serif;
background: #0a0e17;
color: #e0e6ed;
min-height: 100vh;
overflow-x: hidden;
}
</style>
File: src/lib/utils/dataGenerator.js
// Generate random data for visualizations
export function generateTimeSeriesData(points = 24) {
const now = new Date();
return Array.from({ length: points }, (_, i) => ({
timestamp: new Date(now - (points - i - 1) * 3600000),
value: Math.random() * 100 + 50,
id: i
}));
}
export function generateCategoryData(categories = ['Tech', 'Finance', 'Health', 'Energy', 'Consumer']) {
return categories.map(name => ({
name,
value: Math.floor(Math.random() * 500) + 100,
change: (Math.random() - 0.5) * 20
}));
}
export function generatePieData() {
return [
{ label: 'Desktop', value: 45 + Math.random() * 10, color: '#00d4ff' },
{ label: 'Mobile', value: 30 + Math.random() * 10, color: '#00ff88' },
{ label: 'Tablet', value: 15 + Math.random() * 5, color: '#ff6b6b' },
{ label: 'Other', value: 5 + Math.random() * 5, color: '#ffd93d' }
];
}
export function generateMetrics() {
return {
revenue: { value: 284750, change: 12.5, prefix: '$' },
users: { value: 48291, change: -3.2, suffix: '' },
conversion: { value: 4.82, change: 8.7, suffix: '%' },
uptime: { value: 99.98, change: 0.02, suffix: '%' }
};
}
export function updateLastPoint(data) {
const updated = [...data];
const lastIdx = updated.length - 1;
updated[lastIdx] = {
...updated[lastIdx],
value: Math.max(20, Math.min(180, updated[lastIdx].value + (Math.random() - 0.5) * 30))
};
return updated;
}
export function addNewPoint(data) {
const updated = [...data.slice(1)];
const lastTime = data[data.length - 1].timestamp;
updated.push({
timestamp: new Date(lastTime.getTime() + 3600000),
value: Math.random() * 100 + 50,
id: Date.now()
});
return updated;
}
File: src/lib/stores/dataStore.js
import { writable, derived } from 'svelte/store';
import { generateTimeSeriesData, generateCategoryData, generatePieData, generateMetrics } from '../utils/dataGenerator.js';
// Main data stores with live updates
export const timeSeriesData = writable(generateTimeSeriesData(24));
export const categoryData = writable(generateCategoryData());
export const pieData = writable(generatePieData());
export const metrics = writable(generateMetrics());
export const isLoading = writable(false);
export const updateInterval = writable(2000);
// Derived stores for computed values
export const maxValue = derived(timeSeriesData, $data => Math.max(...$data.map(d => d.value)));
export const totalValue = derived(categoryData, $data => $data.reduce((sum, d) => sum + d.value, 0));
File: src/lib/components/LineChart.svelte
<script>
import { onMount, onDestroy, tick } from 'svelte';
import * as d3 from 'd3';
import { createEventDispatcher } from 'svelte';
export let data = [];
export let width = 600;
export let height = 300;
export let animate = true;
const dispatch = createEventDispatcher();
let svgElement;
let tooltipElement;
let pathElement;
let dotsContainer;
const margin = { top: 20, right: 30, bottom: 40, left: 50 };
const innerWidth = width - margin.left - margin.right;
const innerHeight = height - margin.top - margin.bottom;
$: xScale = d3.scaleTime()
.domain(d3.extent(data, d => d.timestamp))
.range([0, innerWidth]);
$: yScale = d3.scaleLinear()
.domain([0, d3.max(data, d => d.value) * 1.1])
.range([innerHeight, 0]);
$: line = d3.line()
.x(d => xScale(d.timestamp))
.y(d => yScale(d.value))
.curve(d3.curveMonotoneX);
$: area = d3.area()
.x(d => xScale(d.timestamp))
.y0(innerHeight)
.y1(d => yScale(d.value))
.curve(d3.curveMonotoneX);
function handleMouseOver(event, d) {
const [x, y] = d3.pointer(event);
dispatch('hover', { data: d, x: event.clientX, y: event.clientY });
d3.select(tooltipElement)
.style('opacity', 1)
.style('left', `${event.offsetX + 10}px`)
.style('top', `${event.offsetY - 30}px`)
.html(`<strong>${d3.timeFormat('%H:%M')(d.timestamp)}</strong><br/>Value: ${d.value.toFixed(1)}`);
}
function handleMouseOut() {
d3.select(tooltipElement).style('opacity', 0);
dispatch('hover', null);
}
$: if (svgElement && data.length > 0) {
updateChart();
}
function updateChart() {
const svg = d3.select(svgElement);
const path = svg.select('.line-path');
const areaPath = svg.select('.area-path');
const dots = svg.select('.dots-container');
// Update line with transition
path.transition()
.duration(animate ? 500 : 0)
.ease(d3.easeQuadOut)
.attr('d', line(data));
// Update area
areaPath.transition()
.duration(animate ? 500 : 0)
.ease(d3.easeQuadOut)
.attr('d', area(data));
// Update dots
const circles = dots.selectAll('circle')
.data(data, d => d.id);
circles.enter()
.append('circle')
.attr('r', 0)
.attr('cx', d => xScale(d.timestamp))
.attr('cy', d => yScale(d.value))
.attr('fill', '#00d4ff')
.attr('stroke', '#0a0e17')
.attr('stroke-width', 2)
.on('mouseover', handleMouseOver)
.on('mouseout', handleMouseOut)
.transition()
.duration(300)
.attr('r', 4);
circles.transition()
.duration(animate ? 500 : 0)
.attr('cx', d => xScale(d.timestamp))
.attr('cy', d => yScale(d.value));
circles.exit()
.transition()
.duration(200)
.attr('r', 0)
.remove();
}
onMount(() => {
const svg = d3.select(svgElement);
// Create gradient
const gradient = svg.append('defs')
.append('linearGradient')
.attr('id', 'area-gradient')
.attr('x1', '0%')
.attr('y1', '0%')
.attr('x2', '0%')
.attr('y2', '100%');
gradient.append('stop')
.attr('offset', '0%')
.attr('stop-color', '#00d4ff')
.attr('stop-opacity', 0.4);
gradient.append('stop')
.attr('offset', '100%')
.attr('stop-color', '#00d4ff')
.attr('stop-opacity', 0);
// Glow filter
const filter = svg.append('defs')
.append('filter')
.attr('id', 'glow')
.attr('x', '-50%')
.attr('y', '-50%')
.attr('width', '200%')
.attr('height', '200%');
filter.append('feGaussianBlur')
.attr('stdDeviation', '3')
.attr('result', 'coloredBlur');
const feMerge = filter.append('feMerge');
feMerge.append('feMergeNode').attr('in', 'coloredBlur');
feMerge.append('feMergeNode').attr('in', 'SourceGraphic');
});
</script>
<div class="chart-container" style="width: {width}px; height: {height}px;">
<svg bind:this={svgElement} {width} {height}>
<g transform="translate({margin.left}, {margin.top})">
<!-- Grid lines -->
<g class="grid">
{#each yScale.ticks(5) as tick}
<line
x1="0"
y1={yScale(tick)}
x2={innerWidth}
y2={yScale(tick)}
stroke="#1a2744"
stroke-dasharray="3,3"
/>
{/each}
</g>
<!-- Area -->
<path class="area-path" fill="url(#area-gradient)" d={area(data)}></path>
<!-- Line -->
<path
class="line-path"
fill="none"
stroke="#00d4ff"
stroke-width="2.5"
filter="url(#glow)"
d={line(data)}
></path>
<!-- Dots container -->
<g class="dots-container"></g>
<!-- X Axis -->
<g class="x-axis" transform="translate(0, {innerHeight})">
{#each xScale.ticks(6) as tick}
<text
x={xScale(tick)}
y="25"
fill="#6b7c93"
font-size="11"
text-anchor="middle"
>
{d3.timeFormat('%H:%M')(tick)}
</text>
{/each}
</g>
<!-- Y Axis -->
<g class="y-axis">
{#each yScale.ticks(5) as tick}
<text
x="-10"
y={yScale(tick)}
fill="#6b7c93"
font-size="11"
text-anchor="end"
dominant-baseline="middle"
>
{tick}
</text>
{/each}
</g>
</g>
</svg>
<div bind:this={tooltipElement} class="tooltip"></div>
</div>
<style>
.chart-container {
position: relative;
background: linear-gradient(135deg, #0d1321 0%, #151d2e 100%);
border-radius: 12px;
padding: 10px;
border: 1px solid #1a2744;
box-shadow: 0 4px 30px rgba(0, 0, 0, 0.3);
}
.tooltip {
position: absolute;
background: #1a2744;
border: 1px solid #00d4ff;
border-radius: 6px;
padding: 8px 12px;
font-size: 12px;
pointer-events: none;
opacity: 0;
transition: opacity 0.15s;
box-shadow: 0 4px 20px rgba(0, 212, 255, 0.2);
z-index: 100;
}
svg :global(circle) {
cursor: pointer;
transition: r 0.15s ease;
}
svg :global(circle:hover) {
r: 7;
fill: #00ff88;
}
</style>
File: src/lib/components/BarChart.svelte
<script>
import { onMount } from 'svelte';
import * as d3 from 'd3';
export let data = [];
export let width = 500;
export let height = 300;
export let animate = true;
let svgElement;
let tooltipElement;
const margin = { top: 20, right: 20, bottom: 50, left: 60 };
const innerWidth = width - margin.left - margin.right;
const innerHeight = height - margin.top - margin.bottom;
$: xScale = d3.scaleBand()
.domain(data.map(d => d.name))
.range([0, innerWidth])
.padding(0.3);
$: yScale = d3.scaleLinear()
.domain([0, d3.max(data, d => d.value) * 1.1])
.range([innerHeight, 0]);
const colorScale = d3.scaleSequential()
.domain([0, data.length])
.interpolator(d3.interpolateRgbBasis(['#00d4ff', '#00ff88', '#ffd93d', '#ff6b6b']));
$: if (svgElement && data.length > 0) {
updateChart();
}
function updateChart() {
const svg = d3.select(svgElement);
const barsGroup = svg.select('.bars-container');
const bars = barsGroup.selectAll('rect')
.data(data, d => d.name);
// Enter
bars.enter()
.append('rect')
.attr('x', d => xScale(d.name))
.attr('width', xScale.bandwidth())
.attr('y', innerHeight)
.attr('height', 0)
.attr('fill', (d, i) => colorScale(i))
.attr('rx', 4)
.attr('ry', 4)
.on('mouseover', function(event, d) {
d3.select(this)
.transition()
.duration(150)
.attr('opacity', 0.8);
d3.select(tooltipElement)
.style('opacity', 1)
.style('left', `${event.offsetX + 10}px`)
.style('top', `${event.offsetY - 30}px`)
.html(`<strong>${d.name}</strong><br/>Value: ${d.value}<br/>Change: ${d.change > 0 ? '+' : ''}${d.change.toFixed(1)}%`);
})
.on('mouseout', function() {
d3.select(this)
.transition()
.duration(150)
.attr('opacity', 1);
d3.select(tooltipElement).style('opacity', 0);
})
.transition()
.duration(animate ? 800 : 0)
.delay((d, i) => i * 100)
.ease(d3.easeBackOut.overshoot(1.2))
.attr('y', d => yScale(d.value))
.attr('height', d => innerHeight - yScale(d.value));
// Update
bars.transition()
.duration(animate ? 500 : 0)
.attr('x', d => xScale(d.name))
.attr('width', xScale.bandwidth())
.attr('y', d => yScale(d.value))
.attr('height', d => innerHeight - yScale(d.value))
.attr('fill', (d, i) => colorScale(i));
// Exit
bars.exit()
.transition()
.duration(300)
.attr('y', innerHeight)
.attr('height', 0)
.remove();
}
</script>
<div class="chart-container" style="width: {width}px; height: {height}px;">
<svg bind:this={svgElement} {width} {height}>
<defs>
<filter id="bar-shadow" x="-20%" y="-20%" width="140%" height="140%">
<feDropShadow dx="0" dy="2" stdDeviation="3" flood-color="#00d4ff" flood-opacity="0.3"/>
</filter>
</defs>
<g transform="translate({margin.left}, {margin.top})">
<!-- Grid -->
{#each yScale.ticks(5) as tick}
<line
x1="0"
y1={yScale(tick)}
x2={innerWidth}
y2={yScale(tick)}
stroke="#1a2744"
stroke-dasharray="3,3"
/>
{/each}
<!-- Bars -->
<g class="bars-container" filter="url(#bar-shadow)"></g>
<!-- X Axis Labels -->
<g transform="translate(0, {innerHeight})">
{#each data as d}
<text
x={xScale(d.name) + xScale.bandwidth() / 2}
y="25"
fill="#6b7c93"
font-size="11"
text-anchor="middle"
>
{d.name}
</text>
{/each}
</g>
<!-- Y Axis -->
{#each yScale.ticks(5) as tick}
<text
x="-10"
y={yScale(tick)}
fill="#6b7c93"
font-size="11"
text-anchor="end"
dominant-baseline="middle"
>
{tick}
</text>
{/each}
</g>
</svg>
<div bind:this={tooltipElement} class="tooltip"></div>
</div>
<style>
.chart-container {
position: relative;
background: linear-gradient(135deg, #0d1321 0%, #151d2e 100%);
border-radius: 12px;
padding: 10px;
border: 1px solid #1a2744;
box-shadow: 0 4px 30px rgba(0, 0, 0, 0.3);
}
.tooltip {
position: absolute;
background: #1a2744;
border: 1px solid #00d4ff;
border-radius: 6px;
padding: 8px 12px;
font-size: 12px;
pointer-events: none;
opacity: 0;
transition: opacity 0.15s;
box-shadow: 0 4px 20px rgba(0, 212, 255, 0.2);
z-index: 100;
}
svg :global(rect) {
cursor: pointer;
}
</style>
File: src/lib/components/PieChart.svelte
<script>
import { onMount } from 'svelte';
import * as d3 from 'd3';
export let data = [];
export let width = 350;
export let height = 350;
export let innerRadius = 60;
export let animate = true;
let svgElement;
let tooltipElement;
const radius = Math.min(width, height) / 2 - 40;
$: pie = d3.pie()
.value(d => d.value)
.sort(null)
.padAngle(0.03)(data);
$: arc = d3.arc()
.innerRadius(innerRadius)
.outerRadius(radius)
.cornerRadius(6);
$: hoverArc = d3.arc()
.innerRadius(innerRadius)
.outerRadius(radius + 15)
.cornerRadius(6);
function handleMouseOver(event, d) {
d3.select(event.currentTarget)
.transition()
.duration(200)
.attr('d', hoverArc);
d3.select(tooltipElement)
.style('opacity', 1)
.style('left', `${event.offsetX + 10}px`)
.style('top', `${event.offsetY - 30}px`)
.html(`<strong>${d.data.label}</strong><br/>${d.data.value.toFixed(1)}%`);
}
function handleMouseOut(event, d) {
d3.select(event.currentTarget)
.transition()
.duration(200)
.attr('d', arc);
d3.select(tooltipElement).style('opacity', 0);
}
$: total = data.reduce((sum, d) => sum + d.value, 0);
</script>
<div class="chart-container" style="width: {width}px; height: {height}px;">
<svg bind:this={svgElement} {width} {height}>
<defs>
{#each data as d, i}
<filter id="glow-{i}" x="-50%" y="-50%" width="200%" height="200%">
<feGaussianBlur stdDeviation="4" result="coloredBlur"/>
<feMerge>
<feMergeNode in="coloredBlur"/>
<feMergeNode in="SourceGraphic"/>
</feMerge>
</filter>
{/each}
</defs>
<g transform="translate({width / 2}, {height / 2})">
<!-- Pie segments -->
{#each pie as segment, i (segment.data.label)}
{@const d = arc(segment)}
{@const startAngle = segment.startAngle}
{@const endAngle = segment.endAngle}
{#if animate}
<path
d={d}
fill={data[i].color}
filter="url(#glow-{i})"
stroke="#0a0e17"
stroke-width="2"
on:mouseover={handleMouseOver}
on:mouseout={handleMouseOut}
style="opacity: 0"
use:animatePie={arc(segment)}
></path>
{:else}
<path
d={d}
fill={data[i].color}
filter="url(#glow-{i})"
stroke="#0a0e17"
stroke-width="2"
on:mouseover={handleMouseOver}
on:mouseout={handleMouseOut}
></path>
{/if}
{/each}
<!-- Center text -->
<text x="0" y="-8" text-anchor="middle" fill="#e0e6ed" font-size="24" font-weight="bold">
{total.toFixed(1)}%
</text>
<text x="0" y="15" text-anchor="middle" fill="#6b7c93" font-size="12">
Total Traffic
</text>
</g>
</svg>
<!-- Legend -->
<div class="legend">
{#each data as d}
<div class="legend-item">
<div class="legend-color" style="background: {d.color}"></div>
<span>{d.label}</span>
<span class="legend-value">{d.value.toFixed(1)}%</span>
</div>
{/each}
</div>
<div bind:this={tooltipElement} class="tooltip"></div>
</div>
<script context="module">
import { tweened } from 'svelte/motion';
import { cubicOut } from 'svelte/easing';
function animatePie(node, d) {
const arc = d3.arc().innerRadius(60).outerRadius(135).cornerRadius(6);
const interpolate = d3.interpolate(
{ startAngle: 0, endAngle: 0 },
{ startAngle: d.startAngle, endAngle: d.endAngle }
);
return {
duration: 1000,
delay: d.index * 150,
easing: cubicOut,
tick: (t) => {
node.setAttribute('d', arc(interpolate(t)));
node.style.opacity = t;
}
};
}
</script>
<style>
.chart-container {
position: relative;
background: linear-gradient(135deg, #0d1321 0%, #151d2e 100%);
border-radius: 12px;
padding: 15px;
border: 1px solid #1a2744;
box-shadow: 0 4px 30px rgba(0, 0, 0, 0.3);
display: flex;
flex-direction: column;
align-items: center;
}
.legend {
display: flex;
flex-wrap: wrap;
gap: 10px;
margin-top: 10px;
justify-content: center;
}
.legend-item {
display: flex;
align-items: center;
gap: 6px;
font-size: 12px;
color: #9aa5b4;
}
.legend-color {
width: 12px;
height: 12px;
border-radius: 3px;
box-shadow: 0 0 8px currentColor;
}
.legend-value {
color: #e0e6ed;
font-weight: 600;
margin-left: 4px;
}
.tooltip {
position: absolute;
background: #1a2744;
border: 1px solid #00d4ff;
border-radius: 6px;
padding: 8px 12px;
font-size: 12px;
pointer-events: none;
opacity: 0;
transition: opacity 0.15s;
box-shadow: 0 4px 20px rgba(0, 212, 255, 0.2);
z-index: 100;
}
svg :global(path) {
cursor: pointer;
transition: filter 0.2s;
}
</style>
File: src/lib/components/StatsCard.svelte
<script>
import { spring } from 'svelte/motion';
export let title = '';
export let value = 0;
export let change = 0;
export let prefix = '';
export let suffix = '';
export let icon = '📊';
$: isPositive = change >= 0;
$: formattedValue = prefix + value.toLocaleString('en-US', {
maximumFractionDigits: prefix === '$' ? 0 : 2
}) + suffix;
// Animated value
const animatedValue = spring(value, { stiffness: 0.1, damping: 0.8 });
$: animatedValue.set(value);
</script>
<div class="stats-card">
<div class="card-header">
<span class="icon">{icon}</span>
<span class="title">{title}</span>
</div>
<div class="card-body">
<div class="value">{formattedValue}</div>
<div class="change" class:positive={isPositive} class:negative={!isPositive}>
<span class="arrow">{isPositive ? '↑' : '↓'}</span>
<span>{Math.abs(change).toFixed(1)}%</span>
</div>
</div>
<div class="sparkline">
<svg width="100" height="30" viewBox="0 0 100 30">
{#each Array.from({ length: 10 }, (_, i) => ({
x: i * 11,
y: 15 + Math.sin(i * 0.8 + Date.now() * 0.001) * 10
})) as point, i}
{@const nextPoint = {
x: (i + 1) * 11,
y: 15 + Math.sin((i + 1) * 0.8 + Date.now() * 0.001) * 10
}}
{#if i < 9}
<line
x1={point.x}
y1={point.y}
x2={nextPoint.x}
y2={nextPoint.y}
stroke={isPositive ? '#00ff88' : '#ff6b6b'}
stroke-width="2"
stroke-linecap="round"
/>
{/if}
{/each}
</svg>
</div>
<div class="card-glow" style="background: {isPositive ? '#00ff88' : '#ff6b6b'}"></div>
</div>
<style>
.stats-card {
position: relative;
background: linear-gradient(135deg, #0d1321 0%, #151d2e 100%);
border-radius: 16px;
padding: 20px;
border: 1px solid #1a2744;
overflow: hidden;
transition: transform 0.3s, box-shadow 0.3s;
}
.stats-card:hover {
transform: translateY(-4px);
box-shadow: 0 8px 40px rgba(0, 0, 0, 0.4);
}
.card-header {
display: flex;
align-items: center;
gap: 10px;
margin-bottom: 15px;
}
.icon {
font-size: 24px;
}
.title {
color: #6b7c93;
font-size: 14px;
font-weight: 500;
text-transform: uppercase;
letter-spacing: 0.5px;
}
.card-body {
display: flex;
justify-content: space-between;
align-items: baseline;
}
.value {
font-size: 28px;
font-weight: 700;
color: #e0e6ed;
letter-spacing: -0.5px;
}
.change {
display: flex;
align-items: center;
gap: 4px;
font-size: 14px;
font-weight: 600;
padding: 4px 10px;
border-radius: 20px;
}
.change.positive {
background: rgba(0, 255, 136, 0.15);
color: #00ff88;
}
.change.negative {
background: rgba(255, 107, 107, 0.15);
color: #ff6b6b;
}
.arrow {
font-size: 12px;
}
.sparkline {
margin-top: 15px;
opacity: 0.6;
}
.card-glow {
position: absolute;
top: -50%;
right: -50%;
width: 100%;
height: 100%;
opacity: 0.05;
border-radius: 50%;
filter: blur(40px);
pointer-events: none;
}
</style>
File: src/routes/+page.svelte
<script>
import { onMount, onDestroy, tick } from 'svelte';
import * as d3 from 'd3';
import LineChart from '$lib/components/LineChart.svelte';
import BarChart from '$lib/components/BarChart.svelte';
import PieChart from '$lib/components/PieChart.svelte';
import StatsCard from '$lib/components/StatsCard.svelte';
import {
timeSeriesData,
categoryData,
pieData,
metrics,
updateInterval
} from '$lib/stores/dataStore.js';
import {
generateTimeSeriesData,
generateCategoryData,
generatePieData,
generateMetrics,
addNewPoint,
updateLastPoint
} from '$lib/utils/dataGenerator.js';
let intervalId;
let isLive = true;
let particles = [];
let chartWidth = 600;
let barChartWidth = 500;
// Initialize data
onMount(() => {
// Responsive chart widths
updateChartWidths();
window.addEventListener('resize', updateChartWidths);
// Create particles
particles = Array.from({ length: 50 }, () => ({
x: Math.random() * window.innerWidth,
y: Math.random() * window.innerHeight,
size: Math.random() * 3 + 1,
speedX: (Math.random() - 0.5) * 0.5,
speedY: (Math.random() - 0.5) * 0.5,
opacity: Math.random() * 0.5 + 0.1
}));
animateParticles();
startLiveUpdates();
});
onDestroy(() => {
window.removeEventListener('resize', updateChartWidths);
if (intervalId) clearInterval(intervalId);
});
function updateChartWidths() {
const container = document.querySelector('.dashboard');
if (container) {
chartWidth = Math.min(700, container.clientWidth - 40);
barChartWidth = Math.min(550, container.clientWidth - 40);
}
}
function startLiveUpdates() {
if (intervalId) clearInterval(intervalId);
let updateCount = 0;
intervalId = setInterval(() => {
if (!isLive) return;
updateCount++;
// Update time series every tick
timeSeriesData.update(data => {
if (updateCount % 3 === 0) {
return addNewPoint(data);
}
return updateLastPoint(data);
});
// Update other data less frequently
if (updateCount % 5 === 0) {
categoryData.update(data =>
data.map(d => ({
...d,
value: Math.max(50, d.value + (Math.random() - 0.5) * 50),
change: (Math.random() - 0.5) * 10
}))
);
}
if (updateCount % 4 === 0) {
pieData.update(data =>
data.map(d => ({
...d,
value: Math.max(5, d.value + (Math.random() - 0.5) * 5)
}))
);
}
// Update metrics
metrics.update(m => ({
revenue: {
...m.revenue,
value: m.revenue.value + Math.floor((Math.random() - 0.3) * 1000),
change: m.revenue.change + (Math.random() - 0.5) * 2
},
users: {
...m.users,
value: Math.max(1000, m.users.value + Math.floor((Math.random() - 0.5) * 500)),
change: m.users.change + (Math.random() - 0.5) * 2
},
conversion: {
...m.conversion,
value: Math.max(1, Math.min(10, m.conversion.value + (Math.random() - 0.5) * 0.5)),
change: m.conversion.change + (Math.random() - 0.5) * 2
},
uptime: {
...m.uptime,
value: Math.min(100, m.uptime.value + (Math.random() - 0.5) * 0.01),
change: m.uptime.change + (Math.random() - 0.5) * 0.01
}
}));
}, $updateInterval);
}
function toggleLive() {
isLive = !isLive;
if (isLive) {
startLiveUpdates();
}
}
function refreshData() {
timeSeriesData.set(generateTimeSeriesData(24));
categoryData.set(generateCategoryData());
pieData.set(generatePieData());
metrics.set(generateMetrics());
}
let animationFrame;
function animateParticles() {
particles = particles.map(p => ({
...p,
x: (p.x + p.speedX + window.innerWidth) % window.innerWidth,
y: (p.y + p.speedY + window.innerHeight) % window.innerHeight
}));
animationFrame = requestAnimationFrame(animateParticles);
}
</script>
<svelte:head>
<title>Real-Time Analytics Dashboard</title>
</svelte:head>
<div class="dashboard">
<!-- Particle Background -->
<div class="particles">
{#each particles as p}
<div
class="particle"
style="left: {p.x}px; top: {p.y}px; width: {p.size}px; height: {p.size}px; opacity: {p.opacity};"
></div>
{/each}
</div>
<!-- Header -->
<header class="header">
<div class="header-left">
<h1>Analytics Dashboard</h1>
<span class="subtitle">Real-time metrics visualization</span>
</div>
<div class="header-right">
<div class="live-indicator" class:active={isLive}>
<span class="dot"></span>
{isLive ? 'LIVE' : 'PAUSED'}
</div>
<button class="btn" on:click={toggleLive}>
{isLive ? '⏸ Pause' : '▶ Resume'}
</button>
<button class="btn btn-primary" on:click={refreshData}>
↻ Refresh
</button>
<div class="interval-control">
<label>Update Speed:</label>
<input
type="range"
min="500"
max="5000"
step="500"
bind:value={$updateInterval}
/>
<span>{$updateInterval}ms</span>
</div>
</div>
</header>
<!-- Stats Cards -->
<section class="stats-grid">
{#if $metrics}
<StatsCard
title="Revenue"
value={$metrics.revenue.value}
change={$metrics.revenue.change}
prefix="$"
icon="💰"
/>
<StatsCard
title="Active Users"
value={$metrics.users.value}
change={$metrics.users.change}
icon="👥"
/>
<StatsCard
title="Conversion Rate"
value={$metrics.conversion.value}
change={$metrics.conversion.change}
suffix="%"
icon="📈"
/>
<StatsCard
title="System Uptime"
value={$metrics.uptime.value}
change={$metrics.uptime.change}
suffix="%"
icon="⚡"
/>
{/if}
</section>
<!-- Charts Grid -->
<section class="charts-grid">
<div class="chart-section">
<div class="chart-header">
<h2>Time Series Analysis</h2>
<span class="chart-info">24-hour rolling window</span>
</div>
<LineChart data={$timeSeriesData} width={chartWidth} height={320} />
</div>
<div class="chart-section">
<div class="chart-header">
<h2>Category Performance</h2>
<span class="chart-info">Sector breakdown</span>
</div>
<BarChart data={$categoryData} width={barChartWidth} height={320} />
</div>
<div class="chart-section pie-section">
<div class="chart-header">
<h2>Traffic Distribution</h2>
<span class="chart-info">By device type</span>
</div>
<PieChart data={$pieData} width={350} height={350} />
</div>
<div class="chart-section full-width">
<div class="chart-header">
<h2>Live Activity Monitor</h2>
<span class="chart-info">Real-time stream</span>
</div>
<div class="activity-stream">
{#each $timeSeriesData.slice(-10) as point, i}
<div class="activity-item" style="animation-delay: {i * 50}ms">
<div class="activity-bar" style="height: {(point.value / 180) * 100}%"></div>
<span class="activity-label">
{d3.timeFormat('%H:%M')(point.timestamp)}
</span>
</div>
{/each}
</div>
</div>
</section>
<!-- Footer -->
<footer class="footer">
<span>Built with SvelteKit + D3.js</span>
<span>Last updated: {new Date().toLocaleTimeString()}</span>
</footer>
</div>
<style>
:global(body) {
background: #0a0e17;
margin: 0;
padding: 0;
}
.dashboard {
position: relative;
min-height: 100vh;
padding: 20px;
max-width: 1600px;
margin: 0 auto;
overflow: hidden;
}
.particles {
position: fixed;
top: 0;
left: 0;
width: 100%;
height: 100%;
pointer-events: none;
z-index: 0;
}
.particle {
position: absolute;
background: #00d4ff;
border-radius: 50%;
box-shadow: 0 0 10px #00d4ff;
}
.header {
display: flex;
justify-content: space-between;
align-items: center;
flex-wrap: wrap;
gap: 20px;
margin-bottom: 30px;
position: relative;
z-index: 10;
padding-bottom: 20px;
border-bottom: 1px solid #1a2744;
}
.header-left h1 {
font-size: 32px;
font-weight: 700;
background: linear-gradient(135deg, #00d4ff, #00ff88);
-webkit-background-clip: text;
-webkit-text-fill-color: transparent;
background-clip: text;
margin: 0;
}
.subtitle {
color: #6b7c93;
font-size: 14px;
}
.header-right {
display: flex;
align-items: center;
gap: 15px;
flex-wrap: wrap;
}
.live-indicator {
display: flex;
align-items: center;
gap: 8px;
padding: 8px 16px;
background: #1a2744;
border-radius: 20px;
font-size: 12px;
font-weight: 600;
letter-spacing: 1px;
color: #ff6b6b;
}
.live-indicator.active {
color: #00ff88;
}
.dot {
width: 8px;
height: 8px;
background: currentColor;
border-radius: 50%;
animation: pulse 1.5s infinite;
}
@keyframes pulse {
0%, 100% { opacity: 1; transform: scale(1); }
50% { opacity: 0.5; transform: scale(0.8); }
}
.btn {
padding: 10px 20px;
border: none;
border-radius: 8px;
font-size: 14px;
font-weight: 500;
cursor: pointer;
background: #1a2744;
color: #e0e6ed;
transition: all 0.2s;
}
.btn:hover {
background: #243554;
transform: translateY(-2px);
}
.btn-primary {
background: linear-gradient(135deg, #00d4ff, #0099cc);
color: #0a0e17;
}
.btn-primary:hover {
background: linear-gradient(135deg, #00e5ff, #00b3e6);
}
.interval-control {
display: flex;
align-items: center;
gap: 10px;
color: #6b7c93;
font-size: 12px;
}
.interval-control input[type="range"] {
width: 100px;
accent-color: #00d4ff;
}
.stats-grid {
display: grid;
grid-template-columns: repeat(auto-fit, minmax(240px, 1fr));
gap: 20px;
margin-bottom: 30px;
position: relative;
z-index: 10;
}
.charts-grid {
display: grid;
grid-template-columns: repeat(auto-fit, minmax(500px, 1fr));
gap: 25px;
position: relative;
z-index: 10;
}
@media (max-width: 600px) {
.charts-grid {
grid-template-columns: 1fr;
}
}
.chart-section {
background: linear-gradient(135deg, #0d1321 0%, #151d2e 100%);
border-radius: 16px;
padding: 20px;
border: 1px solid #1a2744;
box-shadow: 0 4px 30px rgba(0, 0, 0, 0.3);
transition: transform 0.3s, box-shadow 0.3s;
}
.chart-section:hover {
transform: translateY(-4px);
box-shadow: 0 8px 40px rgba(0, 0, 0, 0.4);
}
.chart-section.full-width {
grid-column: 1 / -1;
}
.chart-header {
display: flex;
justify-content: space-between;
align-items: center;
margin-bottom: 15px;
}
.chart-header h2 {
font-size: 18px;
font-weight: 600;
color: #e0e6ed;
margin: 0;
}
.chart-info {
color: #6b7c93;
font-size: 12px;
}
.activity-stream {
display: flex;
justify-content: space-around;
align-items: flex-end;
height: 150px;
padding: 20px 10px;
background: rgba(0, 0, 0, 0.2);
border-radius: 8px;
}
.activity-item {
display: flex;
flex-direction: column;
align-items: center;
gap: 8px;
flex: 1;
max-width: 60px;
}
.activity-bar {
width: 100%;
max-width: 30px;
background: linear-gradient(180deg, #00d4ff, #0066cc);
border-radius: 4px 4px 0 0;
transition: height 0.5s ease-out;
box-shadow: 0 0 15px rgba(0, 212, 255, 0.4);
}
.activity-label {
font-size: 10px;
color: #6b7c93;
}
.pie-section {
display: flex;
flex-direction: column;
align-items: center;
}
.footer {
display: flex;
justify-content: space-between;
padding: 20px 0;
margin-top: 30px;
border-top: 1px solid #1a2744;
color: #6b7c93;
font-size: 12px;
position: relative;
z-index: 10;
}
</style>
Key Features
-
Real-time Updates: Data automatically refreshes at configurable intervals
-
D3.js Integration: Smooth transitions and animations for all chart types
-
Svelte Reactivity: Stores propagate changes instantly to components
-
Multiple Chart Types:
- Line chart with area fill and interactive dots
- Bar chart with hover effects and color gradients
- Donut/Pie chart with animated segments
- Activity stream visualization
-
Interactive Controls:
- Pause/Resume live updates
- Adjust update speed (500ms-5000ms)
- Manual refresh button
-
Visual Effects:
- Floating particle background
- Glowing effects on charts
- Smooth CSS transitions
- Dark theme with cyan/teal accents
-
Responsive Design: Charts adapt to container width
Running the Dashboard
npm run dev
Open http://localhost:5173 to see the live dashboard with real-time animated visualizations!