feat(monitor): add search, status filter, and bulk invalid toggle

- Add search input to filter alerts by alertName or label values
- Add status filter dropdown (All/Resolved/Unresolved)
- Add Select All checkbox with indeterminate state for bulk invalid toggle
- Add indeterminate prop support to Checkbox component
- Add Monitor link to header navigation
- Fix KPI dashboard padding for empty state
This commit is contained in:
Syahdan 2025-12-29 07:12:31 +07:00
parent 22aee93fb3
commit c145d3fb07
8 changed files with 155 additions and 21 deletions

View file

@ -106,6 +106,31 @@ pub struct ProcessedAlert {
pub is_invalid: bool,
pub attached_incident_id: Option<String>,
pub values: HashMap<String, f64>,
pub labels: HashMap<String, String>,
}
fn parse_labels_from_text(text: &str) -> HashMap<String, String> {
let mut labels = HashMap::new();
if let Some(start) = text.find('{') {
if let Some(end) = text.rfind('}') {
if start < end {
let content = &text[start + 1..end];
for pair in content.split(',') {
let pair = pair.trim();
if let Some(eq_pos) = pair.find('=') {
let key = pair[..eq_pos].trim().to_string();
let value = pair[eq_pos + 1..].trim().to_string();
if !key.is_empty() {
labels.insert(key, value);
}
}
}
}
}
}
labels
}
pub fn pair_alerts(raw_alerts: Vec<GrafanaAlert>) -> Vec<ProcessedAlert> {
@ -126,6 +151,8 @@ pub fn pair_alerts(raw_alerts: Vec<GrafanaAlert>) -> Vec<ProcessedAlert> {
let current = &alerts[i];
if current.new_state == "Alerting" {
let labels = parse_labels_from_text(&current.text);
if i + 1 < alerts.len() && alerts[i + 1].new_state == "Normal" {
let resolve = &alerts[i + 1];
let duration_ms = resolve.time.saturating_sub(current.time);
@ -142,6 +169,7 @@ pub fn pair_alerts(raw_alerts: Vec<GrafanaAlert>) -> Vec<ProcessedAlert> {
is_invalid: false,
attached_incident_id: None,
values: current.data.clone().map(|d| d.values).unwrap_or_default(),
labels,
});
i += 2;
} else {
@ -157,6 +185,7 @@ pub fn pair_alerts(raw_alerts: Vec<GrafanaAlert>) -> Vec<ProcessedAlert> {
is_invalid: false,
attached_incident_id: None,
values: current.data.clone().map(|d| d.values).unwrap_or_default(),
labels,
});
i += 1;
}
@ -208,7 +237,7 @@ pub fn calculate_kpis(alerts: &[ProcessedAlert], incidents: &[Incident]) -> KpiM
let overall_downtime_ms: u64 = alerts
.iter()
.filter(|a| !a.is_invalid)
.filter(|a| !a.is_invalid && a.attached_incident_id.is_some())
.map(|a| a.duration_ms)
.sum();

View file

@ -3,7 +3,7 @@ import { Link } from "@tanstack/react-router";
import { ModeToggle } from "./mode-toggle";
export default function Header() {
const links = [{ to: "/", label: "Home" }] as const;
const links = [{ to: "/", label: "Home" }, { to: '/monitor', label: 'Monitor' }] as const;
return (
<div>

View file

@ -137,11 +137,9 @@ export const AlertListItem = React.memo(
</div>
<div className="truncate text-[10px] text-muted-foreground/70 font-mono">
{Object.entries(alert.values)
.map(
([k, v]) =>
`${k}=${Number.isFinite(v) ? v.toFixed(1) : String(v)}`,
)
{Object.entries(alert.labels)
.filter(([k]) => k !== "alertname")
.map(([k, v]) => `${k}=${v}`)
.join(", ")}
</div>
</div>

View file

@ -1,7 +1,7 @@
import { Card, CardContent, CardHeader, CardTitle } from "@/components/ui/card";
import { Skeleton } from "@/components/ui/skeleton";
import { cn } from "@/lib/utils";
import type { KpiMetrics } from "@/lib/types/alerts";
import { cn } from "@/lib/utils";
interface KpiDashboardProps {
kpis: KpiMetrics | null;
@ -51,7 +51,7 @@ export function KpiDashboard({ kpis, isLoading = false }: KpiDashboardProps) {
if (!kpis) {
return (
<Card className="rounded-none">
<CardContent className="pt-6 text-center text-xs text-muted-foreground">
<CardContent className="py-6 text-center text-xs text-muted-foreground">
No KPI data available
</CardContent>
</Card>

View file

@ -1,14 +1,19 @@
import { Checkbox as CheckboxPrimitive } from "@base-ui/react/checkbox";
import { CheckIcon } from "lucide-react";
import { CheckIcon, MinusIcon } from "lucide-react";
import { cn } from "@/lib/utils";
function Checkbox({ className, ...props }: CheckboxPrimitive.Root.Props) {
function Checkbox({
className,
indeterminate,
...props
}: CheckboxPrimitive.Root.Props & { indeterminate?: boolean }) {
return (
<CheckboxPrimitive.Root
data-slot="checkbox"
indeterminate={indeterminate}
className={cn(
"border-input dark:bg-input/30 data-checked:bg-primary data-checked:text-primary-foreground dark:data-checked:bg-primary data-checked:border-primary aria-invalid:aria-checked:border-primary aria-invalid:border-destructive dark:aria-invalid:border-destructive/50 focus-visible:border-ring focus-visible:ring-ring/50 aria-invalid:ring-destructive/20 dark:aria-invalid:ring-destructive/40 flex size-4 items-center justify-center rounded-none border transition-colors group-has-disabled/field:opacity-50 focus-visible:ring-1 aria-invalid:ring-1 peer relative shrink-0 outline-none after:absolute after:-inset-x-3 after:-inset-y-2 disabled:cursor-not-allowed disabled:opacity-50",
"border-input dark:bg-input/30 data-checked:bg-primary data-checked:text-primary-foreground dark:data-checked:bg-primary data-checked:border-primary aria-invalid:aria-checked:border-primary aria-invalid:border-destructive dark:aria-invalid:border-destructive/50 focus-visible:border-ring focus-visible:ring-ring/50 aria-invalid:ring-destructive/20 dark:aria-invalid:ring-destructive/40 data-indeterminate:bg-primary data-indeterminate:text-primary-foreground data-indeterminate:border-primary flex size-4 items-center justify-center rounded-none border transition-colors group-has-disabled/field:opacity-50 focus-visible:ring-1 aria-invalid:ring-1 peer relative shrink-0 outline-none after:absolute after:-inset-x-3 after:-inset-y-2 disabled:cursor-not-allowed disabled:opacity-50",
className,
)}
{...props}
@ -17,7 +22,7 @@ function Checkbox({ className, ...props }: CheckboxPrimitive.Root.Props) {
data-slot="checkbox-indicator"
className="[&>svg]:size-3.5 grid place-content-center text-current transition-none"
>
<CheckIcon />
{indeterminate ? <MinusIcon /> : <CheckIcon />}
</CheckboxPrimitive.Indicator>
</CheckboxPrimitive.Root>
);

View file

@ -10,6 +10,7 @@ export interface ProcessedAlert {
isInvalid: boolean;
attachedIncidentId: string | null;
values: Record<string, number>;
labels: Record<string, string>;
}
export interface Incident {

View file

@ -1,4 +1,4 @@
import { createFileRoute, Link } from "@tanstack/react-router";
import { createFileRoute } from "@tanstack/react-router";
export const Route = createFileRoute("/")({
component: HomeComponent,
@ -29,9 +29,6 @@ function HomeComponent() {
<h2 className="mb-2 font-medium">API Status</h2>
</section>
</div>
<Link to="/monitor" className="text-blue-500 underline">
Go to Monitor Page
</Link>
</div>
);
}

View file

@ -2,7 +2,7 @@ import { createFileRoute } from "@tanstack/react-router";
import { invoke } from "@tauri-apps/api/core";
import { open } from "@tauri-apps/plugin-dialog";
import { readTextFile } from "@tauri-apps/plugin-fs";
import { FileUp } from "lucide-react";
import { FileUp, Filter, Search } from "lucide-react";
import * as React from "react";
import { AlertList } from "@/components/monitor/alert-list";
@ -10,8 +10,19 @@ import { IncidentManager } from "@/components/monitor/incident-manager";
import { KpiDashboard } from "@/components/monitor/kpi-dashboard";
import { Button } from "@/components/ui/button";
import { Card, CardContent, CardHeader, CardTitle } from "@/components/ui/card";
import { Checkbox } from "@/components/ui/checkbox";
import {
DropdownMenu,
DropdownMenuContent,
DropdownMenuRadioGroup,
DropdownMenuRadioItem,
DropdownMenuTrigger,
} from "@/components/ui/dropdown-menu";
import { Input } from "@/components/ui/input";
import type { Incident, KpiMetrics, ProcessedAlert } from "@/lib/types/alerts";
type StatusFilter = "all" | "resolved" | "unresolved";
export const Route = createFileRoute("/monitor")({
component: MonitorPage,
});
@ -24,6 +35,34 @@ function MonitorPage() {
React.useState<ProcessedAlert | null>(null);
const [isLoading, setIsLoading] = React.useState(false);
const [error, setError] = React.useState<string | null>(null);
const [searchQuery, setSearchQuery] = React.useState("");
const [statusFilter, setStatusFilter] = React.useState<StatusFilter>("all");
const filteredAlerts = React.useMemo(() => {
return alerts.filter((alert) => {
if (statusFilter === "resolved" && !alert.isResolved) return false;
if (statusFilter === "unresolved" && alert.isResolved) return false;
if (!searchQuery.trim()) return true;
const query = searchQuery.toLowerCase();
if (alert.alertName?.toLowerCase().includes(query)) return true;
for (const value of Object.values(alert.labels)) {
if (value.toLowerCase().includes(query)) return true;
}
return false;
});
}, [alerts, searchQuery, statusFilter]);
const selectAllState = React.useMemo(() => {
if (filteredAlerts.length === 0) return "none" as const;
const invalidCount = filteredAlerts.filter((a) => a.isInvalid).length;
if (invalidCount === 0) return "none" as const;
if (invalidCount === filteredAlerts.length) return "all" as const;
return "some" as const;
}, [filteredAlerts]);
const recalculateKpis = React.useCallback(
async (currentAlerts: ProcessedAlert[], currentIncidents: Incident[]) => {
@ -86,6 +125,21 @@ function MonitorPage() {
}
};
const handleToggleAllInvalid = (isInvalid: boolean) => {
const filteredIds = new Set(filteredAlerts.map((a) => a.id));
setAlerts((prev) => {
const updated = prev.map((a) =>
filteredIds.has(a.id) ? { ...a, isInvalid } : a,
);
recalculateKpis(updated, incidents);
return updated;
});
if (selectedAlert && filteredIds.has(selectedAlert.id)) {
setSelectedAlert((prev) => (prev ? { ...prev, isInvalid } : null));
}
};
const handleSelectAlert = (alert: ProcessedAlert) => {
setSelectedAlert(alert);
};
@ -174,10 +228,60 @@ function MonitorPage() {
<div className="grid min-h-0 flex-1 grid-cols-[1fr_360px]">
<div className="flex min-h-0 flex-col border-r">
<div className="shrink-0 border-b px-4 py-2">
<div className="flex shrink-0 items-center gap-2 border-b px-4 py-2">
<Checkbox
checked={selectAllState === "all"}
indeterminate={selectAllState === "some"}
onCheckedChange={(checked) =>
handleToggleAllInvalid(checked === true)
}
disabled={filteredAlerts.length === 0}
aria-label="Mark all filtered as invalid"
/>
<span className="text-xs font-medium text-muted-foreground">
Alerts ({alerts.length})
{filteredAlerts.length}
{(searchQuery || statusFilter !== "all") && ` / ${alerts.length}`}
</span>
<DropdownMenu>
<DropdownMenuTrigger
render={
<Button variant="ghost" size="sm" className="h-7 gap-1 px-2">
<Filter className="size-3" />
<span className="text-xs">
{statusFilter === "all"
? "All"
: statusFilter === "resolved"
? "Resolved"
: "Unresolved"}
</span>
</Button>
}
/>
<DropdownMenuContent align="start">
<DropdownMenuRadioGroup
value={statusFilter}
onValueChange={(v) => setStatusFilter(v as StatusFilter)}
>
<DropdownMenuRadioItem value="all">All</DropdownMenuRadioItem>
<DropdownMenuRadioItem value="resolved">
Resolved
</DropdownMenuRadioItem>
<DropdownMenuRadioItem value="unresolved">
Unresolved
</DropdownMenuRadioItem>
</DropdownMenuRadioGroup>
</DropdownMenuContent>
</DropdownMenu>
<div className="relative ml-auto flex-1 max-w-xs">
<Search className="absolute left-2 top-1/2 size-3 -translate-y-1/2 text-muted-foreground" />
<Input
type="text"
placeholder="Search alerts..."
value={searchQuery}
onChange={(e) => setSearchQuery(e.target.value)}
className="h-7 pl-7 text-xs"
/>
</div>
</div>
{alerts.length === 0 ? (
<div className="flex flex-1 items-center justify-center">
@ -193,7 +297,7 @@ function MonitorPage() {
</div>
) : (
<AlertList
alerts={alerts}
alerts={filteredAlerts}
incidents={incidents}
onToggleInvalid={handleToggleInvalid}
onSelectAlert={handleSelectAlert}