aboutsummaryrefslogtreecommitdiff
path: root/layouts/shortcodes/chart.html
blob: 2198b63b7b5c91e8b8cece51457f4cd279260396 (plain) (blame)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51

{{- $id := printf "chart-%d" (now.UnixNano) -}}
{{- $type := .Get "type" | default "bar" -}}
{{- $preset := .Get "preset" -}}
{{- $title := .Get "title" -}}
{{- $data := .Get "data" -}}
{{- $options := .Get "options" | default "{}" -}}

{{/* Load chart presets */}}
{{- $presets := site.Data.chart_presets -}}

{{/* Handle preset-based charts */}}
{{- if $preset -}}
  {{- $presetData := index $presets.charts $preset -}}
  {{- if $presetData -}}
    {{- $data = $presetData.data | jsonify -}}
    {{- if and $title (not (index $presetData.options.plugins.title "text")) -}}
      {{- $presetData = merge $presetData (dict "options" (merge $presetData.options (dict "plugins" (merge $presetData.options.plugins (dict "title" (dict "text" $title)))))) -}}
    {{- end -}}
    {{- $options = $presetData.options | jsonify -}}
  {{- end -}}
{{- end -}}

<div class="chart-container mb-5">
  <canvas id="{{ $id }}"></canvas>
</div>

<script src="https://cdn.jsdelivr.net/npm/chart.js"></script>
<script>
  document.addEventListener('DOMContentLoaded', function() {
    const ctx = document.getElementById('{{ $id }}').getContext('2d');
    new Chart(ctx, {
      type: '{{ $type }}',
      data: {{ $data | safeJS }},
      options: Object.assign({
        responsive: true,
        maintainAspectRatio: false,
        plugins: {
          legend: { position: 'top' }
        }
      }, {{ $options | safeJS }})
    });
  });
</script>

<style>
  .chart-container {
    position: relative;
    height: 400px;
    width: 100%;
  }
</style>