philomena/lib/philomena_web/views/stat_view.ex

38 lines
1 KiB
Elixir
Raw Permalink Normal View History

2019-11-29 23:45:44 +01:00
defmodule PhilomenaWeb.StatView do
use PhilomenaWeb, :view
2020-01-05 18:55:10 +01:00
def upload_graph(data) do
data = Enum.sort_by(data, & &1["key"])
n_buckets = length(data)
2020-01-05 19:03:43 +01:00
{
%{"doc_count" => min_docs},
%{"doc_count" => max_docs}
} = Enum.min_max_by(data, & &1["doc_count"], fn -> %{"doc_count" => 0} end)
2020-01-05 18:55:10 +01:00
graph_width = 950
graph_height = 475
bar_width = safe_div(graph_width, n_buckets)
content_tag :svg, class: "upload-stats", viewBox: "0 0 #{graph_width} #{graph_height}" do
for {datum, i} <- Enum.with_index(data) do
2020-01-05 19:05:39 +01:00
bar_height = safe_div(datum["doc_count"], max_docs - min_docs) * graph_height
2020-01-05 18:55:10 +01:00
x = i * bar_width
2020-01-11 05:20:19 +01:00
y = graph_height - bar_height
2020-01-05 18:55:10 +01:00
height = bar_height
content_tag :rect, width: bar_width, height: height, x: x, y: y, fill: "#000" do
2020-01-11 05:20:19 +01:00
content_tag(:title,
do: [datum["key_as_string"], " - ", Integer.to_string(datum["doc_count"]), " uploads"]
)
2020-01-05 18:55:10 +01:00
end
end
end
end
2020-01-05 19:03:43 +01:00
defp safe_div(_n, 0), do: 0
2020-01-05 18:55:10 +01:00
defp safe_div(n, d), do: n / d
2019-11-29 23:45:44 +01:00
end