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

104 lines
2.6 KiB
Svelte
Raw Normal View History

<script>
import { onMount } from "svelte"
import {
fetchDatasource,
fetchTableDefinition,
} from "@budibase/component-sdk"
import { ApexOptionsBuilder } from "./ApexOptionsBuilder"
import ApexChart from "./ApexChart.svelte"
import { isEmpty } from "lodash/fp"
2020-11-03 15:32:21 +01:00
// Common props
export let _bb
export let title
export let datasource
export let labelColumn
export let valueColumns
export let xAxisLabel
export let yAxisLabel
export let height
export let width
export let color
export let animate
export let dataLabels
export let curve
export let legend
2020-11-03 15:32:21 +01:00
export let yAxisUnits
2020-11-05 14:37:28 +01:00
export let palette
2020-11-03 15:32:21 +01:00
// Area specific props
export let area
export let stacked
export let gradient
const store = _bb.store
let options
// Fetch data on mount
onMount(async () => {
const allCols = [labelColumn, ...(valueColumns || [])]
if (isEmpty(datasource) || allCols.find(x => x == null)) {
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 reducer = row => (valid, column) => valid && row[column] != null
const hasAllColumns = row => allCols.reduce(reducer(row), true)
2020-11-04 15:21:48 +01:00
const data = result
.filter(row => hasAllColumns(row))
2020-11-04 15:21:48 +01:00
.slice(0, 100)
.sort((a, b) => (a[labelColumn] > b[labelColumn] ? 1 : -1))
if (!schema || !data.length) {
options = false
return
}
// Initialise default chart
let builder = new ApexOptionsBuilder()
.title(title)
2020-11-03 15:32:21 +01:00
.type(area ? "area" : "line")
.width(width)
.height(height)
.xLabel(xAxisLabel)
.yLabel(yAxisLabel)
.dataLabels(dataLabels)
.animate(animate)
.curve(curve.toLowerCase())
2020-11-03 15:32:21 +01:00
.gradient(gradient)
.stacked(stacked)
.legend(legend)
2020-11-03 15:32:21 +01:00
.yUnits(yAxisUnits)
2020-11-05 14:37:28 +01:00
.palette(palette)
// Add data
let useDates = false
if (datasource.type !== "view" && schema[labelColumn]) {
const labelFieldType = schema[labelColumn].type
builder = builder.xType(labelFieldType)
useDates = labelFieldType === "datetime"
}
const series = valueColumns.map(column => ({
name: column,
data: data.map(row => {
if (!useDates) {
return row[column]
} else {
return [row[labelColumn], row[column]]
}
}),
}))
builder = builder.series(series)
2020-11-04 15:21:48 +01:00
if (!useDates) {
builder = builder.categories(data.map(row => row[labelColumn]))
}
// Build chart options
options = builder.getOptions()
})
</script>
<ApexChart {options} />