cannery/assets/js/shot_log_chart.js

107 lines
2.5 KiB
JavaScript
Raw Normal View History

2022-11-09 21:04:57 -05:00
import { Chart, Title, Tooltip, Legend, LineController, LineElement, PointElement, TimeScale, LinearScale } from 'chart.js'
import 'chartjs-adapter-date-fns'
Chart.register(Title, Tooltip, Legend, LineController, LineElement, PointElement, TimeScale, LinearScale)
export default {
initalizeChart (el) {
const data = JSON.parse(el.dataset.chartData)
this.el.chart = new Chart(el, {
type: 'line',
data: {
datasets: [{
label: el.dataset.label,
2022-11-11 19:34:23 -05:00
data: data.map(({ date, count, label }) => ({
label,
2022-11-09 21:04:57 -05:00
x: date,
y: count
})),
2022-11-11 19:34:23 -05:00
backgroundColor: `${el.dataset.color}77`,
2022-11-09 21:04:57 -05:00
borderColor: el.dataset.color,
fill: true,
2022-11-11 19:34:23 -05:00
borderWidth: 3,
pointBorderWidth: 1
2022-11-09 21:04:57 -05:00
}]
},
options: {
elements: {
point: {
2022-11-11 19:34:23 -05:00
radius: 9,
hoverRadius: 12
2022-11-09 21:04:57 -05:00
}
},
plugins: {
legend: {
position: 'bottom',
labels: {
padding: 20
}
},
tooltip: {
displayColors: false,
callbacks: {
2022-11-11 19:34:23 -05:00
title: (contexts) => contexts.map(({ raw: { x } }) => Intl.DateTimeFormat([], { timeZone: 'Etc/UTC', dateStyle: 'short' }).format(new Date(x))),
label: ({ raw: { label } }) => label
2022-11-09 21:04:57 -05:00
}
}
},
scales: {
y: {
beginAtZero: true,
stacked: true,
grace: '15%',
ticks: {
padding: 15
}
},
x: {
type: 'time',
time: {
unit: 'day'
}
}
},
transitions: {
show: {
animations: {
x: {
from: 0
}
}
},
hide: {
animations: {
x: {
to: 0
}
}
}
}
}
})
},
2022-12-03 21:27:39 -05:00
updateChart (el) {
const data = JSON.parse(el.dataset.chartData)
this.el.chart.data = {
datasets: [{
label: el.dataset.label,
data: data.map(({ date, count, label }) => ({
label,
x: date,
y: count
})),
backgroundColor: `${el.dataset.color}77`,
borderColor: el.dataset.color,
fill: true,
borderWidth: 3,
pointBorderWidth: 1
}]
}
this.el.chart.update()
},
2022-11-09 21:04:57 -05:00
mounted () { this.initalizeChart(this.el) },
2022-12-03 21:27:39 -05:00
updated () { this.updateChart(this.el) }
2022-11-09 21:04:57 -05:00
}