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

70 lines
1.7 KiB
Svelte
Raw Normal View History

2020-11-03 12:50:55 +01:00
<script>
import { onMount } from "svelte"
import {
fetchDatasource,
fetchTableDefinition,
} from "@budibase/component-sdk"
2020-11-03 12:50:55 +01:00
import { ApexOptionsBuilder } from "./ApexOptionsBuilder"
import ApexChart from "./ApexChart.svelte"
import { isEmpty } from "lodash/fp"
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
2020-11-05 14:37:28 +01:00
export let palette
2020-11-03 12:50:55 +01:00
const store = _bb.store
let options
2020-11-03 12:50:55 +01:00
// Fetch data on mount
onMount(async () => {
if (isEmpty(datasource) || !labelColumn || !valueColumn) {
options = false
return
}
2020-11-04 15:21:48 +01:00
// Fetch, filter and sort data
const schema = (await fetchTableDefinition(datasource.tableId)).schema
const result = await fetchDatasource(datasource)
2020-11-04 15:21:48 +01:00
const data = result
.filter(row => row[labelColumn] != null && row[valueColumn] != null)
.slice(0, 20)
.sort((a, b) => (a[labelColumn] > b[labelColumn] ? 1 : -1))
if (!schema || !data.length) {
options = false
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")
2020-11-05 14:37:28 +01:00
.palette(palette)
2020-11-03 12:50:55 +01:00
// Add data if valid datasource
const series = data.map(row => parseFloat(row[valueColumn]))
2020-11-04 15:21:48 +01:00
const labels = data.map(row => row[labelColumn])
builder = builder.series(series).labels(labels)
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} />