defmodule VigilWeb.IssueLive.Index do
@moduledoc """
A project's issues: the page a project link lands on.
Everything the list shows is in the URL, so a view can be shared and
back/forward walks through it: `q` (the search box, parsed with
`Vigil.Issues.parse_query/1`), and `status`, `env`, `period`, `sort` and
`page`, which win over what `q` says. Every control patches the URL;
`handle_params/3` reads it and searches.
Rows can be selected (one by one, or the whole page) and resolved,
ignored, reopened, assigned or deleted together. New events and changes
arrive on the project's PubSub topic; they refresh the page at most once
a second, keeping the selection where the rows remain. A keyboard hook
moves a focus ring with `j`/`k` and acts on the focused row.
Until the project has seen an event, the page is its setup guide.
"""
use VigilWeb, :live_view
import VigilWeb.IssueListComponents
alias Vigil.Accounts.Scope
alias Vigil.{Issues, Projects, Releases}
alias Vigil.Projects.Platforms
@per_page 50
@refresh_ms 1_000
@statuses [
{"unresolved", "Unresolved", :unresolved},
{"resolved", "Resolved", :resolved},
{"ignored", "Ignored", :ignored},
{"all", "All", :all}
]
@sorts [{"Last seen", "last_seen"}, {"First seen", "first_seen"}, {"Events", "count"}]
@past %{
"resolve" => "resolved",
"ignore" => "ignored",
"unresolve" => "reopened",
"assign_me" => "assigned to you",
"delete" => "deleted"
}
@impl true
def mount(_params, _session, socket) do
%{current_scope: scope, project: project} = socket.assigns
if connected?(socket),
do: Phoenix.PubSub.subscribe(Vigil.PubSub, "project:#{project.id}:issues")
key = project |> Projects.list_keys() |> Enum.find(& &1.active)
dsn = key && Projects.dsn(key, project)
{:ok,
socket
|> assign(:page_title, project.name)
|> assign(:dsn, dsn)
|> assign(:snippet, dsn && Platforms.snippet(project.platform, dsn))
|> assign(:can_write, Scope.can?(scope, "event:write"))
|> assign(:can_delete, Scope.can?(scope, "project:admin"))
|> assign(:ever?, project.first_event_at != nil)
|> assign(:selected, MapSet.new())
|> assign(:page_ids, [])
|> assign(:refresh_pending?, false)
|> stream(:issues, [])}
end
@impl true
def handle_params(params, _uri, socket) do
q = params |> Map.get("q", "") |> to_string() |> String.trim()
parsed = if q == "", do: %{}, else: Issues.parse_query(q)
status = status_param(params["status"])
env = blank(params["env"])
period = if params["period"] in Enum.map(Issues.periods(), &elem(&1, 0)), do: params["period"]
sort = if params["sort"] in Enum.map(@sorts, &elem(&1, 1)), do: params["sort"]
page = page_param(params["page"])
filters =
Map.merge(parsed, %{
status: status || parsed[:status] || :unresolved,
environment: env || parsed[:environment],
period: period,
sort: String.to_existing_atom(sort || "last_seen"),
limit: @per_page,
offset: (page - 1) * @per_page
})
query =
%{
"q" => q,
"status" => status && Atom.to_string(status),
"env" => env,
"period" => period,
"sort" => sort
}
|> reject_blank()
{:noreply,
socket
|> assign(:query, query)
|> assign(:page, page)
|> assign(:filters, filters)
|> assign(:search_form, to_form(%{"q" => q}, as: :search))
|> assign(
:filter_form,
to_form(%{"env" => env || "", "period" => period || "", "sort" => sort || "last_seen"},
as: :filters
)
)
|> load()}
end
defp status_param(s) do
Enum.find_value(@statuses, fn {key, _, atom} -> key == s && atom end)
end
defp page_param(p) do
case Integer.parse(to_string(p)) do
{n, ""} when n > 0 -> n
_ -> 1
end
end
defp blank(v) when v in [nil, ""], do: nil
defp blank(v), do: v
defp reject_blank(map), do: map |> Enum.reject(fn {_, v} -> v in [nil, ""] end) |> Map.new()
# The current page of issues, with sparklines, streamed afresh.
defp load(socket) do
%{current_scope: scope, project: project, filters: filters} = socket.assigns
%{issues: issues, more?: more?} = Issues.search(scope, project.id, filters)
ids = Enum.map(issues, & &1.id)
sparks = Issues.sparklines(ids)
rows = Enum.map(issues, &%{id: &1.id, issue: &1, spark: Map.get(sparks, &1.id, [])})
ever? =
socket.assigns.ever? or issues != [] or
Issues.list_issues(project.id, status: :all, limit: 1) != []
socket
|> assign(:ever?, ever?)
|> assign(:more?, more?)
|> assign(:page_ids, ids)
|> assign(:selected, MapSet.intersection(socket.assigns.selected, MapSet.new(ids)))
|> assign(:environments, environments(project.id, filters[:environment]))
|> stream(:issues, rows, reset: true)
end
defp environments(project_id, current) do
envs = Releases.list_environments(project_id)
if current && current not in envs, do: envs ++ [current], else: envs
end
# A link to this page with `changes` applied to its query; changing a
# filter goes back to the first page.
defp list_path(assigns, changes) do
query =
assigns.query
|> Map.merge(changes)
|> Map.put("page", Map.get(changes, "page"))
|> then(&if(&1["page"] in [1, "1"], do: Map.delete(&1, "page"), else: &1))
|> reject_blank()
base = ~p"/orgs/#{assigns.current_scope.organization.slug}/projects/#{assigns.project.slug}"
if query == %{}, do: base, else: base <> "?" <> URI.encode_query(query)
end
defp issue_path(scope, project, issue),
do: ~p"/orgs/#{scope.organization.slug}/projects/#{project.slug}/issues/#{issue.short_id}"
defp short_id(project, issue), do: "#{String.upcase(project.slug)}-#{issue.short_id}"
@impl true
def render(assigns) do
assigns =
assign(assigns,
statuses: @statuses,
sorts: @sorts,
periods: Issues.periods(),
all_selected?:
assigns.page_ids != [] and MapSet.size(assigns.selected) == length(assigns.page_ids),
status_paths:
Map.new(@statuses, fn {k, _, _} -> {k, list_path(assigns, %{"status" => k})} end),
prev_path: list_path(assigns, %{"page" => assigns.page - 1}),
next_path: list_path(assigns, %{"page" => assigns.page + 1}),
setup_path:
~p"/orgs/#{assigns.current_scope.organization.slug}/projects/#{assigns.project.slug}/setup"
)
~H"""
<Layouts.app flash={@flash} current_scope={@current_scope} active={:projects}>
<.header>
<span class="flex items-center gap-2">
{@project.name}
<span
:if={@ever?}
id="live-indicator"
class="inline-flex items-center gap-1 rounded-full bg-success/10 px-2 py-0.5 text-xs font-medium text-success"
title="This list updates as events arrive"
>
<span class="size-1.5 rounded-full bg-success motion-safe:animate-pulse" /> Live
</span>
</span>
<:subtitle>
{Platforms.name(@project.platform)} · <span class="font-mono">{@project.slug}</span>
</:subtitle>
<:actions>
<div class="flex items-center gap-1">
<.link
navigate={@setup_path}
class="btn btn-ghost btn-sm"
id="project-setup"
>
<.icon name="hero-code-bracket-micro" class="size-4" /> Setup
</.link>
<.link
:if={Scope.can?(@current_scope, "project:write")}
navigate={
~p"/orgs/#{@current_scope.organization.slug}/projects/#{@project.slug}/settings"
}
class="btn btn-ghost btn-sm"
id="project-settings"
>
<.icon name="hero-cog-6-tooth-micro" class="size-4" /> Settings
</.link>
</div>
</:actions>
</.header>
<%= if @ever? do %>
<.filter_bar
search_form={@search_form}
filter_form={@filter_form}
environments={@environments}
periods={@periods}
sorts={@sorts}
statuses={@statuses}
status={@filters.status}
paths={@status_paths}
/>
<div
id="issue-list"
phx-hook=".IssueKeys"
class="overflow-hidden rounded-box border border-base-300 bg-base-100"
>
<div class="flex min-h-11 items-center gap-3 border-b border-base-300 bg-base-200/50 px-3 py-1.5">
<input
:if={@can_write}
type="checkbox"
id="select-all"
class="checkbox checkbox-sm"
checked={@all_selected?}
disabled={@page_ids == []}
phx-click="select_all"
aria-label="Select all issues on this page"
/>
<%= if MapSet.size(@selected) > 0 do %>
<.bulk_actions count={MapSet.size(@selected)} can_delete={@can_delete} />
<% else %>
<div class="flex flex-1 items-center justify-between gap-3 text-xs text-base-content/60">
<span>Issue</span>
<span class="hidden items-center gap-6 sm:flex">
<span class="w-24 text-center">24h</span>
<span class="w-12 text-right">Events</span>
<span class="w-20 text-right">Seen</span>
<span class="w-6"></span>
</span>
</div>
<% end %>
</div>
<ul id="issues" phx-update="stream" class="divide-y divide-base-300">
<li
id="issues-empty"
class="hidden px-4 py-12 text-center text-sm text-base-content/60 only:block"
>
<.icon name="hero-sparkles" class="mx-auto mb-2 size-6 text-base-content/30" />
No issues match.
</li>
<li
:for={{dom_id, row} <- @streams.issues}
id={dom_id}
data-issue-id={row.id}
phx-mounted={JS.ignore_attributes(["data-focused"])}
class="group flex items-center gap-3 px-3 py-2.5 transition-colors hover:bg-base-200/60 has-checked:bg-primary/5 data-focused:bg-base-200/80 data-focused:shadow-[inset_3px_0_0_var(--color-primary)]"
>
<input
:if={@can_write}
type="checkbox"
id={"select-#{dom_id}"}
class="checkbox checkbox-sm"
checked={MapSet.member?(@selected, row.id)}
phx-click="toggle"
phx-value-id={row.id}
aria-label={"Select #{short_id(@project, row.issue)}"}
/>
<.level_marker level={row.issue.level} />
<div class="min-w-0 flex-1">
<.link
navigate={issue_path(@current_scope, @project, row.issue)}
id={"link-#{dom_id}"}
data-issue-link
class="block truncate font-medium transition-colors group-hover:text-primary"
>
{row.issue.title}
</.link>
<p
:if={row.issue.culprit not in [nil, ""]}
class="truncate font-mono text-xs text-base-content/60"
>
{row.issue.culprit}
</p>
<div class="mt-0.5 flex flex-wrap items-center gap-x-2 gap-y-0.5 text-xs text-base-content/50">
<span class="font-mono">{short_id(@project, row.issue)}</span>
<.status_badge status={row.issue.status} />
<span class="hidden sm:inline">
first seen <.relative_time at={row.issue.first_seen} />
</span>
<span class="sm:hidden">
<.relative_time at={row.issue.last_seen} /> · {compact(row.issue.count)} events
</span>
</div>
</div>
<div class="hidden shrink-0 items-center gap-6 sm:flex">
<.sparkline id={"spark-#{dom_id}"} counts={row.spark} class="w-24" />
<span
class="w-12 text-right font-mono text-sm tabular-nums"
title={"#{row.issue.count} #{plural(row.issue.count, "event")}"}
>
{compact(row.issue.count)}
</span>
<.relative_time
at={row.issue.last_seen}
class="w-20 text-right text-xs text-base-content/60"
/>
</div>
<.assignee user={row.issue.assignee} />
</li>
</ul>
<div class="flex flex-wrap items-center justify-between gap-2 border-t border-base-300 bg-base-200/30 px-3 py-2 text-xs text-base-content/50">
<p id="keyboard-hint" class="hidden md:block">
Keyboard: <kbd class="kbd kbd-xs">j</kbd>/<kbd class="kbd kbd-xs">k</kbd>
move · <kbd class="kbd kbd-xs">o</kbd>
open · <kbd class="kbd kbd-xs">x</kbd>
select · <kbd class="kbd kbd-xs">r</kbd>
resolve · <kbd class="kbd kbd-xs">i</kbd>
ignore · <kbd class="kbd kbd-xs">/</kbd>
search
</p>
<nav id="pagination" class="ml-auto flex items-center gap-1" aria-label="Pages">
<span class="mr-1">Page {@page}</span>
<.link
:if={@page > 1}
id="page-prev"
patch={@prev_path}
class="btn btn-ghost btn-xs"
>
<.icon name="hero-chevron-left-micro" class="size-3.5" /> Prev
</.link>
<.link
:if={@more?}
id="page-next"
patch={@next_path}
class="btn btn-ghost btn-xs"
>
Next <.icon name="hero-chevron-right-micro" class="size-3.5" />
</.link>
</nav>
</div>
</div>
<script :type={Phoenix.LiveView.ColocatedHook} name=".IssueKeys">
export default {
mounted() {
this.focusId = null
this.focusIndex = -1
this.onKey = e => {
if (e.metaKey || e.ctrlKey || e.altKey) return
const t = e.target
if (t.closest && t.closest("input, textarea, select, [contenteditable]")) {
if (e.key === "Escape") t.blur()
return
}
if (e.key === "/") {
e.preventDefault()
document.getElementById("issue-search-q")?.focus()
return
}
if (e.key === "j" || e.key === "k") {
e.preventDefault()
this.move(e.key === "j" ? 1 : -1)
return
}
const row = this.focused()
if (!row) return
const id = row.dataset.issueId
switch (e.key) {
case "Enter":
case "o":
row.querySelector("[data-issue-link]")?.click()
break
case "x":
row.querySelector("input[type=checkbox]")?.click()
break
case "r":
this.pushEvent("resolve_issue", {id})
break
case "i":
this.pushEvent("ignore_issue", {id})
break
default:
return
}
e.preventDefault()
}
window.addEventListener("keydown", this.onKey)
},
destroyed() {
window.removeEventListener("keydown", this.onKey)
},
rows() {
return Array.from(this.el.querySelectorAll("li[data-issue-id]"))
},
// The focused row; if it left the list (resolved, say), the one
// that took its place.
focused() {
const rows = this.rows()
if (rows.length === 0) return null
let row = rows.find(r => r.dataset.issueId === this.focusId)
if (!row && this.focusIndex >= 0) {
row = rows[Math.min(this.focusIndex, rows.length - 1)]
this.focusId = row.dataset.issueId
this.paint()
}
return row || null
},
move(delta) {
const rows = this.rows()
if (rows.length === 0) return
const current = this.focused()
const at = current ? rows.indexOf(current) : -1
const next = Math.max(0, Math.min(rows.length - 1, at < 0 ? 0 : at + delta))
this.focusIndex = next
this.focusId = rows[next].dataset.issueId
this.paint()
rows[next].scrollIntoView({block: "nearest"})
},
paint() {
this.rows().forEach(r => r.toggleAttribute("data-focused", r.dataset.issueId === this.focusId))
}
}
</script>
<% else %>
<.setup_panel dsn={@dsn} snippet={@snippet} setup_path={@setup_path} />
<% end %>
</Layouts.app>
"""
end
attr :search_form, :any, required: true
attr :filter_form, :any, required: true
attr :environments, :list, required: true
attr :periods, :list, required: true
attr :sorts, :list, required: true
attr :statuses, :list, required: true
attr :status, :atom, required: true
attr :paths, :map, required: true
defp filter_bar(assigns) do
~H"""
<div class="mb-4 space-y-3">
<.form
for={@search_form}
id="issue-search"
phx-submit="search"
class="flex items-center gap-2"
>
<label class="input input-sm flex-1 transition focus-within:border-primary">
<.icon name="hero-magnifying-glass-micro" class="size-4 text-base-content/50" />
<input
type="search"
id="issue-search-q"
name={@search_form[:q].name}
value={@search_form[:q].value}
placeholder="Search: is:resolved level:error env:production browser.name:Chrome timeout"
class="grow"
autocomplete="off"
phx-debounce="blur"
aria-label="Search issues"
/>
<kbd class="kbd kbd-xs hidden sm:inline-flex">/</kbd>
</label>
<button type="submit" class="btn btn-sm btn-primary" phx-disable-with="…">Search</button>
</.form>
<div class="flex flex-wrap items-center justify-between gap-2">
<nav id="status-tabs" role="tablist" class="tabs tabs-box tabs-sm">
<.link
:for={{key, label, atom} <- @statuses}
id={"status-#{key}"}
patch={@paths[key]}
role="tab"
aria-selected={to_string(@status == atom)}
class={["tab transition", @status == atom && "tab-active"]}
>
{label}
</.link>
</nav>
<.form
for={@filter_form}
id="issue-filters"
phx-change="filter"
class="flex flex-wrap items-center gap-2"
>
<.input
field={@filter_form[:env]}
type="select"
id="filter-env"
class="select select-sm w-auto"
prompt="All environments"
options={@environments}
aria-label="Environment"
/>
<.input
field={@filter_form[:period]}
type="select"
id="filter-period"
class="select select-sm w-auto"
prompt="Any time"
options={Enum.map(@periods, fn {k, label} -> {label, k} end)}
aria-label="Time range"
/>
<.input
field={@filter_form[:sort]}
type="select"
id="filter-sort"
class="select select-sm w-auto"
options={@sorts}
aria-label="Sort by"
/>
</.form>
</div>
</div>
"""
end
attr :dsn, :string, default: nil
attr :snippet, :string, default: nil
attr :setup_path, :string, required: true
defp setup_panel(assigns) do
~H"""
<section
id="setup"
class="space-y-4 rounded-box border border-dashed border-base-300 bg-base-100 p-5"
>
<div class="flex items-center gap-2">
<span class="size-2.5 rounded-full bg-warning motion-safe:animate-pulse" />
<h2 class="font-semibold">Waiting for the first event</h2>
</div>
<p class="text-sm text-base-content/70">
Point an SDK at this DSN and send an error; it shows up here as it happens.
</p>
<%= if @dsn do %>
<div class="join w-full">
<input
id="dsn"
type="text"
readonly
value={@dsn}
class="input input-sm join-item min-w-0 flex-1 font-mono text-xs"
aria-label="DSN"
/>
<button
id="copy-dsn"
type="button"
class="btn btn-sm btn-primary join-item"
phx-click={JS.dispatch("phx:copy", to: "#dsn")}
>
<.icon name="hero-clipboard-document-micro" class="size-4" /> Copy
</button>
</div>
<pre
id="snippet"
class="overflow-x-auto rounded-box bg-base-200 p-4 font-mono text-xs leading-relaxed"
><code>{@snippet}</code></pre>
<% else %>
<p class="text-sm text-warning">This project has no active key. Make one in its settings.</p>
<% end %>
<.link navigate={@setup_path} class="link link-primary text-sm" id="setup-guide">
The full setup guide <.icon name="hero-arrow-right-micro" class="size-3.5" />
</.link>
</section>
"""
end
## Filters
@impl true
def handle_event("search", %{"search" => %{"q" => q}}, socket),
do: {:noreply, push_patch(socket, to: list_path(socket.assigns, %{"q" => String.trim(q)}))}
def handle_event("filter", %{"filters" => f}, socket) do
changes = %{
"env" => f["env"],
"period" => f["period"],
"sort" => if(f["sort"] == "last_seen", do: nil, else: f["sort"])
}
{:noreply, push_patch(socket, to: list_path(socket.assigns, changes))}
end
## Selection
# The checkbox has already toggled in the browser, so the row needn't
# re-render; only the toolbar follows.
def handle_event("toggle", %{"id" => id}, socket) do
selected = socket.assigns.selected
selected =
cond do
id not in socket.assigns.page_ids -> selected
MapSet.member?(selected, id) -> MapSet.delete(selected, id)
true -> MapSet.put(selected, id)
end
{:noreply, assign(socket, :selected, selected)}
end
def handle_event("select_all", _params, socket) do
%{selected: selected, page_ids: ids} = socket.assigns
all? = ids != [] and MapSet.size(selected) == length(ids)
selected = if all?, do: MapSet.new(), else: MapSet.new(ids)
{:noreply, socket |> assign(:selected, selected) |> load()}
end
def handle_event("clear_selection", _params, socket),
do: {:noreply, socket |> assign(:selected, MapSet.new()) |> load()}
## Actions
def handle_event("bulk", %{"action" => action}, socket) when is_map_key(@past, action) do
%{current_scope: scope, project: project, selected: selected} = socket.assigns
cond do
action == "delete" and not socket.assigns.can_delete ->
{:noreply, put_flash(socket, :error, "You can't delete issues here.")}
MapSet.size(selected) == 0 ->
{:noreply, socket}
true ->
op = if action == "assign_me", do: {"assign", scope.user.id}, else: action
n = Issues.bulk(scope, project.id, MapSet.to_list(selected), op)
{:noreply,
socket
|> put_flash(:info, "#{n} #{plural(n, "issue")} #{@past[action]}.")
|> assign(:selected, MapSet.new())
|> load()}
end
end
def handle_event("resolve_issue", %{"id" => id}, socket),
do: one(socket, id, &Issues.resolve(&1, &2), "resolved")
def handle_event("ignore_issue", %{"id" => id}, socket),
do: one(socket, id, &Issues.ignore/2, "ignored")
defp one(socket, id, fun, done) do
%{current_scope: scope, project: project} = socket.assigns
with %{} = issue <- Issues.get_issue(project.id, id),
{:ok, issue} <- fun.(scope, issue) do
{:noreply,
socket
|> put_flash(:info, "#{short_id(project, issue)} #{done}.")
|> load()}
else
_ -> {:noreply, put_flash(socket, :error, "Couldn't change that issue.")}
end
end
## Live updates
@impl true
def handle_info({event, _}, socket) when event in [:issue_event, :issue_updated] do
if socket.assigns.refresh_pending? do
{:noreply, socket}
else
Process.send_after(self(), :refresh, @refresh_ms)
{:noreply, assign(socket, :refresh_pending?, true)}
end
end
# Comments don't change anything the list shows.
def handle_info({:issue_comment, _}, socket), do: {:noreply, socket}
def handle_info(:refresh, socket),
do: {:noreply, socket |> assign(:refresh_pending?, false) |> load()}
end
neiam
/vigil
public · Issues · Pulls · Labels · Forks · Compare · Actions success · Badges · Packages
⭐
Log in to mark this repository.
25.0 KiB · text
History
2f56e4f