Last active
January 1, 2022 18:30
-
-
Save alvincrespo/24fc433b70829eef7c2eb90a1a216aa1 to your computer and use it in GitHub Desktop.
Chart.js Controller for Rails
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
/* | |
* Template Usage | |
* <div data-controller="chart"> | |
* <canvas id="element" width="400" height="400"></canvas> | |
* </div> | |
* | |
*/ | |
/* | |
* Sample Data Structure | |
* [ | |
* { | |
* "id": 4, | |
* "name": "Height", | |
* "value": "2", | |
* "unit": "in (inches)", | |
* "created_at": "2021-12-01T14:13:58.590Z", | |
* "updated_at": "2021-12-01T14:13:58.590Z" | |
* }, | |
* { | |
* "id": 3, | |
* "name": "Height", | |
* "value": "4", | |
* "unit": "in (inches)", | |
* "created_at": "2021-12-10T14:13:44.430Z", | |
* "updated_at": "2021-12-10T14:13:44.430Z" | |
* }, | |
* { | |
* "id": 2, | |
* "name": "Height", | |
* "value": "6", | |
* "unit": "in (inches)", | |
* "created_at": "2021-12-20T14:13:44.430Z", | |
* "updated_at": "2021-12-20T14:13:44.430Z" | |
* } | |
* ] | |
*/ | |
import { Controller } from "@hotwired/stimulus"; | |
import Chart from 'chart.js/auto'; | |
export default class ChartController extends Controller { | |
static ELEMENT_ID = 'element'; | |
static DEFAULT_OPTIONS = { responsive: true, maintainAspectRatio: false }; | |
connect() { | |
this.render(); | |
} | |
render() { | |
if (!this.ele) return; | |
const ctx = this.ele.getContext('2d'); | |
this.graph = new Chart(ctx, { type: 'line', data: this.data, options: this.options }); | |
} | |
get ele() { | |
return this._ele = this._ele || document.getElementById(ChartController.ELEMENT_ID); | |
} | |
get metrics() { | |
return this._metrics = this._metrics || JSON.parse(document.querySelector('[data-metrics-type]').dataset.metrics); | |
} | |
get options() { | |
return ChartController.DEFAULT_OPTIONS; | |
} | |
get data() { | |
return { labels: this.labels, datasets: this.datasets }; | |
} | |
get labels() { | |
return this._labels = this._labels || this.metrics.map((m) => new Date(m.updated_at).toDateString()); | |
} | |
get datasets() { | |
return [{ | |
label: 'Height (in)', | |
data: this.metrics.map((m) => parseInt(m.value, 10)), | |
fill: false, | |
borderColor: 'rgb(75, 192, 192)', | |
tension: 0.1 | |
}]; | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment