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

71 lines
1.7 KiB
Svelte
Raw Normal View History

2020-11-03 12:50:55 +01:00
<script>
import { onMount } from "svelte"
import fetchData, { fetchSchema } from "../fetchData"
import { sortBy } from "lodash/fp"
2020-11-03 12:50:55 +01:00
import { ApexOptionsBuilder } from "./ApexOptionsBuilder"
import ApexChart from "./ApexChart.svelte"
2020-11-03 12:50:55 +01:00
export let _bb
2020-11-03 12:50:55 +01:00
export let title
export let datasource
export let labelColumn
export let valueColumn
export let height
export let width
export let color
export let dataLabels
export let animate
export let legend
export let donut
const store = _bb.store
let options
2020-11-03 12:50:55 +01:00
// Fetch data on mount
onMount(async () => {
if (!datasource || !labelColumn || !valueColumn) {
return
}
const result = (await fetchData(datasource, $store)).slice(0, 20)
const data = sortBy(row => row[labelColumn])(result)
const schema = await fetchSchema(datasource.tableId)
if (!schema || !data || !data.length) {
return
}
// Check columns are valid
if (datasource.type !== "view") {
if (schema[labelColumn] == null) {
return
}
if (schema[valueColumn] == null) {
return
}
2020-11-03 12:50:55 +01:00
}
// Initialise default chart
let builder = new ApexOptionsBuilder()
.title(title)
.type(donut ? "donut" : "pie")
.width(width)
.height(height)
.dataLabels(dataLabels)
.animate(animate)
.legend(legend)
.legendPosition("right")
// Add data if valid datasource
const series = data.map(row => parseFloat(row[valueColumn]))
builder = builder.series(series)
if (data[0][labelColumn] != null) {
builder = builder.labels(data.map(row => row[labelColumn]))
2020-11-03 12:50:55 +01:00
}
// Build chart options
options = builder.getOptions()
})
2020-11-03 12:50:55 +01:00
</script>
<ApexChart {options} />