discourse/app/assets/javascripts/admin/addon/components/admin-report-stacked-chart.gjs
Natalie Tay 3a04443632
FIX: Sum pageviews with number instead of string (#28596)
When the tooltip items are tooltipItem = [{parsed: {y:12} }, {parsed: {y:10} } ], reducing without a initial value as a number would result in Javascript thinking it is a string. Thanks, Javascript!

There are no tests here yet since this makes use of an external library Chart.js.
2024-08-28 19:24:57 +08:00

104 lines
2.5 KiB
Plaintext

import Component from "@glimmer/component";
import { number } from "discourse/lib/formatter";
import { makeArray } from "discourse-common/lib/helpers";
import Report from "admin/models/report";
import Chart from "./chart";
export default class AdminReportStackedChart extends Component {
get chartConfig() {
const { model } = this.args;
const chartData = makeArray(model.chartData || model.data).map((cd) => ({
label: cd.label,
color: cd.color,
data: Report.collapse(model, cd.data),
}));
const data = {
labels: chartData[0].data.mapBy("x"),
datasets: chartData.map((cd) => ({
label: cd.label,
stack: "pageviews-stack",
data: cd.data,
backgroundColor: cd.color,
})),
};
return {
type: "bar",
data,
options: {
responsive: true,
maintainAspectRatio: false,
responsiveAnimationDuration: 0,
hover: { mode: "index" },
animation: {
duration: 0,
},
plugins: {
tooltip: {
mode: "index",
intersect: false,
callbacks: {
beforeFooter: (tooltipItem) => {
const total = tooltipItem.reduce(
(sum, item) => sum + parseInt(item.parsed.y || 0, 10),
0
);
return `= ${total}`;
},
title: (tooltipItem) =>
moment(tooltipItem[0].label, "YYYY-MM-DD").format("LL"),
},
},
},
layout: {
padding: {
left: 0,
top: 0,
right: 0,
bottom: 0,
},
},
scales: {
y: [
{
stacked: true,
display: true,
ticks: {
callback: (label) => number(label),
sampleSize: 5,
maxRotation: 25,
minRotation: 25,
},
},
],
x: [
{
display: true,
gridLines: { display: false },
type: "time",
time: {
unit: Report.unitForDatapoints(data.labels.length),
},
ticks: {
sampleSize: 5,
maxRotation: 50,
minRotation: 50,
},
},
],
},
},
};
}
<template>
<Chart
@chartConfig={{this.chartConfig}}
class="admin-report-chart admin-report-stacked-chart"
/>
</template>
}