Example Pattern for Integrating ChartUtils into Dashboard Files
This file demonstrates the pattern for updating existing dashboard JavaScript files to use the new ChartUtils module for:
- Responsive Chart.js configuration
- Empty/loading/error states
- Accessibility features
- Performance optimization
Integration Steps
- Add Loading State: Show loading indicator before data fetch
- Handle Empty Data: Display user-friendly empty state
- Handle Errors: Show error state with retry option
- Use Responsive Options: Apply ChartUtils.getResponsiveOptions()
- Add Keyboard Nav: Enable keyboard navigation for charts
- Add Resize Handler: Create debounced resize handler
Before (Original Code)
function createChart(data) {
const ctx = document.getElementById('myChart');
new Chart(ctx, {
type: 'bar',
data: {
labels: data.labels,
datasets: [{
label: 'My Dataset',
data: data.values
}]
},
options: {
responsive: true,
// ... basic options
}
});
}
After (With ChartUtils)
function createChart(data) {
const ctx = document.getElementById('myChart');
// Hide loading state
ChartUtils.hideStateOverlays('myChart');
// Handle empty data
if (!data || data.values.length === 0) {
ChartUtils.showEmptyState('myChart', 'No data available for selected period');
return;
}
// Create chart with responsive options
const chart = new Chart(ctx, {
type: 'bar',
data: {
labels: data.labels,
datasets: [{
label: 'My Dataset',
data: data.values,
backgroundColor: ChartUtils.THEME_COLORS.cyan
}]
},
options: ChartUtils.getResponsiveOptions('bar', {
plugins: {
tooltip: {
callbacks: {
label: (context) => {
return `${context.dataset.label}: ${ChartUtils.formatNumber(context.parsed.y)}`;
}
}
}
}
})
});
// Add keyboard navigation
ChartUtils.addKeyboardNavigation(ctx, chart);
}
// Main initialization function
async function initDashboard() {
// Show loading state
ChartUtils.showLoadingState('myChart');
try {
// Fetch data
const data = await fetchData();
// Create chart
createChart(data);
} catch (error) {
// Show error state
ChartUtils.showErrorState('myChart', error.message);
}
}
// Add resize handler
const charts = [];
window.addEventListener('resize', ChartUtils.createResizeHandler(charts));
- Version:
- 1.0.0
- Since:
- 2026
- License:
- Apache-2.0
- Source:
Methods
(inner) runCompleteDashboardExample()
Complete dashboard integration example This function demonstrates the full pattern but does not auto-execute Call runCompleteDashboardExample() to execute