budibase/packages/standard-components/src/Chart/Bar.svelte

65 lines
1.6 KiB
Svelte
Raw Normal View History

2020-07-26 12:54:55 +02:00
<script>
2020-07-28 15:19:46 +02:00
import { onMount } from "svelte"
import { chart } from "svelte-apexcharts"
import fetchData from "../fetchData"
import { isEmpty } from "lodash/fp"
import { ApexOptionsBuilder } from "./ApexOptionsBuilder"
2020-07-26 12:54:55 +02:00
export let datasource
export let nameLabel
export let valueLabel
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-07-26 12:54:55 +02:00
let data
$: options = getChartOptions(data)
2020-07-26 12:54:55 +02:00
// Fetch data on mount
2020-08-04 14:55:26 +02:00
onMount(async () => {
if (!isEmpty(datasource)) {
data = await fetchData(datasource)
2020-07-28 15:19:46 +02:00
}
})
function getChartOptions(rows = []) {
// Initialise default chart
let builder = new ApexOptionsBuilder()
.type("bar")
.color(color)
.width(width)
.height(height)
.xLabel(xAxisLabel)
.yLabel(yAxisLabel)
.horizontal(horizontal)
.dataLabels(dataLabels)
.animate(animate)
2020-07-28 15:19:46 +02:00
// Add data if valid datasource
if (rows && rows.length) {
rows = rows.slice(0, 50)
if (!isEmpty(nameLabel) && !isNaN(rows[0][valueLabel])) {
builder = builder.series([
{
name: valueLabel,
data: rows.map(row => row[valueLabel]),
},
])
}
if (!isEmpty(nameLabel)) {
builder = builder.categories(rows.map(row => row[nameLabel]))
}
2020-07-28 15:19:46 +02:00
}
// Build chart options
return builder.getOptions()
2020-07-28 15:19:46 +02:00
}
2020-07-26 12:54:55 +02:00
</script>
<div use:chart={options} />