4.4 KiB · text History 154a76a
defmodule VigilWeb.ChartComponents do
  @moduledoc """
  The app's one chart form: a single-series bar chart drawn in HTML.

  One series, so no legend: the surrounding section's title names it. Thin
  bars in the theme's primary, 4px rounded tops anchored to the baseline, a
  2px gap between bars; a recessive axis (the peak and three marks along
  the bottom); a hover tooltip per bar with a hit target the full column
  tall; and the same numbers as a table (`Show as a table`) for screen
  readers and anyone who wants them. No JS.
  """
  use Phoenix.Component

  @doc """
  Bars for `points`, each `%{value:, tip:, axis:, row:}`: `tip` is the
  tooltip's text after the value, `axis` the short label used for the
  three axis marks, `row` the table's first column. DOM ids hang off `id`:
  `<id>-bars`, `<id>-bar-<i>`, `<id>-table`.
  """
  attr :id, :string, required: true
  attr :points, :list, required: true
  attr :label, :string, required: true, doc: "what the chart shows, for its aria-label"
  attr :key_header, :string, required: true
  attr :value_header, :string, required: true
  attr :format, :any, default: &__MODULE__.format_count/1
  attr :class, :string, default: "h-32"

  def bars(assigns) do
    max = assigns.points |> Enum.map(& &1.value) |> Enum.max(fn -> 0 end)
    assigns = assign(assigns, max: max, marks: axis_marks(assigns.points))

    ~H"""
    <div class="mt-4">
      <div
        class={["relative", @class]}
        role="img"
        aria-label={"#{@label}, peak #{@format.(@max)}"}
      >
        <div class="absolute inset-x-0 bottom-0 border-t border-base-300" aria-hidden="true" />
        <span
          :if={@max > 0}
          class="absolute -top-1 right-0 text-[0.65rem] tabular-nums text-base-content/50"
          aria-hidden="true"
        >
          {@format.(@max)}
        </span>
        <div class="flex h-full items-end gap-[2px]" id={"#{@id}-bars"}>
          <div
            :for={{p, i} <- Enum.with_index(@points)}
            id={"#{@id}-bar-#{i}"}
            class="group relative flex h-full flex-1 items-end"
          >
            <div
              class={[
                "w-full rounded-t-[4px] transition-colors",
                if(p.value > 0,
                  do: "bg-primary group-hover:bg-primary/80",
                  else: "bg-base-300/60"
                )
              ]}
              style={"height: #{bar_height(p.value, @max)}"}
            />
            <div class="pointer-events-none absolute bottom-full left-1/2 z-10 mb-1 hidden -translate-x-1/2 whitespace-nowrap rounded-box border border-base-300 bg-base-100 px-2 py-1 text-xs shadow-md group-hover:block">
              <span class="font-semibold tabular-nums">{@format.(p.value)}</span> {p.tip}
            </div>
          </div>
        </div>
      </div>
      <div class="mt-1 flex justify-between text-[0.65rem] text-base-content/50" aria-hidden="true">
        <span :for={p <- @marks}>{p.axis}</span>
      </div>
      <details class="mt-2 text-xs text-base-content/60">
        <summary class="cursor-pointer">Show as a table</summary>
        <table id={"#{@id}-table"} class="table table-xs mt-2">
          <thead>
            <tr>
              <th>{@key_header}</th><th class="text-right">{@value_header}</th>
            </tr>
          </thead>
          <tbody>
            <tr :for={p <- @points}>
              <td>{p.row}</td>
              <td class="text-right tabular-nums">{@format.(p.value)}</td>
            </tr>
          </tbody>
        </table>
      </details>
    </div>
    """
  end

  @doc "Hourly `{hour, count}` pairs as `bars/1` points."
  def hourly_points(hourly) do
    for {hour, n} <- hourly do
      %{
        value: n,
        tip: "at #{Calendar.strftime(hour, "%H:00")} UTC",
        axis: Calendar.strftime(hour, "%H:00"),
        row: Calendar.strftime(hour, "%Y-%m-%d %H:00")
      }
    end
  end

  defp bar_height(n, _max) when n <= 0, do: "2px"
  defp bar_height(n, max), do: "max(3px, #{Float.round(n / max * 100, 2)}%)"

  defp axis_marks([]), do: []

  defp axis_marks(points) do
    n = length(points)
    [Enum.at(points, 0), Enum.at(points, div(n, 2)), List.last(points)]
  end

  @doc "A count, compacted for an axis or tooltip: 12, 12k, 1.2M."
  def format_count(n) when n >= 1_000_000, do: "#{Float.round(n / 1_000_000, 1)}M"
  def format_count(n) when n >= 10_000, do: "#{div(n, 1000)}k"
  def format_count(n), do: to_string(n)
end