Last active
June 3, 2024 13:38
-
-
Save smitmartijn/0dc3163bf4c25224be29e6adff538842 to your computer and use it in GitHub Desktop.
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
import { Controller } from "@hotwired/stimulus" | |
export default class extends Controller { | |
static targets = [ "canvas" ] | |
static values = { | |
numberOfRows: Number, | |
labels: Array, | |
data: Array | |
} | |
connect() { | |
this.createSparklineChart(); | |
} | |
createSparklineChart() { | |
// don't recreate when the chart already exists | |
if (this.chart) { | |
return this.chart; | |
} | |
const ctx = this.canvasTarget.getContext('2d'); | |
this.chart = new Chart(ctx, { | |
type: 'line', | |
data: { | |
labels: this.labelsValue, | |
datasets: [ | |
{ | |
data: this.dataValue, | |
borderColor: '#2A3E51', | |
borderWidth: 1, | |
pointRadius: 0, | |
fill: true, | |
backgroundColor: 'rgba(42,62,81, 0.3)' | |
} | |
] | |
}, | |
options: { | |
plugins: { | |
legend: { | |
display: false | |
}, | |
tooltip: { | |
enabled: false | |
} | |
}, | |
scales: { | |
y: { | |
display: false | |
}, | |
x: { | |
display: false | |
} | |
}, | |
responsive: false | |
} | |
}); | |
if (this.numberOfRowsValue == 0) { | |
this.canvasTarget.style.display = 'none'; | |
} | |
return this.chart; | |
} | |
} |
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
<canvas id="<%= @canvas_id %>" | |
height="<%= @height %>" | |
width="200" | |
data-controller="chart-sparkline" | |
data-chart-sparkline-target="canvas" | |
data-chart-sparkline-labels-value="<%= raw chart_labels.to_json %>" | |
data-chart-sparkline-data-value="<%= raw chart_data.to_json %>" | |
data-chart-sparkline-number-of-rows-value="<%= number_of_rows %>" | |
data-action="load->chart-sparkline#createSparklineChart"> | |
</canvas> |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment