6.9 KiB · text History bbb2a48
defmodule VigilWeb.IssueListComponents do
  @moduledoc """
  The small pieces of the issue list (`VigilWeb.IssueLive.Index`): a
  level marker, an hourly sparkline, relative times, compact counts, the
  status badge, the assignee's initial, and the bulk-action toolbar.
  """
  use VigilWeb, :html

  @doc "A coloured bar at a row's edge for the issue's level (`fatal` … `debug`)."
  attr :level, :string, required: true

  def level_marker(assigns) do
    ~H"""
    <span
      class={["block h-9 w-1 shrink-0 rounded-full", level_class(@level)]}
      title={"Level: #{@level}"}
      aria-label={"Level: #{@level}"}
      role="img"
    />
    """
  end

  defp level_class("fatal"), do: "bg-error ring-2 ring-error/30"
  defp level_class("error"), do: "bg-error"
  defp level_class("warning"), do: "bg-warning"
  defp level_class("info"), do: "bg-info"
  defp level_class(_), do: "bg-base-content/30"

  @doc """
  Events per hour as bars, oldest first, in inline SVG. Zero hours keep a
  faint baseline so the shape of a quiet day still reads.
  """
  attr :id, :string, required: true
  attr :counts, :list, required: true
  attr :class, :string, default: nil

  def sparkline(assigns) do
    counts = assigns.counts
    max = Enum.max(counts, fn -> 0 end)

    bars =
      counts
      |> Enum.with_index()
      |> Enum.map(fn {n, i} ->
        h = if n > 0, do: max(2, round(n / max * 22)), else: 1
        %{x: i * 4, y: 24 - h, h: h, zero?: n == 0}
      end)

    assigns =
      assign(assigns,
        bars: bars,
        total: Enum.sum(counts),
        width: max(length(counts) * 4 - 1, 1)
      )

    ~H"""
    <svg
      id={@id}
      viewBox={"0 0 #{@width} 24"}
      width={@width}
      height="24"
      role="img"
      aria-label={"#{@total} #{plural(@total, "event")} in the last #{length(@counts)} hours"}
      class={["overflow-visible", @class]}
    >
      <title>{@total} {plural(@total, "event")} in the last {length(@counts)} hours</title>
      <rect
        :for={bar <- @bars}
        x={bar.x}
        y={bar.y}
        width="3"
        height={bar.h}
        rx="0.5"
        class={if(bar.zero?, do: "fill-base-content/15", else: "fill-primary/70")}
      />
    </svg>
    """
  end

  @doc "A `<time>` reading like `5m ago`, with the full timestamp on hover."
  attr :at, :any, required: true
  attr :id, :string, default: nil
  attr :class, :string, default: nil

  def relative_time(assigns) do
    ~H"""
    <time
      id={@id}
      datetime={@at && DateTime.to_iso8601(@at)}
      title={@at && Calendar.strftime(@at, "%Y-%m-%d %H:%M:%S UTC")}
      class={@class}
    >
      {ago(@at)}
    </time>
    """
  end

  @doc "How long ago `at` was, briefly: `just now`, `12m ago`, `3h ago`, `5d ago`, or a date."
  def ago(nil), do: "never"

  def ago(at, now \\ DateTime.utc_now()) do
    diff = DateTime.diff(now, at)

    cond do
      diff < 45 -> "just now"
      diff < 3600 -> "#{max(div(diff, 60), 1)}m ago"
      diff < 86_400 -> "#{div(diff, 3600)}h ago"
      diff < 30 * 86_400 -> "#{div(diff, 86_400)}d ago"
      true -> Calendar.strftime(at, "%b %-d, %Y")
    end
  end

  @doc "A count shortened for a narrow column: `999`, `1.2k`, `34k`, `1.5M`."
  def compact(n) when n < 1000, do: Integer.to_string(n)
  def compact(n) when n < 10_000, do: "#{Float.round(n / 1000, 1)}k"
  def compact(n) when n < 1_000_000, do: "#{div(n, 1000)}k"
  def compact(n), do: "#{Float.round(n / 1_000_000, 1)}M"

  @doc "`word` with an `s` unless `n` is one."
  def plural(1, word), do: word
  def plural(_, word), do: word <> "s"

  @doc "A badge for resolved and ignored issues; nothing for unresolved ones."
  attr :status, :atom, required: true

  def status_badge(%{status: :unresolved} = assigns), do: ~H""

  def status_badge(assigns) do
    ~H"""
    <span class={[
      "badge badge-sm gap-1",
      if(@status == :resolved, do: "badge-success badge-soft", else: "badge-ghost")
    ]}>
      <.icon
        name={if(@status == :resolved, do: "hero-check-micro", else: "hero-eye-slash-micro")}
        class="size-3"
      />
      {@status}
    </span>
    """
  end

  @doc "The assignee's initial in a circle, or a dashed placeholder."
  attr :user, :any, required: true

  def assignee(%{user: nil} = assigns) do
    ~H"""
    <span
      class="inline-flex size-6 items-center justify-center rounded-full border border-dashed border-base-content/25 text-base-content/30"
      title="Unassigned"
    >
      <.icon name="hero-user-micro" class="size-3" />
    </span>
    """
  end

  def assignee(assigns) do
    ~H"""
    <span
      class="inline-flex size-6 items-center justify-center rounded-full bg-primary/15 text-xs font-semibold uppercase text-primary"
      title={"Assigned to #{@user.email}"}
    >
      {String.first(@user.email)}
    </span>
    """
  end

  @doc """
  What can be done to the selected issues. Delete shows only to callers
  holding `project:admin` (admins and up), and asks first.
  """
  attr :count, :integer, required: true
  attr :can_delete, :boolean, default: false

  def bulk_actions(assigns) do
    ~H"""
    <div
      id="bulk-actions"
      class="flex flex-wrap items-center gap-1"
      role="toolbar"
      aria-label="Selected issues"
    >
      <span id="selected-count" class="mr-2 text-sm font-medium">
        {@count} selected
      </span>
      <.bulk_button id="bulk-resolve" action="resolve" icon="hero-check-micro">
        Resolve
      </.bulk_button>
      <.bulk_button id="bulk-ignore" action="ignore" icon="hero-eye-slash-micro">
        Ignore
      </.bulk_button>
      <.bulk_button id="bulk-unresolve" action="unresolve" icon="hero-arrow-uturn-left-micro">
        Unresolve
      </.bulk_button>
      <.bulk_button id="bulk-assign-me" action="assign_me" icon="hero-user-micro">
        Assign to me
      </.bulk_button>
      <button
        :if={@can_delete}
        type="button"
        id="bulk-delete"
        class="btn btn-ghost btn-xs text-error phx-click-loading:opacity-50"
        phx-click="bulk"
        phx-value-action="delete"
        phx-disable-with="Deleting…"
        data-confirm={"Delete #{@count} #{plural(@count, "issue")}? Their events go too."}
      >
        <.icon name="hero-trash-micro" class="size-3.5" /> Delete
      </button>
      <button
        type="button"
        id="bulk-clear"
        class="btn btn-ghost btn-xs text-base-content/60"
        phx-click="clear_selection"
      >
        Clear
      </button>
    </div>
    """
  end

  attr :id, :string, required: true
  attr :action, :string, required: true
  attr :icon, :string, required: true
  slot :inner_block, required: true

  defp bulk_button(assigns) do
    ~H"""
    <button
      type="button"
      id={@id}
      class="btn btn-ghost btn-xs transition hover:bg-base-200 phx-click-loading:opacity-50"
      phx-click="bulk"
      phx-value-action={@action}
      phx-disable-with="Working…"
    >
      <.icon name={@icon} class="size-3.5" /> {render_slot(@inner_block)}
    </button>
    """
  end
end