Class: Asciidoctor::Chart::Converter::Html5ChartjsConverter

Inherits:
Base
  • Object
show all
Defined in:
lib/asciidoctor/chart/converter/chartjs.rb

Constant Summary collapse

CSS_VALUE_UNIT_RX =
/^([+-]?(?:\d+|\d*\.\d+))([a-z]*|%)$/.freeze
DEFAULT_COLORS =
[{ r: 220, g: 220, b: 220 }, { r: 151, g: 187, b: 205 }].freeze

Instance Method Summary collapse

Methods inherited from Base

#handles?

Instance Method Details

#convert_line_chart(node) ⇒ Object



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
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
# File 'lib/asciidoctor/chart/converter/chartjs.rb', line 10

def convert_line_chart node
  data, labels = prepare_data node
  datasets = data.map do |set|
    color = DEFAULT_COLORS[data.index(set) % 2]
    color_rgba = "rgba(#{color[:r]},#{color[:g]},#{color[:b]},1.0)"
    <<~JSON
      {
        borderColor: "#{color_rgba}",
        backgroundColor: "#{color_rgba}",
        fill: false,
        tension: 0.1,
        data: #{set.to_s}
      }
    JSON
  end.join ','

  chart_id = node.attr 'id'
  inline_styles = []
  if (chart_height = get_height node)
    inline_styles.push("height: #{chart_height}")
  end
  if (chart_width = get_width node)
    inline_styles.push("max-width: #{chart_width}")
  end
  maintain_aspect_ratio = chart_height.nil? && chart_width.nil?
  title_element = node.title? ? %(\n  <div class="title">#{node.captioned_title}</div>) : ''
  <<~HTML
    <div class="chartblock">
      <div class="content chartjs-content" style="#{inline_styles.join('; ')}">
        <canvas id="#{chart_id}"></canvas>
      </div>#{title_element}
    </div>
    <script>
    window.addEventListener('load', function(event) {
      var data = {
        labels: #{labels.to_s},
        datasets: [#{datasets}]
      }
      var chart = new Chart(document.getElementById("#{chart_id}").getContext("2d"), {
        type: 'line',
        data: data,
        options: {
          interaction: {
            mode: 'index'
          },
          responsive : true,
          maintainAspectRatio: #{maintain_aspect_ratio},
          plugins: {
            legend: {
              display: false
            }
          }
        }
      })
    })
    </script>
  HTML
end

#prepare_data(node) ⇒ Object



69
70
71
72
73
74
75
76
# File 'lib/asciidoctor/chart/converter/chartjs.rb', line 69

def prepare_data node
  raw_data = node.attr 'data-raw', []
  return [[], []] if raw_data.length <= 1 # question: should we warn?

  labels = raw_data[0]
  raw_data.shift
  [raw_data, labels]
end