feat: download chart data in csv

This commit is contained in:
Azgaar 2023-05-28 14:55:26 +04:00
parent 0b04efc90f
commit c74d38ea2f
4 changed files with 20 additions and 12 deletions

View file

@ -426,19 +426,18 @@ function renderChart({id, entity, plotBy, groupBy, sorting, type}) {
})
.flat();
const sortedData = sortData(chartData, sorting);
const colors = getColors();
const {offset, formatX = formatTicks} = plotTypeMap[type];
const $chart = createStackedBarChart(chartData, {sorting, colors, tooltip, offset, formatX});
insertChart(id, $chart, title);
const $chart = createStackedBarChart(sortedData, {colors, tooltip, offset, formatX});
insertChart(id, sortedData, $chart, title);
byId("chartsOverview__charts").lastChild.scrollIntoView();
}
// based on observablehq.com/@d3/stacked-horizontal-bar-chart
function createStackedBarChart(data, {sorting, colors, tooltip, offset, formatX}) {
const sortedData = sortData(data, sorting);
function createStackedBarChart(sortedData, {colors, tooltip, offset, formatX}) {
const X = sortedData.map(d => d.value);
const Y = sortedData.map(d => d.name);
const Z = sortedData.map(d => d.group);
@ -568,7 +567,7 @@ function createStackedBarChart(data, {sorting, colors, tooltip, offset, formatX}
return svg.node();
}
function insertChart(id, $chart, title) {
function insertChart(id, sortedData, $chart, title) {
const $chartContainer = byId("chartsOverview__charts");
const $figure = document.createElement("figure");
@ -580,7 +579,8 @@ function insertChart(id, $chart, title) {
<strong>Figure ${figureNo}</strong>. ${title}
</div>
<div>
<button data-tip="Download the chart in svg format (can open in browser or Inkscape)" class="icon-download"></button>
<button data-tip="Download chart data as a text file (.csv)" class="icon-download"></button>
<button data-tip="Download the chart in svg format (can open in browser or Inkscape)" class="icon-chart-bar"></button>
<button data-tip="Remove the chart" class="icon-trash"></button>
</div>
`;
@ -589,7 +589,14 @@ function insertChart(id, $chart, title) {
$figure.appendChild($caption);
$chartContainer.appendChild($figure);
const downloadChart = () => {
const downloadChartData = () => {
const name = `${getFileName(title)}.csv`;
const headers = "Name,Group,Value\n";
const values = sortedData.map(({name, group, value}) => `${name},${group},${value}`).join("\n");
downloadFile(headers + values, name);
};
const downloadChartSvg = () => {
const name = `${getFileName(title)}.svg`;
downloadFile($chart.outerHTML, name);
};
@ -600,7 +607,8 @@ function insertChart(id, $chart, title) {
updateDialogPosition();
};
$figure.querySelector("button.icon-download").on("click", downloadChart);
$figure.querySelector("button.icon-download").on("click", downloadChartData);
$figure.querySelector("button.icon-chart-bar").on("click", downloadChartSvg);
$figure.querySelector("button.icon-trash").on("click", removeChart);
}