tapircharts
Version:
A lightweight, customizable JavaScript charting framework designed for dashboard applications with multiple charts sharing themes
598 lines (492 loc) • 15.3 kB
Markdown
# TapirCharts
A lightweight, customizable JavaScript charting framework designed for dashboard applications with multiple charts sharing themes. Built with pure JavaScript, no external dependencies required.
## Features
- **Powerful Theme System** - Global theme management with coordinated updates across all charts
- **Responsive Design** - Automatic resizing and mobile-friendly layouts
- **High Performance** - SVG-based rendering optimized for dashboards with 20+ charts
- **Clean Configuration API** - Simple, intuitive configuration with sensible defaults
- **Multiple Chart Types** - Bar charts, line charts, circle charts, and multi-series support
- **Interactive Features** - Hover tooltips, smooth animations, zoom/pan controls
- **Zero Dependencies** - Pure JavaScript implementation, works everywhere
## Installation
### NPM Package (Recommended)
```bash
npm install tapircharts
```
### CDN (Browser)
```html
<!-- Latest version -->
<script src="https://unpkg.com/tapircharts@latest/dist/tapircharts.js"></script>
<!-- Minified version -->
<script src="https://unpkg.com/tapircharts@latest/dist/tapircharts.min.js"></script>
```
## Quick Start Examples
### Basic CDN Usage
```html
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>TapirCharts CDN Usage</title>
<style>
.chart-container {
margin: 20px 0;
height: 400px;
}
</style>
</head>
<body>
<div class="container">
<h1>TapirCharts CDN Usage Example</h1>
<div class="controls">
<button onclick="setTheme('default')">Default Theme</button>
<button onclick="setTheme('dark')">Dark Theme</button>
<button onclick="setTheme('minimal')">Minimal Theme</button>
</div>
<div id="bar-chart" class="chart-container"></div>
<div id="line-chart" class="chart-container"></div>
</div>
<!-- Load TapirCharts from CDN -->
<script src="https://unpkg.com/tapircharts@latest/dist/tapircharts.js"></script>
<script>
// Initialize TapirCharts
const charts = new TapirCharts();
// Create bar chart
const barChart = charts.createBarChart('#bar-chart', {
title: 'Monthly Sales Performance',
showValues: true,
responsive: true,
barCornerRadius: 4
});
// Set bar chart data
barChart.setData([
{ x: 'Jan', y: 1200, previousValue: 1000 },
{ x: 'Feb', y: 1900, previousValue: 1200 },
{ x: 'Mar', y: 1500, previousValue: 1900 },
{ x: 'Apr', y: 2100, previousValue: 1500 },
{ x: 'May', y: 2400, previousValue: 2100 },
{ x: 'Jun', y: 2200, previousValue: 2400 }
]);
// Create line chart
const lineChart = charts.createLineChart('#line-chart', {
title: 'Growth Trend Over Time',
showArea: true,
responsive: true,
showGrid: true
});
// Set line chart data
lineChart.setData([
{ x: 'Week 1', y: 100 },
{ x: 'Week 2', y: 150 },
{ x: 'Week 3', y: 120 },
{ x: 'Week 4', y: 180 },
{ x: 'Week 5', y: 220 },
{ x: 'Week 6', y: 200 },
{ x: 'Week 7', y: 280 },
{ x: 'Week 8', y: 320 }
]);
// Theme switching function
function setTheme(themeName) {
charts.setTheme(themeName);
console.log(`Theme changed to: ${themeName}`);
}
</script>
</body>
</html>
```
### NPM Usage (Node.js/Bundlers)
```javascript
// Install: npm install tapircharts
import TapirCharts from 'tapircharts';
// Or with CommonJS:
// const TapirCharts = require('tapircharts');
// Initialize
const charts = new TapirCharts();
// Create a simple bar chart
const chart = charts.createBarChart('#chart', {
title: 'Monthly Sales',
showValues: true,
responsive: true
});
// Set data
chart.setData([
{ x: 'Jan', y: 1200 },
{ x: 'Feb', y: 1900 },
{ x: 'Mar', y: 1500 }
]);
```
### Direct Include Usage
```html
<!DOCTYPE html>
<html>
<head>
<title>TapirCharts Direct Include</title>
</head>
<body>
<div id="chart"></div>
<!-- Load TapirCharts source files -->
<script src="src/ThemeManager.js"></script>
<script src="src/ChartFramework.js"></script>
<script src="src/BarChart.js"></script>
<script src="src/LineChart.js"></script>
<script src="src/CircleChart.js"></script>
<script src="src/ChartFactory.js"></script>
<script src="src/TapirCharts.js"></script>
<script>
// Create a bar chart directly
const chart = new BarChart('#chart', {
title: 'Monthly Sales',
showValues: true,
width: 600,
height: 400
});
// Set data
chart.setData([
{ x: 'Jan', y: 1200 },
{ x: 'Feb', y: 1900 },
{ x: 'Mar', y: 1500 }
]);
</script>
</body>
</html>
```
## Chart Types
### Bar Charts
```javascript
// Basic bar chart
const barChart = new BarChart('#chart', {
title: 'Monthly Sales',
showValues: true,
barCornerRadius: 4,
enableZoom: true,
enablePan: true,
showControls: true
});
barChart.setData([
{ x: 'Q1', y: 1200 },
{ x: 'Q2', y: 1900 },
{ x: 'Q3', y: 1500 },
{ x: 'Q4', y: 2100 }
]);
// Stacked bar chart
const stackedChart = new BarChart('#stacked-chart', {
title: 'Market Share',
stacked: true,
stackLabels: ['Product A', 'Product B', 'Product C']
});
stackedChart.setData([
{
x: 'Q1',
segments: [
{ label: 'Product A', value: 30 },
{ label: 'Product B', value: 25 },
{ label: 'Product C', value: 20 }
]
}
]);
```
### Line Charts
```javascript
// Basic line chart with area fill
const lineChart = new LineChart('#line-chart', {
title: 'Daily Revenue Trend',
showArea: true,
showGradient: true,
smooth: true,
enableZoom: true,
enablePan: true,
showControls: true
});
// Multi-series line chart
const multiLineChart = new LineChart('#multi-line-chart', {
title: 'Performance Metrics',
multiSeries: true,
showDots: true
});
multiLineChart.setData([
{
x: 'Jan',
series: [
{ name: 'Revenue', y: 5000 },
{ name: 'Costs', y: 3000 }
]
},
{
x: 'Feb',
series: [
{ name: 'Revenue', y: 7500 },
{ name: 'Costs', y: 3200 }
]
}
]);
```
### Circle Charts
```javascript
// Progress circle
const progressChart = new CircleChart('#progress-chart', {
title: 'Project Progress',
width: 280,
height: 280,
strokeWidth: 10,
showValue: true,
showPercentage: true
});
progressChart.setData(67);
// Multi-segment pie chart
const pieChart = new CircleChart('#pie-chart', {
title: 'Market Share',
innerRadius: 0, // Full pie chart
showValue: true,
legend: true
});
pieChart.setData([
{ value: 45, label: 'Product A', color: 'var(--color-primary, #006EDB)' },
{ value: 30, label: 'Product B', color: 'var(--color-success, #008060)' },
{ value: 15, label: 'Product C', color: 'var(--color-warning, #ffcc00)' },
{ value: 10, label: 'Others', color: 'var(--color-critical, #D72C0D)' }
]);
// Donut chart
const donutChart = new CircleChart('#donut-chart', {
title: 'Revenue Breakdown',
innerRadius: 0.5,
showValue: true,
centerText: false
});
donutChart.setData([
{ value: 120000, label: 'Subscriptions', color: 'var(--color-primary, #006EDB)' },
{ value: 80000, label: 'One-time Sales', color: 'var(--color-success, #008060)' },
{ value: 45000, label: 'Consulting', color: 'var(--color-violet-600, #8b5cf6)' },
{ value: 25000, label: 'Support', color: 'var(--color-warning, #ffcc00)' }
]);
```
## Theme System
### Built-in Themes
- **Default** - Clean, professional look
- **Dark** - Dark mode for low-light environments
- **Minimal** - Simple, distraction-free design
- **GMF** - Integration with GMF CSS Framework (auto-detected)
### Theme Switching
```javascript
// Global theme switching (affects all charts)
const themeManager = ThemeManager.getInstance();
// Switch themes
themeManager.setGlobalTheme('dark');
themeManager.setGlobalTheme('minimal');
themeManager.setGlobalTheme('default');
// Get current theme
const currentTheme = themeManager.getCurrentTheme();
// Auto-detect GMF framework
if (themeManager.isGMFAvailable()) {
themeManager.autoDetectGMF();
}
```
### Custom Themes
```javascript
// Create custom theme
const customTheme = {
backgroundColor: '#2c3e50',
gridColor: '#34495e',
textColor: '#ecf0f1',
barColors: ['#e74c3c', '#3498db', '#f39c12'],
axisColor: '#bdc3c7',
tooltipBackground: '#ecf0f1',
tooltipText: '#2c3e50',
tooltipBorder: '#bdc3c7',
// Chart configuration
chart: {
margin: { top: 30, right: 30, bottom: 50, left: 70 },
barWidth: 'auto',
barSpacing: 6,
barCornerRadius: 4,
fontSize: 13,
titleFontSize: 18
}
};
// Add and use custom theme
themeManager.addCustomTheme('custom', customTheme);
themeManager.setGlobalTheme('custom');
```
## Interactive Features
### Zoom and Pan Controls
```javascript
const chart = new BarChart('#chart', {
title: 'Interactive Chart',
enableZoom: true, // Enable zoom functionality
enablePan: true, // Enable pan functionality
showControls: true, // Show built-in controls
controlsPosition: 'top-right',
minZoom: 0.5, // 50% zoom out limit
maxZoom: 5.0 // 500% zoom in limit
});
// Manual zoom/pan control
chart.zoomIn();
chart.zoomOut();
chart.panLeft();
chart.panRight();
chart.resetZoomPan();
```
### Tooltips
```javascript
const chart = new BarChart('#chart', {
title: 'Chart with Custom Tooltips',
showTooltip: true,
tooltipShowDelay: 100, // Delay before showing
tooltipHideDelay: 100, // Delay before hiding
tooltipTemplate: null, // Custom HTML template
tooltipFormatter: null, // Custom data formatter
tooltipStyle: 'default', // 'default', 'compact', 'detailed', 'minimal'
tooltipPosition: 'auto' // 'auto', 'top', 'bottom', 'left', 'right'
});
```
## Configuration
### Basic Configuration
```javascript
const config = {
width: 600, // Chart width
height: 400, // Chart height
title: 'Chart Title', // Chart title
showGrid: true, // Show grid lines
showTooltip: true, // Show hover tooltips
showValues: false, // Show values above bars
responsive: true, // Auto-resize with container
animation: true, // Enable animations
margin: { // Chart margins
top: 20,
right: 20,
bottom: 40,
left: 60
}
};
```
### Bar Chart Configuration
```javascript
const barConfig = {
barWidth: 'auto', // 'auto' or fixed pixel width
barSpacing: 4, // Space between bars (pixels)
barCornerRadius: 2, // Rounded corners (pixels)
minBarWidth: 8, // Minimum bar width when auto
maxBarWidth: 60, // Maximum bar width when auto
barBorder: false, // Add border around bars
barBorderWidth: 1, // Border thickness (pixels)
// Stacked bar options
stacked: false, // Enable stacked bars
stackLabels: [], // Labels for segments
showStackLabels: true, // Show segment labels in tooltips
showStackValues: false, // Show individual values on bars
// Typography
fontSize: 12, // General text size
titleFontSize: 16, // Title text size
labelRotation: 0, // X-axis label rotation (degrees)
// Value formatting
valueFormat: (value) => `$${value}`, // Custom value formatting
};
```
## Data Format
### Basic Data
```javascript
const data = [
{ x: 'Jan', y: 1200 },
{ x: 'Feb', y: 1900 },
{ x: 'Mar', y: 1500 }
];
```
### Enhanced Data with Comparisons
```javascript
const enhancedData = [
{
x: 'Q1 2024',
y: 71913,
previousValue: 65200, // Previous period for comparison
tooltip: 'Strong growth this quarter'
},
{
x: 'Q2 2024',
y: 84521,
previousValue: 71913,
tooltip: 'Record-breaking performance'
}
];
```
### Stacked Data
```javascript
// Object format with labels and colors
const stackedData = [
{
x: 'Q1 2024',
segments: [
{value: 450, label: 'Product Sales', color: '#28a745'},
{value: 280, label: 'Services', color: '#007bff'},
{value: 120, label: 'Subscriptions', color: '#ffc107'}
],
previousValue: 800,
tooltip: 'Strong growth across all segments'
}
];
```
## API Reference
### TapirCharts (Main Class)
```javascript
const charts = new TapirCharts();
// Chart creation methods
charts.createBarChart(container, config);
charts.createLineChart(container, config);
charts.createCircleChart(container, config);
// Theme management
charts.setTheme(themeName);
charts.getCurrentTheme();
charts.getAvailableThemes();
// Export functionality
charts.exportDashboard(container, format); // 'svg' or 'png'
```
### Chart Methods (All Chart Types)
```javascript
// Data management
chart.setData(data);
chart.getData();
// Rendering
chart.render();
chart.clearChart();
// Theme updates
chart.updateTheme();
// Cleanup
chart.destroy();
// Dimensions
chart.getDimensions();
```
### Bar/Line Chart Specific Methods
```javascript
// Zoom and pan (Bar/Line charts only)
chart.zoomIn();
chart.zoomOut();
chart.panLeft();
chart.panRight();
chart.resetZoomPan();
// Scale calculation
chart.calculateScales();
// Rendering components
chart.renderGrid();
chart.renderAxes();
chart.renderBars(); // BarChart only
```
## Empty State Handling
All chart types gracefully handle empty data:
```javascript
// Empty data shows appropriate empty state
chart.setData([]);
// Bar/Line charts show axes and grid with "No data available"
// Circle charts show dashed outline when no segments are provided
```
## Browser Support
- **Modern Browsers**: Chrome 60+, Firefox 55+, Safari 12+, Edge 79+
- **ES6+ Features**: Classes, Arrow functions, Template literals
- **SVG Support**: Required for rendering
- **ResizeObserver**: Required for responsive behavior
## Performance Tips
1. **Use ResizeObserver**: Charts automatically handle container resizing
2. **Batch Updates**: Update multiple charts together when possible
3. **Theme Management**: Use global themes for consistent styling
4. **Memory Cleanup**: Call `destroy()` when removing charts
5. **Data Optimization**: Limit data points for very large datasets
## License
MIT License - see LICENSE file for details.