2020-07-26 12:54:55 +02:00
|
|
|
<script>
|
2020-07-28 15:19:46 +02:00
|
|
|
import { onMount } from "svelte"
|
2020-11-02 16:32:37 +01:00
|
|
|
import { chart } from "svelte-apexcharts"
|
|
|
|
import fetchData from "../fetchData"
|
2020-11-03 10:43:45 +01:00
|
|
|
import { isEmpty, sortBy } from "lodash/fp"
|
2020-11-02 16:32:37 +01:00
|
|
|
import { ApexOptionsBuilder } from "./ApexOptionsBuilder"
|
2020-07-26 12:54:55 +02:00
|
|
|
|
2020-11-03 10:43:45 +01:00
|
|
|
export let title
|
2020-11-02 16:32:37 +01:00
|
|
|
export let datasource
|
2020-11-03 10:43:45 +01:00
|
|
|
export let labelColumn
|
|
|
|
export let valueColumns
|
2020-11-02 16:32:37 +01:00
|
|
|
export let xAxisLabel
|
|
|
|
export let yAxisLabel
|
|
|
|
export let height
|
|
|
|
export let width
|
|
|
|
export let color
|
|
|
|
export let horizontal
|
|
|
|
export let dataLabels
|
|
|
|
export let animate
|
2020-11-03 10:43:45 +01:00
|
|
|
export let legend
|
2020-11-03 10:48:35 +01:00
|
|
|
export let stacked
|
2020-07-26 12:54:55 +02:00
|
|
|
|
2020-11-02 16:32:37 +01:00
|
|
|
let data
|
|
|
|
$: options = getChartOptions(data)
|
2020-07-26 12:54:55 +02:00
|
|
|
|
2020-11-02 16:32:37 +01:00
|
|
|
// Fetch data on mount
|
2020-08-04 14:55:26 +02:00
|
|
|
onMount(async () => {
|
2020-08-26 18:03:30 +02:00
|
|
|
if (!isEmpty(datasource)) {
|
2020-11-03 10:43:45 +01:00
|
|
|
const result = (await fetchData(datasource)).slice(0, 20)
|
|
|
|
data = sortBy(row => row[labelColumn])(result)
|
2020-07-28 15:19:46 +02:00
|
|
|
}
|
|
|
|
})
|
|
|
|
|
2020-11-02 16:32:37 +01:00
|
|
|
function getChartOptions(rows = []) {
|
|
|
|
// Initialise default chart
|
|
|
|
let builder = new ApexOptionsBuilder()
|
2020-11-03 10:43:45 +01:00
|
|
|
.title(title)
|
2020-11-02 16:32:37 +01:00
|
|
|
.type("bar")
|
|
|
|
.width(width)
|
|
|
|
.height(height)
|
|
|
|
.xLabel(xAxisLabel)
|
|
|
|
.yLabel(yAxisLabel)
|
|
|
|
.horizontal(horizontal)
|
|
|
|
.dataLabels(dataLabels)
|
|
|
|
.animate(animate)
|
2020-11-03 10:43:45 +01:00
|
|
|
.legend(legend)
|
2020-11-03 10:48:35 +01:00
|
|
|
.stacked(stacked)
|
2020-07-28 15:19:46 +02:00
|
|
|
|
2020-11-02 16:32:37 +01:00
|
|
|
// Add data if valid datasource
|
|
|
|
if (rows && rows.length) {
|
2020-11-03 10:43:45 +01:00
|
|
|
if (valueColumns && valueColumns.length) {
|
|
|
|
const series = valueColumns.map(column => ({
|
|
|
|
name: column,
|
|
|
|
data: rows.map(row => parseFloat(row[column])),
|
|
|
|
}))
|
|
|
|
builder = builder.series(series)
|
2020-11-02 16:32:37 +01:00
|
|
|
}
|
2020-11-03 10:43:45 +01:00
|
|
|
if (!isEmpty(rows[0][labelColumn])) {
|
|
|
|
builder = builder.categories(rows.map(row => row[labelColumn]))
|
2020-11-02 16:32:37 +01:00
|
|
|
}
|
2020-07-28 15:19:46 +02:00
|
|
|
}
|
|
|
|
|
2020-11-02 16:32:37 +01:00
|
|
|
// Build chart options
|
|
|
|
return builder.getOptions()
|
2020-07-28 15:19:46 +02:00
|
|
|
}
|
2020-07-26 12:54:55 +02:00
|
|
|
</script>
|
|
|
|
|
2020-11-02 16:32:37 +01:00
|
|
|
<div use:chart={options} />
|