baseddata.io/layouts/partials/chart.html

97 lines
3.0 KiB
HTML
Raw Normal View History

2024-08-06 12:04:37 +01:00
<script src="https://cdn.jsdelivr.net/npm/echarts@5.5.1/dist/echarts.min.js"></script>
2024-08-08 14:28:50 +01:00
<section class="chart-container">
2024-08-14 19:48:58 +01:00
<div id="chart-modifiers"></div>
2024-08-08 14:28:50 +01:00
<div id="chart">
<script>
chartData = [];
function createChart(
id,
endpoint,
chartType,
xAxisField,
yAxisField,
sortField = null,
scaleChart = false,
) {
async function fetchDataForChart(query, valueId) {
try {
const apiEndpoint = `${apiURL}/${endpoint}?query=${query}`;
const response = await fetch(apiEndpoint);
if (!response.ok) {
throw new Error(`HTTP error! status: ${response.status}`);
}
const fetchedData = await response.json();
const newData = fetchedData.reduce((acc, item) => {
const objectId = item[valueId];
if (!acc[objectId]) {
acc[objectId] = [];
}
acc[objectId].push([item[xAxisField], item[yAxisField]]);
return acc;
}, {});
chartData = { ...chartData, ...newData };
updateChart();
} catch (error) {
console.error("Fetching data failed:", error);
}
}
function updateChart() {
console.log(chartData);
let chartDataMap = new Map();
for (let objectId in chartData) {
chartDataMap.set(objectId, chartData[objectId]);
}
var chartDom = document.getElementById("chart");
var myChart = echarts.init(chartDom);
// // Sort the data by year
// if (sortField) {
// data.sort((a, b) => a[sortField] - b[sortField]);
// }
var option = {
xAxis: {
type: "category",
},
yAxis: {
scale: scaleChart,
type: "value",
},
series: Array.from(chartDataMap.entries()).map(([name, data]) => ({
name,
type: chartType,
data,
showSymbol: false,
})),
};
myChart.setOption(option, true);
}
document.addEventListener("rowSelected", (event) => {
console.log(
"Row selected:",
event.detail.row.offsetParent.id,
event.detail.row.value,
event.detail.valueId,
event.detail.selectableRows,
);
query = `{'country_with_parent': '${event.detail.row.value}'}`;
fetchDataForChart(query, event.detail.valueId);
});
document.addEventListener("rowDeselected", (event) => {
console.log(
"Row deselected:",
event.detail.row.offsetParent.id,
event.detail.row.value,
);
delete chartData[event.detail.row.value];
updateChart()
});
}
</script>
2024-08-08 14:28:50 +01:00
</div>
</section>
2024-08-01 14:06:16 +01:00
<script src="/js/chart-params.js"></script>