33.7 KiB · text History 18b6032
defmodule VigilWeb.EventComponents do
  @moduledoc """
  An event's interfaces, rendered: exceptions with their stack traces,
  threads, the message, a CSP report, breadcrumbs, the request, user,
  contexts, extra, SDK, modules, fingerprint and tags, and the raw JSON.
  Used by the issue page (`VigilWeb.IssueLive.Show`) and, with `public`,
  by the share page (`VigilWeb.ShareLive.Issue`), which shows only the
  exception, stack trace and message: the rest may hold personal data.

  An event's `data` is what an SDK sent, normalised but not trusted: any
  key may be missing and any value may be any JSON type. Every component
  here reads it defensively (`map/1`, `list/1`, `text/1`) and renders what
  isn't a string as JSON, so odd data shows up oddly instead of crashing
  the page.

  Stack traces are stored oldest frame first; they are shown most recent
  call first, Sentry style. Runs of frames outside the app are folded
  behind a "Show N more frames" toggle (unless no frame is in the app), and
  each frame opens (a `<details>`) to its source context and variables.
  Toggles are client-side (`Phoenix.LiveView.JS`), so they cost no round
  trip and survive no re-render of the event (which only changes when the
  page moves to another event).
  """
  use VigilWeb, :html

  ## The whole event

  @doc """
  An event's body. With `public`, only the exception, stack trace (without
  frame variables), threads and message.
  """
  attr :event, :map, required: true, doc: "a `Vigil.Issues.IssueEvent` (or a map with `:data`)"
  attr :id, :string, default: "event"
  attr :public, :boolean, default: false

  def event_body(assigns) do
    data = as_map(Map.get(assigns.event, :data))

    assigns =
      assigns
      |> assign(:data, data)
      |> assign(:tags, as_map(Map.get(assigns.event, :tags)))
      |> assign(:exceptions, exception_values(data))
      |> assign(:show_vars, !assigns.public)

    ~H"""
    <div id={@id} class="space-y-5">
      <.processing_errors :if={!@public} id={"#{@id}-errors"} errors={@data["errors"]} />
      <.tag_pills :if={!@public and @tags != %{}} id={"#{@id}-tags"} tags={@tags} />
      <.message id={"#{@id}-message"} data={@data} />
      <.exceptions
        :if={@exceptions != []}
        id={"#{@id}-exceptions"}
        values={@exceptions}
        show_vars={@show_vars}
      />
      <.threads
        :if={show_threads?(@data, @exceptions)}
        id={"#{@id}-threads"}
        threads={@data["threads"]}
        show_vars={@show_vars}
      />
      <.section
        :if={
          @exceptions == [] and !show_threads?(@data, @exceptions) and
            frames(@data["stacktrace"]) != []
        }
        id={"#{@id}-stacktrace"}
        title="Stack trace"
      >
        <.stacktrace id={"#{@id}-st"} stacktrace={@data["stacktrace"]} show_vars={@show_vars} />
      </.section>
      <.csp_report :if={is_map(@data["csp"])} id={"#{@id}-csp"} csp={@data["csp"]} />

      <%= if !@public do %>
        <.breadcrumbs id={"#{@id}-breadcrumbs"} breadcrumbs={@data["breadcrumbs"]} />
        <.request_info
          :if={is_map(@data["request"])}
          id={"#{@id}-request"}
          request={@data["request"]}
        />
        <.kv_section
          :if={non_empty_map?(@data["user"])}
          id={"#{@id}-user"}
          title="User"
          icon="hero-user-micro"
          value={@data["user"]}
        />
        <.contexts
          :if={non_empty_map?(@data["contexts"])}
          id={"#{@id}-contexts"}
          contexts={@data["contexts"]}
        />
        <.kv_section
          :if={non_empty_map?(@data["extra"])}
          id={"#{@id}-extra"}
          title="Additional data"
          icon="hero-plus-circle-micro"
          value={@data["extra"]}
        />
        <.sdk_info :if={non_empty_map?(@data["sdk"])} id={"#{@id}-sdk"} sdk={@data["sdk"]} />
        <.modules
          :if={non_empty_map?(@data["modules"])}
          id={"#{@id}-modules"}
          modules={@data["modules"]}
        />
        <.fingerprint
          :if={as_list(@data["fingerprint"]) != []}
          id={"#{@id}-fingerprint"}
          fingerprint={@data["fingerprint"]}
        />
        <.json_view id={"#{@id}-json"} data={@data} />
      <% end %>
    </div>
    """
  end

  defp show_threads?(data, exceptions) do
    threads = thread_values(data["threads"])

    Enum.any?(threads, &(frames(&1["stacktrace"]) != [])) and
      (exceptions == [] or Enum.any?(threads, &(&1["crashed"] == true)))
  end

  ## Section shell

  attr :id, :string, required: true
  attr :title, :string, required: true
  attr :icon, :string, default: nil
  attr :rest, :global
  slot :inner_block, required: true
  slot :actions

  @doc "A titled card, the frame of each interface."
  def section(assigns) do
    ~H"""
    <section id={@id} class="rounded-box border border-base-300 bg-base-100" {@rest}>
      <header class="flex items-center justify-between gap-2 border-b border-base-300 px-4 py-2.5">
        <h3 class="flex items-center gap-1.5 text-sm font-semibold">
          <.icon :if={@icon} name={@icon} class="size-4 opacity-60" />
          {@title}
        </h3>
        <div :if={@actions != []} class="flex items-center gap-1">{render_slot(@actions)}</div>
      </header>
      <div class="p-4">{render_slot(@inner_block)}</div>
    </section>
    """
  end

  ## Exceptions

  attr :id, :string, required: true
  attr :values, :list, required: true, doc: "the chain, oldest first (as stored)"
  attr :show_vars, :boolean, default: true

  @doc "An exception chain: the raised exception first, then what caused it."
  def exceptions(assigns) do
    assigns =
      assign(assigns, :chain, assigns.values |> as_list() |> Enum.reverse() |> Enum.with_index())

    ~H"""
    <div id={@id} class="space-y-4">
      <.section
        :for={{exc, i} <- @chain}
        id={"#{@id}-#{i}"}
        title={if(i == 0, do: "Exception", else: "Caused by")}
        icon={if(i == 0, do: "hero-bolt-micro", else: "hero-arrow-uturn-up-micro")}
      >
        <:actions>
          <button
            :if={frames(exc["raw_stacktrace"]) != []}
            type="button"
            id={"#{@id}-#{i}-raw-toggle"}
            class="btn btn-ghost btn-xs"
            phx-click={
              JS.toggle(to: "##{@id}-#{i}-st")
              |> JS.toggle(to: "##{@id}-#{i}-raw")
              |> JS.toggle_class("btn-active")
            }
          >
            Raw
          </button>
        </:actions>
        <div class="mb-3 space-y-1">
          <div class="flex flex-wrap items-center gap-2">
            <span class="font-mono text-base font-semibold text-error">
              {text(exc["type"]) || "Exception"}
            </span>
            <.mechanism mechanism={exc["mechanism"]} />
            <span :if={text(exc["module"])} class="font-mono text-xs text-base-content/50">
              {text(exc["module"])}
            </span>
          </div>
          <p :if={text(exc["value"])} class="whitespace-pre-wrap break-words font-mono text-sm">
            {text(exc["value"])}
          </p>
        </div>
        <.stacktrace id={"#{@id}-#{i}-st"} stacktrace={exc["stacktrace"]} show_vars={@show_vars} />
        <div :if={frames(exc["raw_stacktrace"]) != []} id={"#{@id}-#{i}-raw"} class="hidden">
          <.stacktrace
            id={"#{@id}-#{i}-rawst"}
            stacktrace={exc["raw_stacktrace"]}
            show_vars={@show_vars}
          />
        </div>
      </.section>
    </div>
    """
  end

  attr :mechanism, :any, required: true

  defp mechanism(assigns) do
    assigns = assign(assigns, :m, as_map(assigns.mechanism))

    ~H"""
    <span :if={@m["handled"] == false} class="badge badge-error badge-sm">unhandled</span>
    <span :if={@m["handled"] == true} class="badge badge-ghost badge-sm">handled</span>
    <span :if={text(@m["type"])} class="badge badge-outline badge-sm font-mono">
      {text(@m["type"])}
    </span>
    <span :if={@m["synthetic"] == true} class="badge badge-ghost badge-sm">synthetic</span>
    """
  end

  ## Stack traces

  attr :id, :string, required: true
  attr :stacktrace, :any, required: true
  attr :show_vars, :boolean, default: true

  @doc """
  A stack trace, most recent call first. In-app frames show; runs of other
  frames fold behind a toggle, unless no frame is in-app. The first shown
  frame starts open.
  """
  def stacktrace(assigns) do
    frames = assigns.stacktrace |> frames() |> Enum.reverse() |> Enum.with_index()
    any_in_app? = Enum.any?(frames, fn {f, _} -> f["in_app"] == true end)

    groups =
      if any_in_app? do
        frames
        |> Enum.chunk_by(fn {f, _} -> f["in_app"] == true end)
        |> Enum.map(fn [{f, i} | _] = chunk -> {f["in_app"] == true, i, chunk} end)
      else
        [{true, 0, frames}]
      end

    open =
      case Enum.find(frames, fn {f, _} -> !any_in_app? or f["in_app"] == true end) do
        {_, i} -> i
        nil -> nil
      end

    assigns = assign(assigns, groups: groups, open: open, empty?: frames == [])

    ~H"""
    <div id={@id} class="overflow-hidden rounded-box border border-base-300">
      <p :if={@empty?} class="p-3 text-sm text-base-content/60">No frames.</p>
      <%= for {shown?, gi, chunk} <- @groups do %>
        <%= if shown? do %>
          <.frame
            :for={{f, i} <- chunk}
            id={"#{@id}-f#{i}"}
            frame={f}
            open={i == @open}
            show_vars={@show_vars}
          />
        <% else %>
          <button
            type="button"
            id={"#{@id}-more#{gi}"}
            class="flex w-full items-center gap-1.5 border-b border-base-300 bg-base-200/50 px-3 py-1.5 text-left text-xs text-base-content/60 transition hover:bg-base-200 hover:text-base-content last:border-b-0"
            phx-click={
              JS.toggle(to: "##{@id}-group#{gi}")
              |> JS.toggle_class("hidden", to: "##{@id}-more#{gi} .lbl")
            }
          >
            <.icon name="hero-chevron-up-down-micro" class="size-3.5" />
            <span class="lbl">Show {length(chunk)} more {plural(length(chunk), "frame")}</span>
            <span class="lbl hidden">Hide {length(chunk)} {plural(length(chunk), "frame")}</span>
          </button>
          <div id={"#{@id}-group#{gi}"} class="hidden">
            <.frame
              :for={{f, i} <- chunk}
              id={"#{@id}-f#{i}"}
              frame={f}
              open={false}
              show_vars={@show_vars}
            />
          </div>
        <% end %>
      <% end %>
    </div>
    """
  end

  attr :id, :string, required: true
  attr :frame, :map, required: true
  attr :open, :boolean, default: false
  attr :show_vars, :boolean, default: true

  @doc "One frame: where, then (opened) its source context and variables."
  def frame(assigns) do
    f = as_map(assigns.frame)

    assigns =
      assign(assigns,
        f: f,
        path: text(f["filename"]) || text(f["abs_path"]) || text(f["module"]),
        function: text(f["function"]) || text(f["raw_function"]),
        context: source_context(f),
        vars: if(assigns.show_vars, do: as_map(f["vars"]), else: %{}),
        in_app?: f["in_app"] == true
      )

    assigns = assign(assigns, :expandable?, assigns.context != [] or assigns.vars != %{})

    ~H"""
    <details
      id={@id}
      open={@open and @expandable?}
      class="group/frame border-b border-base-300 last:border-b-0"
    >
      <summary class={[
        "flex cursor-pointer list-none flex-wrap items-baseline gap-x-1.5 gap-y-0.5 px-3 py-2 font-mono text-xs transition-colors hover:bg-base-200/60",
        @in_app? && "bg-base-100",
        !@in_app? && "bg-base-200/30 text-base-content/70"
      ]}>
        <.icon
          name="hero-chevron-right-micro"
          class={[
            "size-3.5 self-center opacity-50 transition-transform group-open/frame:rotate-90",
            !@expandable? && "invisible"
          ]}
        />
        <span :if={text(@f["package"])} class="text-base-content/50">{text(@f["package"])}</span>
        <span class={["break-all", @in_app? && "font-semibold"]}>{@path || "?"}</span>
        <span :if={@function} class="text-base-content/50">in</span>
        <span :if={@function} class="break-all text-primary">{@function}</span>
        <span :if={line_col(@f)} class="text-base-content/50">at line {line_col(@f)}</span>
        <span :if={@in_app?} class="badge badge-primary badge-xs ml-auto self-center">in app</span>
      </summary>
      <div :if={@expandable?} class="border-t border-base-300 bg-base-200/40">
        <ol :if={@context != []} class="overflow-x-auto py-1 font-mono text-xs leading-5">
          <li
            :for={{n, line, current?} <- @context}
            class={[
              "flex whitespace-pre",
              current? && "bg-warning/20 font-semibold"
            ]}
          >
            <span class="w-12 shrink-0 select-none pr-3 text-right text-base-content/40">{n}</span>
            <code>{line}</code>
          </li>
        </ol>
        <div :if={@vars != %{}} class="border-t border-base-300 p-2">
          <.kv_table id={"#{@id}-vars"} value={@vars} />
        </div>
      </div>
    </details>
    """
  end

  # [{line_number | "", line, context_line?}]
  defp source_context(f) do
    pre = f["pre_context"] |> as_list() |> Enum.map(&line_text/1)
    post = f["post_context"] |> as_list() |> Enum.map(&line_text/1)
    line = line_text(f["context_line"])
    lineno = if is_integer(f["lineno"]), do: f["lineno"], else: nil

    if is_nil(f["context_line"]) and pre == [] and post == [] do
      []
    else
      start = if lineno, do: lineno - length(pre), else: nil
      lines = Enum.map(pre, &{&1, false}) ++ [{line, true}] ++ Enum.map(post, &{&1, false})

      lines
      |> Enum.with_index()
      |> Enum.map(fn {{l, cur}, i} -> {if(start, do: start + i, else: ""), l, cur} end)
    end
  end

  defp line_text(nil), do: ""
  defp line_text(v), do: text(v)

  defp line_col(f) do
    case {f["lineno"], f["colno"]} do
      {nil, _} -> nil
      {l, nil} -> text(l)
      {l, c} -> "#{text(l)}:#{text(c)}"
    end
  end

  ## Threads

  attr :id, :string, required: true
  attr :threads, :any, required: true
  attr :show_vars, :boolean, default: true

  @doc "Threads with stack traces, one shown at a time (the crashed one first)."
  def threads(assigns) do
    threads =
      assigns.threads
      |> thread_values()
      |> Enum.filter(&(frames(&1["stacktrace"]) != []))
      |> Enum.with_index()

    selected =
      Enum.find(threads, fn {t, _} -> t["crashed"] == true end) ||
        Enum.find(threads, fn {t, _} -> t["current"] == true end) ||
        List.first(threads)

    assigns = assign(assigns, threads: threads, selected: selected && elem(selected, 1))

    ~H"""
    <.section id={@id} title="Threads" icon="hero-queue-list-micro">
      <div :if={length(@threads) > 1} role="tablist" class="tabs tabs-box tabs-xs mb-3 flex-wrap">
        <button
          :for={{t, i} <- @threads}
          type="button"
          role="tab"
          id={"#{@id}-tab#{i}"}
          class={["tab thread-tab", i == @selected && "tab-active"]}
          phx-click={
            JS.hide(to: "##{@id} .thread-panel")
            |> JS.show(to: "##{@id}-t#{i}")
            |> JS.remove_class("tab-active", to: "##{@id} .thread-tab")
            |> JS.add_class("tab-active")
          }
        >
          {thread_label(t)}
          <.icon :if={t["crashed"] == true} name="hero-bolt-micro" class="ml-1 size-3 text-error" />
        </button>
      </div>
      <div
        :for={{t, i} <- @threads}
        id={"#{@id}-t#{i}"}
        class={["thread-panel", i != @selected && "hidden"]}
      >
        <p :if={length(@threads) == 1} class="mb-2 text-xs text-base-content/60">
          {thread_label(t)}
        </p>
        <.stacktrace id={"#{@id}-t#{i}-st"} stacktrace={t["stacktrace"]} show_vars={@show_vars} />
      </div>
    </.section>
    """
  end

  defp thread_label(t) do
    name = text(t["name"])
    id = text(t["id"])

    cond do
      name && id -> "#{name} (#{id})"
      name -> name
      id -> "Thread #{id}"
      true -> "Thread"
    end
  end

  ## Message, CSP, processing errors

  attr :id, :string, required: true
  attr :data, :map, required: true

  @doc "The event's log message, if it has one."
  def message(assigns) do
    assigns = assign(assigns, :text, message_text(assigns.data))

    ~H"""
    <.section :if={@text} id={@id} title="Message" icon="hero-chat-bubble-bottom-center-text-micro">
      <pre class="whitespace-pre-wrap break-words font-mono text-sm">{@text}</pre>
    </.section>
    """
  end

  defp message_text(data) do
    log = data["logentry"]

    cond do
      is_map(log) and text(log["formatted"]) -> text(log["formatted"])
      is_map(log) and text(log["message"]) -> text(log["message"])
      is_binary(log) -> log
      is_binary(data["message"]) and data["message"] != "" -> data["message"]
      is_map(data["message"]) -> message_text(%{"logentry" => data["message"]})
      true -> nil
    end
  end

  attr :id, :string, required: true
  attr :csp, :map, required: true

  @doc "A CSP violation report's fields."
  def csp_report(assigns) do
    ~H"""
    <.section id={@id} title="CSP report" icon="hero-shield-exclamation-micro">
      <.kv_table id={"#{@id}-table"} value={@csp} />
    </.section>
    """
  end

  attr :id, :string, required: true
  attr :errors, :any, required: true

  @doc "Problems met while processing the event, as a quiet notice."
  def processing_errors(assigns) do
    assigns = assign(assigns, :errors, as_list(assigns.errors))

    ~H"""
    <div
      :if={@errors != []}
      id={@id}
      class="flex gap-2 rounded-box border border-warning/30 bg-warning/5 px-4 py-2.5 text-sm"
    >
      <.icon name="hero-exclamation-triangle-micro" class="mt-0.5 size-4 shrink-0 text-warning" />
      <div>
        <p class="font-medium">
          {length(@errors)} {plural(length(@errors), "problem")} processing this event
        </p>
        <ul class="mt-1 space-y-0.5 text-xs text-base-content/70">
          <li :for={e <- @errors}>
            <%= if is_map(e) do %>
              <span class="font-mono">{text(e["type"]) || "error"}</span>
              <span :if={text(e["name"])}>
                · <span class="font-mono">{text(e["name"])}</span>
              </span>
              <span :if={text(e["value"])}>· {text(e["value"])}</span>
            <% else %>
              {text(e)}
            <% end %>
          </li>
        </ul>
      </div>
    </div>
    """
  end

  ## Breadcrumbs

  @breadcrumbs_shown 30

  attr :id, :string, required: true
  attr :breadcrumbs, :any, required: true

  @doc "What happened before, oldest first; the oldest fold away past #{@breadcrumbs_shown}."
  def breadcrumbs(assigns) do
    crumbs =
      case assigns.breadcrumbs do
        %{"values" => v} -> as_list(v)
        v -> as_list(v)
      end
      |> Enum.filter(&is_map/1)

    hidden = max(length(crumbs) - @breadcrumbs_shown, 0)
    {older, recent} = Enum.split(crumbs, hidden)

    assigns =
      assign(assigns, older: Enum.with_index(older), recent: Enum.with_index(recent, hidden))

    ~H"""
    <.section
      :if={@older != [] or @recent != []}
      id={@id}
      title="Breadcrumbs"
      icon="hero-list-bullet-micro"
    >
      <button
        :if={@older != []}
        type="button"
        id={"#{@id}-older-toggle"}
        class="btn btn-ghost btn-xs mb-2"
        phx-click={JS.toggle(to: "##{@id} .crumb-older") |> JS.hide()}
      >
        Show {length(@older)} older
      </button>
      <div class="-mx-4 -mb-4 overflow-x-auto">
        <table class="table table-xs">
          <thead>
            <tr>
              <th class="w-28">Time</th>
              <th class="w-32">Category</th>
              <th>Message</th>
            </tr>
          </thead>
          <tbody>
            <.crumb :for={{c, i} <- @older} id={"#{@id}-#{i}"} crumb={c} class="crumb-older hidden" />
            <.crumb :for={{c, i} <- @recent} id={"#{@id}-#{i}"} crumb={c} class="" />
          </tbody>
        </table>
      </div>
    </.section>
    """
  end

  attr :id, :string, required: true
  attr :crumb, :map, required: true
  attr :class, :string, required: true

  defp crumb(assigns) do
    c = assigns.crumb
    assigns = assign(assigns, c: c, level: text(c["level"]) || "info", data: c["data"])

    ~H"""
    <tr id={@id} class={["align-top hover:bg-base-200/40", @class]}>
      <td class="whitespace-nowrap font-mono text-base-content/60" title={text(@c["timestamp"])}>
        <span class="flex items-center gap-1.5">
          <span class={["size-2 shrink-0 rounded-full", level_dot(@level)]} title={@level} />
          {clock(@c["timestamp"])}
        </span>
      </td>
      <td class="font-mono">
        <span>{text(@c["category"]) || text(@c["type"]) || "default"}</span>
      </td>
      <td class="min-w-64">
        <p :if={text(@c["message"])} class="whitespace-pre-wrap break-words font-mono">
          {text(@c["message"])}
        </p>
        <pre
          :if={non_empty?(@data)}
          class="mt-1 whitespace-pre-wrap break-all font-mono text-[0.7rem] text-base-content/60"
        >{json(@data)}</pre>
      </td>
    </tr>
    """
  end

  ## Request

  attr :id, :string, required: true
  attr :request, :map, required: true

  @doc "The HTTP request: method and URL, query, headers, body, cookies and env."
  def request_info(assigns) do
    r = assigns.request

    assigns =
      assign(assigns,
        r: r,
        method: text(r["method"]),
        url: text(r["url"]),
        query: query_string(r["query_string"]),
        headers: pairs(r["headers"]),
        cookies: pairs(r["cookies"]),
        body: r["data"],
        env: as_map(r["env"])
      )

    ~H"""
    <.section id={@id} title="Request" icon="hero-globe-alt-micro">
      <p :if={@method || @url} class="mb-3 break-all font-mono text-sm">
        <span :if={@method} class="badge badge-neutral badge-sm mr-1.5 font-bold">{@method}</span>
        {@url}
      </p>
      <div class="space-y-3">
        <.kv_block :if={@query} id={"#{@id}-query"} title="Query string">
          <pre class="whitespace-pre-wrap break-all font-mono text-xs">{@query}</pre>
        </.kv_block>
        <.kv_block :if={non_empty?(@body)} id={"#{@id}-body"} title="Body">
          <pre class="max-h-96 overflow-auto whitespace-pre-wrap break-all font-mono text-xs">{if is_binary(@body), do: @body, else: json(@body)}</pre>
        </.kv_block>
        <.kv_block :if={@headers != []} id={"#{@id}-headers"} title="Headers">
          <.kv_table id={"#{@id}-headers-table"} value={@headers} />
        </.kv_block>
        <.kv_block :if={@cookies != []} id={"#{@id}-cookies"} title="Cookies">
          <.kv_table id={"#{@id}-cookies-table"} value={@cookies} />
        </.kv_block>
        <.kv_block :if={@env != %{}} id={"#{@id}-env"} title="Environment">
          <.kv_table id={"#{@id}-env-table"} value={@env} />
        </.kv_block>
      </div>
    </.section>
    """
  end

  defp query_string(q) when is_binary(q) and q != "", do: q
  defp query_string(q) when is_list(q) or is_map(q), do: if(non_empty?(q), do: json(q))
  defp query_string(_), do: nil

  attr :id, :string, required: true
  attr :title, :string, required: true
  slot :inner_block, required: true

  defp kv_block(assigns) do
    ~H"""
    <div id={@id}>
      <h4 class="mb-1 text-xs font-semibold uppercase tracking-wide text-base-content/50">
        {@title}
      </h4>
      {render_slot(@inner_block)}
    </div>
    """
  end

  ## Key/value interfaces

  attr :id, :string, required: true
  attr :title, :string, required: true
  attr :icon, :string, default: nil
  attr :value, :any, required: true

  @doc "A titled key/value table (user, extra)."
  def kv_section(assigns) do
    ~H"""
    <.section id={@id} title={@title} icon={@icon}>
      <.kv_table id={"#{@id}-table"} value={@value} />
    </.section>
    """
  end

  attr :id, :string, required: true
  attr :contexts, :map, required: true

  @doc "One card per context (browser, os, runtime, device, trace, ...)."
  def contexts(assigns) do
    assigns =
      assign(
        assigns,
        :cards,
        assigns.contexts |> as_map() |> Enum.sort_by(&elem(&1, 0)) |> Enum.with_index()
      )

    ~H"""
    <.section id={@id} title="Contexts" icon="hero-cpu-chip-micro">
      <div class="grid gap-3 sm:grid-cols-2">
        <div
          :for={{{name, ctx}, i} <- @cards}
          id={"#{@id}-#{i}"}
          data-context={name}
          class="rounded-box border border-base-300 bg-base-200/30 p-3"
        >
          <h4 class="mb-1.5 flex items-center gap-1.5 text-xs font-semibold uppercase tracking-wide">
            {context_title(name, ctx)}
          </h4>
          <.kv_table id={"#{@id}-#{i}-table"} value={context_fields(ctx)} />
        </div>
      </div>
    </.section>
    """
  end

  defp context_title(name, ctx) do
    ctx = as_map(ctx)

    case {text(ctx["name"]), text(ctx["version"])} do
      {n, v} when is_binary(n) and is_binary(v) -> "#{name} · #{n} #{v}"
      _ -> text(name)
    end
  end

  defp context_fields(ctx) when is_map(ctx), do: Map.delete(ctx, "type")
  defp context_fields(ctx), do: %{"value" => ctx}

  attr :id, :string, required: true
  attr :sdk, :map, required: true

  @doc "The SDK that sent the event."
  def sdk_info(assigns) do
    assigns =
      assign(assigns,
        name: text(assigns.sdk["name"]),
        version: text(assigns.sdk["version"]),
        rest: Map.drop(assigns.sdk, ["name", "version"])
      )

    ~H"""
    <.section id={@id} title="SDK" icon="hero-cube-micro">
      <p class="font-mono text-sm">{@name || "unknown"} <span :if={@version}>{@version}</span></p>
      <div :if={@rest != %{}} class="mt-2">
        <.kv_table id={"#{@id}-table"} value={@rest} />
      </div>
    </.section>
    """
  end

  attr :id, :string, required: true
  attr :modules, :map, required: true

  @doc "Loaded modules/packages and their versions, folded."
  def modules(assigns) do
    ~H"""
    <details id={@id} class="group rounded-box border border-base-300 bg-base-100">
      <summary class="flex cursor-pointer list-none items-center gap-1.5 px-4 py-2.5 text-sm font-semibold">
        <.icon
          name="hero-chevron-right-micro"
          class="size-4 opacity-60 transition-transform group-open:rotate-90"
        /> Modules <span class="badge badge-ghost badge-sm">{map_size(@modules)}</span>
      </summary>
      <div class="border-t border-base-300 p-4">
        <.kv_table id={"#{@id}-table"} value={@modules} />
      </div>
    </details>
    """
  end

  attr :id, :string, required: true
  attr :fingerprint, :list, required: true

  @doc "The grouping fingerprint the event was sent with."
  def fingerprint(assigns) do
    ~H"""
    <.section id={@id} title="Fingerprint" icon="hero-finger-print-micro">
      <div class="flex flex-wrap gap-1.5">
        <code :for={part <- as_list(@fingerprint)} class="badge badge-ghost badge-sm font-mono">
          {text(part)}
        </code>
      </div>
    </.section>
    """
  end

  attr :id, :string, required: true
  attr :tags, :map, required: true

  @doc "An event's own tags, as pills."
  def tag_pills(assigns) do
    assigns = assign(assigns, :pairs, assigns.tags |> as_map() |> Enum.sort_by(&elem(&1, 0)))

    ~H"""
    <div id={@id} class="flex flex-wrap gap-1.5">
      <span
        :for={{k, v} <- @pairs}
        class="inline-flex overflow-hidden rounded-full border border-base-300 text-xs transition hover:border-primary/50"
        data-tag={k}
      >
        <span class="bg-base-200 px-2 py-0.5 text-base-content/60">{k}</span>
        <span class="px-2 py-0.5 font-medium">{text(v)}</span>
      </span>
    </div>
    """
  end

  attr :id, :string, required: true
  attr :value, :any, required: true, doc: "a map, or a list of `{k, v}` / `[k, v]` pairs"

  @doc "Keys and values; non-string values as (pretty) JSON."
  def kv_table(assigns) do
    assigns = assign(assigns, :rows, pairs(assigns.value))

    ~H"""
    <table id={@id} class="w-full table-fixed text-xs">
      <tbody>
        <tr :for={{k, v} <- @rows} class="border-b border-base-300/60 align-top last:border-b-0">
          <th class="w-1/3 break-words py-1 pr-3 text-left font-mono font-normal text-base-content/60">
            {k}
          </th>
          <td class="py-1">
            <%= if is_map(v) or is_list(v) do %>
              <pre class="whitespace-pre-wrap break-all font-mono">{json(v)}</pre>
            <% else %>
              <span class="whitespace-pre-wrap break-all font-mono">{display(v)}</span>
            <% end %>
          </td>
        </tr>
      </tbody>
    </table>
    """
  end

  ## JSON

  attr :id, :string, required: true
  attr :data, :any, required: true

  @doc "The whole event as pretty JSON, behind a toggle."
  def json_view(assigns) do
    ~H"""
    <div id={@id}>
      <button
        type="button"
        id={"#{@id}-toggle"}
        class="btn btn-ghost btn-sm"
        phx-click={JS.toggle(to: "##{@id}-pre")}
      >
        <.icon name="hero-code-bracket-micro" class="size-4" /> JSON
      </button>
      <pre
        id={"#{@id}-pre"}
        class="mt-2 hidden max-h-[40rem] overflow-auto rounded-box bg-base-200 p-4 font-mono text-xs leading-relaxed"
      >{json(@data)}</pre>
    </div>
    """
  end

  ## Small shared pieces (also used by the pages)

  attr :level, :any, required: true
  attr :class, :any, default: nil

  @doc "A level badge (fatal, error, warning, info, debug)."
  def level_badge(assigns) do
    assigns = assign(assigns, :level, text(assigns.level) || "error")

    ~H"""
    <span class={["badge badge-sm gap-1", level_badge_class(@level), @class]}>
      <span class={["size-1.5 rounded-full", level_dot(@level)]} />{@level}
    </span>
    """
  end

  attr :at, :any, required: true
  attr :id, :string, default: nil

  @doc "A relative time (\"3h ago\"), with the full time as its title."
  def time_ago(assigns) do
    ~H"""
    <time id={@id} datetime={iso(@at)} title={full_time(@at)}>{relative_time(@at)}</time>
    """
  end

  @doc "How long ago `dt` was, briefly."
  def relative_time(nil), do: "—"

  def relative_time(%DateTime{} = dt) do
    s = DateTime.diff(DateTime.utc_now(), dt)

    cond do
      s < 45 -> "just now"
      s < 3600 -> "#{div(s + 30, 60)}m ago"
      s < 86_400 -> "#{div(s, 3600)}h ago"
      s < 86_400 * 30 -> "#{div(s, 86_400)}d ago"
      s < 86_400 * 365 -> "#{div(s, 86_400 * 30)}mo ago"
      true -> "#{div(s, 86_400 * 365)}y ago"
    end
  end

  def relative_time(%NaiveDateTime{} = dt),
    do: dt |> DateTime.from_naive!("Etc/UTC") |> relative_time()

  def relative_time(_), do: "—"

  @doc "A time in full, UTC."
  def full_time(%DateTime{} = dt), do: Calendar.strftime(dt, "%Y-%m-%d %H:%M:%S UTC")
  def full_time(%NaiveDateTime{} = dt), do: Calendar.strftime(dt, "%Y-%m-%d %H:%M:%S UTC")
  def full_time(_), do: nil

  defp iso(%DateTime{} = dt), do: DateTime.to_iso8601(dt)
  defp iso(_), do: nil

  # A breadcrumb's time of day: from an ISO string or a Unix timestamp.
  defp clock(ts) do
    dt =
      cond do
        is_binary(ts) ->
          case DateTime.from_iso8601(ts) do
            {:ok, dt, _} -> dt
            _ -> nil
          end

        is_number(ts) ->
          case DateTime.from_unix(trunc(ts * 1000), :millisecond) do
            {:ok, dt} -> dt
            _ -> nil
          end

        true ->
          nil
      end

    if dt, do: Calendar.strftime(dt, "%H:%M:%S.%3f"), else: text(ts) || ""
  end

  @doc "daisyUI badge classes for a level."
  def level_badge_class(level) do
    case level do
      l when l in ["fatal", "error"] -> "badge-error badge-soft"
      "warning" -> "badge-warning badge-soft"
      "info" -> "badge-info badge-soft"
      _ -> "badge-ghost"
    end
  end

  @doc "A background colour class for a level's dot."
  def level_dot(level) do
    case level do
      "fatal" -> "bg-error ring-2 ring-error/30"
      "error" -> "bg-error"
      "warning" -> "bg-warning"
      "info" -> "bg-info"
      _ -> "bg-base-content/30"
    end
  end

  ## Reading untrusted data

  @doc "The exception chain of an event's data, oldest first (as stored)."
  def exception_values(data) do
    case as_map(data)["exception"] do
      %{"values" => values} -> as_list(values)
      values when is_list(values) -> values
      %{"type" => _} = one -> [one]
      _ -> []
    end
    |> Enum.filter(&is_map/1)
  end

  defp thread_values(%{"values" => v}), do: v |> as_list() |> Enum.filter(&is_map/1)
  defp thread_values(v) when is_list(v), do: Enum.filter(v, &is_map/1)
  defp thread_values(_), do: []

  defp frames(%{"frames" => frames}) when is_list(frames), do: Enum.filter(frames, &is_map/1)
  defp frames(_), do: []

  defp as_map(v) when is_map(v) and not is_struct(v), do: v
  defp as_map(_), do: %{}

  defp as_list(v) when is_list(v), do: v
  defp as_list(_), do: []

  defp non_empty_map?(v), do: is_map(v) and map_size(v) > 0

  defp non_empty?(nil), do: false
  defp non_empty?(""), do: false
  defp non_empty?([]), do: false
  defp non_empty?(m) when is_map(m), do: map_size(m) > 0
  defp non_empty?(_), do: true

  # Rows of a map or a list of pairs, as {string key, value}.
  defp pairs(v) when is_map(v) and not is_struct(v),
    do: v |> Enum.map(fn {k, val} -> {display(k), val} end) |> Enum.sort_by(&elem(&1, 0))

  defp pairs(v) when is_list(v) do
    Enum.flat_map(v, fn
      [k, val] -> [{display(k), val}]
      {k, val} -> [{display(k), val}]
      %{} = m -> pairs(m)
      other -> [{"", other}]
    end)
  end

  defp pairs(nil), do: []
  defp pairs(other), do: [{"", other}]

  # A scalar as a string; nil and "" as nil.
  defp text(nil), do: nil
  defp text(""), do: nil
  defp text(v) when is_binary(v), do: v
  defp text(v), do: display(v)

  defp display(v) when is_binary(v), do: v
  defp display(nil), do: "null"
  defp display(v) when is_map(v) or is_list(v), do: json(v)
  defp display(v), do: encode(v, false)

  defp json(v), do: encode(v, true)

  defp encode(v, pretty) do
    case Jason.encode(v, pretty: pretty) do
      {:ok, s} -> s
      {:error, _} -> inspect(v)
    end
  rescue
    _ -> inspect(v)
  end

  defp plural(1, word), do: word
  defp plural(_, word), do: word <> "s"
end