/
chartkick.ex
93 lines (84 loc) · 2.84 KB
/
chartkick.ex
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
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
defmodule Chartkick do
require EEx
@json_serializer Poison
gen_chart_fn = fn (chart_type) ->
def unquote(
chart_type
|> Macro.underscore
|> String.to_atom
)(data_source, options \\ []) do
chartkick_chart(unquote(chart_type), data_source, options)
end
end
Enum.map(
~w(LineChart PieChart BarChart AreaChart ColumnChart ComboChart GeoChart ScatterChart Timeline),
gen_chart_fn
)
def chartkick_chart(klass, data_source, options \\ []) do
id = Keyword.get_lazy(options, :id, &UUID.uuid4/0)
height = Keyword.get(options, :height, "300px")
width = Keyword.get(options, :width, "100%")
only = Keyword.get(options, :only)
defer = Keyword.get(options, :defer, false)
case only do
:html -> chartkick_tag(id, height, width)
:script -> chartkick_script(klass, id, data_source, options, defer)
_ -> """
#{ chartkick_tag(id, height, width) }
#{ chartkick_script(klass, id, data_source, options, defer) }
"""
end
end
EEx.function_from_string(
:def,
:chartkick_script,
~s[<script type="text/javascript">
<%= if defer do
chartkick_defer_create_js(klass, id, data_source, options)
else
chartkick_create_js(klass, id, data_source, options)
end
%>
</script>],
~w(klass id data_source options defer)a
)
EEx.function_from_string(
:def,
:chartkick_tag,
~s[<div id="<%= id %>" style="width: <%= width %>; height: <%= height %>; text-align: center; color: #999; line-height: <%= height %>; font-size: 14px; font-family: 'Lucida Grande', 'Lucida Sans Unicode', Verdana, Arial, Helvetica, sans-serif;">Loading...</div>],
~w(id height width)a
)
EEx.function_from_string(
:def,
:chartkick_create_js,
~s[new Chartkick.<%= klass %>('<%= id %>', <%= data_source %>, <%= options_json(options) %>);],
~w(klass id data_source options)a
)
EEx.function_from_string(
:def,
:chartkick_defer_create_js,
~s[
(function() {
var createChart = function() { <%= chartkick_create_js(klass, id, data_source, options) %> };
if (window.addEventListener) {
window.addEventListener("load", createChart, true);
} else if (window.attachEvent) {
window.attachEvent("onload", createChart);
} else {
createChart();
}
})();
],
~w(klass id data_source options)a
)
@options ~w(colors curve dataset decimal discrete donut download label legend library max messages min points prefix refresh stacked suffix thousands title xtitle xtype ytitle)a
defp options_json(opts) when is_list(opts) do
opts
|> Keyword.take(@options)
|> Enum.into(%{})
|> @json_serializer.encode!()
end
defp options_json(opts) when is_bitstring(opts) do
opts
end
end