baseddata.io/layouts/partials/chart.html

97 lines
2.8 KiB
HTML
Raw Permalink 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-09-23 17:46:59 +01:00
<script>
chartData = [];
function createChart(
id,
endpoint,
chartType,
xAxisField,
yAxisField,
sortField = null,
scaleChart = false,
xAxisType = "time",
formatValueDecimalPlaces = null
2024-09-23 17:46:59 +01:00
) {
async function fetchDataForChart(query, valueId) {
try {
const apiEndpoint = `${apiURL}/${endpoint}?${query}`;
const response = await fetch(apiEndpoint);
if (!response.ok) {
throw new Error(`HTTP error! status: ${response.status}`);
}
2024-09-23 17:46:59 +01:00
const fetchedData = await response.json();
const newData = fetchedData.reduce((acc, item) => {
const objectId = item[valueId];
if (!acc[objectId]) {
acc[objectId] = [];
}
2024-09-23 17:46:59 +01:00
acc[objectId].push([item[xAxisField], item[yAxisField]]);
return acc;
}, {});
chartData = { ...chartData, ...newData };
updateChart();
} catch (error) {
console.error("Fetching data failed:", error);
}
}
2024-09-23 17:46:59 +01:00
function updateChart() {
let chartDataMap = new Map();
for (let objectId in chartData) {
chartDataMap.set(objectId, chartData[objectId]);
}
2024-09-23 20:11:25 +01:00
var chartDom = document.getElementById(`${id}`);
2024-09-23 17:46:59 +01:00
var myChart = echarts.init(chartDom);
2024-09-23 17:46:59 +01:00
var option = {
tooltip: {
...tooltip,
valueFormatter(value, index) {
return formatValueDecimalPlaces == null ? value : nFormatter(value, formatValueDecimalPlaces);
2024-09-23 17:46:59 +01:00
},
},
xAxis: {
type: xAxisType,
2024-09-23 17:46:59 +01:00
},
yAxis: {
scale: scaleChart,
type: "value",
},
series: Array.from(chartDataMap.entries()).map(([name, data]) => ({
name,
type: chartType,
data,
showSymbol: false,
})),
};
2024-09-23 17:46:59 +01:00
myChart.setOption(option, true);
}
2024-09-23 20:11:25 +01:00
// listen for filter events for this target
document.addEventListener("filterChange", function (event) {
tableId = document.getElementById(id).id;
console.log(event.detail);
eventDetail = event.detail;
if (eventDetail.filterActions.includes("refresh")) {
chartData = [];
updateChart();
} else {
if (eventDetail.filterTargets.includes(tableId)) {
if (eventDetail.filterActions.includes("selected")) {
valueId = eventDetail.filterId;
let selectedRow = {
[valueId]: eventDetail.filterValue,
};
query = queryConstructor(selectedRow);
fetchDataForChart(query, valueId);
} else {
delete chartData[eventDetail.filterValue];
updateChart();
}
}
}
2024-09-23 17:46:59 +01:00
});
}
</script>