AccountingNext/Schaad.Accounting.UI/wwwroot/js/charts.js
Claudio Schaad a6e479094e Add "Strom" page for the yearly NeoVac electricity bills (#9)
Co-authored-by: Claudio Schaad <c.schaad@pog.ch>
Co-committed-by: Claudio Schaad <c.schaad@pog.ch>
2026-10-27 18:40:53 +00:00

291 lines
11 KiB
JavaScript
Raw Blame History

This file contains ambiguous Unicode characters

This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.

// Thin Chart.js wrapper for Blazor (see ChartJsChart.razor). Chart.js and the treemap plugin are
// loaded on first use from wwwroot/lib, so pages without charts don't pay for them.
const scripts = new Map();
function loadScript(src) {
if (!scripts.has(src)) {
scripts.set(src, new Promise((resolve, reject) => {
const script = document.createElement('script');
script.src = src;
script.onload = resolve;
script.onerror = () => reject(new Error(`${src} could not be loaded`));
document.head.appendChild(script);
}));
}
return scripts.get(src);
}
async function loadChartJs(kind) {
await loadScript('lib/chartjs/chart.umd.min.js');
if (kind === 'treemap') {
// Registers itself with the global Chart.
await loadScript('lib/chartjs-chart-treemap/chartjs-chart-treemap.min.js');
}
window.Chart.defaults.font.family = theme.font;
}
// Same look as ChartTheme.cs.
const theme = {
font: "'Helvetica Neue', Helvetica, Arial, sans-serif",
ink: '#0b0b0b',
muted: '#52514e',
grid: '#e1e0d9',
surface: '#fcfcfb'
};
// de-CH uses a typographic apostrophe; the rest of the app (Formatting.cs) uses a plain one.
const amount = new Intl.NumberFormat('de-CH', { minimumFractionDigits: 2, maximumFractionDigits: 2 });
const formatChf = value => amount.format(value).replace(/’/g, "'");
// Axis ticks default to whole numbers (CHF amounts in the hundreds/thousands); series with small
// values (e.g. CHF/kWh, well under 1) pass data.axisDecimals to avoid every tick rounding to "0".
const axisAmountFormatters = new Map();
function axisAmount(decimals) {
if (!axisAmountFormatters.has(decimals)) {
axisAmountFormatters.set(decimals, new Intl.NumberFormat('de-CH', { minimumFractionDigits: decimals, maximumFractionDigits: decimals }));
}
return axisAmountFormatters.get(decimals);
}
const formatAxis = (value, decimals = 0) => axisAmount(decimals).format(value).replace(/’/g, "'");
// Treemap tile helpers: level 0 tiles are parents (their group value is the parent id); level 1
// tiles keep the original tree items, which carry the parent id.
const parentOf = raw => raw.l === 0 ? raw.g : raw._data.children[0].p;
const isParentGroup = (raw, items) => raw.l === 0 && items.some(i => i.c);
function withAlpha(hex, alpha) {
const n = parseInt(hex.slice(1), 16);
return `rgba(${n >> 16}, ${(n >> 8) & 255}, ${n & 255}, ${alpha})`;
}
const tooltip = {
backgroundColor: '#ffffff',
borderColor: theme.grid,
borderWidth: 1,
titleColor: theme.ink,
bodyColor: theme.ink,
footerColor: theme.ink,
titleFont: { weight: 'bold' },
footerFont: { weight: 'bold' },
padding: 10,
usePointStyle: true
};
const legend = {
position: 'bottom',
labels: { usePointStyle: true, pointStyle: 'rectRounded', boxWidth: 10, color: theme.muted, font: { size: 12 } }
};
// unit/decimals default to CHF/0, so existing callers that don't pass data.unit/axisDecimals
// keep their current axis.
const amountAxis = (unit = 'CHF', decimals = 0) => ({
grid: { color: theme.grid },
border: { display: false },
title: { display: true, text: unit, color: theme.muted },
ticks: { color: theme.muted, callback: value => formatAxis(value, decimals) }
});
const categoryAxis = { grid: { display: false }, ticks: { color: theme.muted } };
// Each kind turns the data sent from Blazor into Chart.js data, and builds its options once.
// Options read the current data through state(), so update() only has to swap the data.
const kinds = {
// data: { labels, series: [{ name, color, values, clickable }], totalLine?: { name, values } };
// click key = series index. The optional line (e.g. the net result) is its own stack, so it
// shows its value instead of stacking onto the bars.
stackedBar: {
type: 'bar',
data: data => ({
labels: data.labels,
datasets: [...data.series.map(s => ({
label: s.name,
data: s.values,
backgroundColor: s.color,
hoverBackgroundColor: s.color,
borderColor: theme.surface,
borderWidth: { top: 1 },
borderRadius: 3,
stack: 'total',
clickable: s.clickable
})), ...(data.totalLine ? [{
type: 'line',
label: data.totalLine.name,
data: data.totalLine.values,
stack: 'line',
borderColor: theme.ink,
backgroundColor: theme.ink,
borderWidth: 2,
pointRadius: 2,
tension: 0.25,
order: -1
}] : [])]
}),
options: state => ({
interaction: { mode: 'index', intersect: false },
plugins: {
legend,
tooltip: {
...tooltip,
filter: item => item.parsed.y !== 0,
itemSort: (a, b) => b.parsed.y - a.parsed.y,
callbacks: {
label: item => ` ${item.dataset.label}: ${formatChf(item.parsed.y)} ${state().unit ?? 'CHF'}`,
footer: items => {
const bars = items.filter(i => i.dataset.type !== 'line');
return bars.length === items.length
? `Total: ${formatChf(bars.reduce((sum, i) => sum + i.parsed.y, 0))} ${state().unit ?? 'CHF'}`
: '';
}
}
}
},
scales: { x: { ...categoryAxis, stacked: true }, y: { ...amountAxis(state().unit ?? 'CHF', state().axisDecimals ?? 0), stacked: true } }
}),
hit: (chart, event) => {
const hit = chart.getElementsAtEventForMode(event, 'nearest', { intersect: true }, false)[0];
return hit && chart.data.datasets[hit.datasetIndex].clickable ? String(hit.datasetIndex) : null;
}
},
// data: { labels, series: [{ name, color, values (null = no data), width }] }; not clickable
line: {
type: 'line',
data: data => ({
labels: data.labels,
datasets: data.series.map(s => ({
label: s.name,
data: s.values,
borderColor: s.color,
backgroundColor: s.color,
borderWidth: s.width,
pointRadius: s.width > 2 ? 3 : 2,
pointHoverRadius: 5,
tension: 0.25,
spanGaps: false
}))
}),
options: state => ({
interaction: { mode: 'index', intersect: false },
plugins: {
legend: { ...legend, labels: { ...legend.labels, pointStyle: 'line' } },
tooltip: {
...tooltip,
filter: item => item.parsed.y !== null,
itemSort: (a, b) => b.parsed.y - a.parsed.y,
callbacks: { label: item => ` ${item.dataset.label}: ${formatChf(item.parsed.y)} ${state().unit ?? 'CHF'}` }
}
},
scales: { x: categoryAxis, y: amountAxis(state().unit ?? 'CHF', state().axisDecimals ?? 0) }
}),
hit: () => null
},
// data: { items: [{ p, c, value }], names: { id: name }, colors: { p: color }, clickable: [key] }
// p = parent id, c = child id (null for a single level); click key = "p" or "p|c"
treemap: {
type: 'treemap',
data: data => ({
datasets: [{
tree: data.items,
key: 'value',
groups: data.items.some(i => i.c) ? ['p', 'c'] : ['p'],
spacing: 1,
borderWidth: 0,
borderRadius: 3,
backgroundColor: ctx => {
if (ctx.type !== 'data') {
return 'transparent';
}
const color = data.colors[parentOf(ctx.raw)] ?? '#898781';
return withAlpha(color, isParentGroup(ctx.raw, data.items) ? 0.25 : 0.9);
},
captions: {
display: true,
color: theme.ink,
font: { weight: 'bold', size: 12 },
formatter: ctx => `${data.names[ctx.raw.g]} ${formatAxis(ctx.raw.v)}`
},
labels: {
display: true,
color: '#ffffff',
font: [{ size: 12, weight: 'bold' }, { size: 11 }],
overflow: 'hidden',
formatter: ctx => [data.names[ctx.raw.g], `${formatAxis(ctx.raw.v)} CHF`]
}
}]
}),
options: state => ({
plugins: {
legend: { display: false },
tooltip: {
...tooltip,
displayColors: false,
callbacks: {
title: items => {
const raw = items[0].raw;
const names = state().names;
return raw.l === 0 ? names[raw.g] : `${names[parentOf(raw)]} › ${names[raw.g]}`;
},
label: item => `${formatChf(item.raw.v)} CHF`
}
}
}
}),
hit: (chart, event) => {
// Deepest tile under the pointer: an account inside a subclass wins over the subclass.
const hits = chart.getElementsAtEventForMode(event, 'point', { intersect: true }, false);
const data = chart.data.datasets[0].data;
const raw = hits.map(h => data[h.index]).sort((a, b) => b.l - a.l)[0];
if (!raw) {
return null;
}
const key = raw.l === 0 ? raw.g : `${parentOf(raw)}|${raw.g}`;
return chart.$clickable?.includes(key) ? key : null;
}
}
};
/**
* Creates a chart of the given kind on the canvas and returns a handle with update/destroy.
* Clicking a clickable element calls dotNetRef.OnChartClicked(key); see the kinds above for keys.
*/
export async function createChart(canvas, kind, data, dotNetRef) {
await loadChartJs(kind);
const spec = kinds[kind];
let current = data;
const chart = new window.Chart(canvas, {
type: spec.type,
data: spec.data(current),
options: {
responsive: true,
maintainAspectRatio: false,
animation: { duration: 250 },
...spec.options(() => current),
onHover: (event, _, chart) => {
event.native.target.style.cursor = spec.hit(chart, event) !== null ? 'pointer' : 'default';
},
onClick: (event, _, chart) => {
const key = spec.hit(chart, event);
if (key !== null) {
dotNetRef.invokeMethodAsync('OnChartClicked', key);
}
}
}
});
chart.$clickable = current.clickable;
return {
update(newData) {
current = newData;
chart.$clickable = current.clickable;
chart.data = spec.data(current);
chart.update();
},
destroy() {
chart.destroy();
}
};
}