Skip to content

The only tool you need to know what is happening and how to fix it.

feat: Metrics dashboard - legends, resizable widgets, stacked area & sparklines, drag-and-drop (#258)

FelineStateMachinef83537049276
diff --git a/CLAUDE.md b/CLAUDE.md
index e16515dc..cda10fb5 100644
--- a/CLAUDE.md
+++ b/CLAUDE.md
@@ -621,7 +621,7 @@ backend/
| DELETE | `/api/widget-groups/:id` | App+Write | Delete widget group |
| POST | `/api/widget-groups/:id/widgets` | App+Write | Add widget |
| PUT | `/api/widget-groups/:id/widgets/:wid` | App+Write | Update widget |
-| PUT | `/api/widget-groups/:id/widgets/:wid/move` | App+Write | Reorder widget |
+| PUT | `/api/widget-groups/:id/reorder` | App+Write | Reorder widgets (explicit id order) |
| DELETE | `/api/widget-groups/:id/widgets/:wid` | App+Write | Delete widget |
**Endpoints**
diff --git a/backend/app/controllers/routes.go b/backend/app/controllers/routes.go
index 0e39415d..51a4d7c8 100644
--- a/backend/app/controllers/routes.go
+++ b/backend/app/controllers/routes.go
@@ -80,7 +80,7 @@ func RegisterControllers(router *gin.RouterGroup) {
router.POST("/widget-groups/:id/widgets", middleware.UseAppAuth, middleware.RequireProjectAccess, middleware.RequireWriteAccess, middleware.Transactional, WidgetController.Add)
router.PUT("/widget-groups/:id/widgets/:wid", middleware.UseAppAuth, middleware.RequireProjectAccess, middleware.RequireWriteAccess, middleware.Transactional, WidgetController.Update)
- router.PUT("/widget-groups/:id/widgets/:wid/move", middleware.UseAppAuth, middleware.RequireProjectAccess, middleware.RequireWriteAccess, middleware.Transactional, WidgetController.Move)
+ router.PUT("/widget-groups/:id/reorder", middleware.UseAppAuth, middleware.RequireProjectAccess, middleware.RequireWriteAccess, middleware.Transactional, WidgetController.Reorder)
router.PUT("/widget-groups/:id/widgets/:wid/star", middleware.UseAppAuth, middleware.RequireProjectAccess, middleware.RequireWriteAccess, middleware.Transactional, WidgetController.ToggleStar)
router.DELETE("/widget-groups/:id/widgets/:wid", middleware.UseAppAuth, middleware.RequireProjectAccess, middleware.RequireWriteAccess, middleware.Transactional, WidgetController.Delete)
diff --git a/backend/app/controllers/widget.controller.go b/backend/app/controllers/widget.controller.go
index 74554086..79c42d4d 100644
--- a/backend/app/controllers/widget.controller.go
+++ b/backend/app/controllers/widget.controller.go
@@ -3,7 +3,6 @@ package controllers
import (
"encoding/json"
"net/http"
- "sort"
"strconv"
"strings"
"time"
@@ -173,11 +172,11 @@ func (c *widgetController) Update(ctx *gin.Context) {
ctx.JSON(http.StatusOK, widget)
}
-type MoveWidgetRequest struct {
- Offset int `json:"offset" binding:"required"`
+type ReorderWidgetsRequest struct {
+ WidgetIds []int `json:"widgetIds" binding:"required,min=1"`
}
-func (c *widgetController) Move(ctx *gin.Context) {
+func (c *widgetController) Reorder(ctx *gin.Context) {
projectId, err := middleware.GetProjectId(ctx)
if err != nil {
ctx.AbortWithError(http.StatusInternalServerError, traceway.NewStackTraceErrorf("RequireProjectAccess middleware must be applied: %w", err))
@@ -191,14 +190,7 @@ func (c *widgetController) Move(ctx *gin.Context) {
return
}
- widgetIdStr := ctx.Param("wid")
- widgetId, err := strconv.Atoi(widgetIdStr)
- if err != nil {
- ctx.JSON(http.StatusBadRequest, gin.H{"error": "Invalid widget id"})
- return
- }
-
- var req MoveWidgetRequest
+ var req ReorderWidgetsRequest
if err := ctx.ShouldBindJSON(&req); err != nil {
ctx.JSON(http.StatusBadRequest, gin.H{"error": "Invalid request body"})
return
@@ -208,7 +200,7 @@ func (c *widgetController) Move(ctx *gin.Context) {
group, err := repositories.WidgetGroupRepository.FindById(tx, groupId)
if err != nil {
- ctx.AbortWithError(http.StatusInternalServerError, traceway.NewStackTraceErrorf("failed to move widget: %w", err))
+ ctx.AbortWithError(http.StatusInternalServerError, traceway.NewStackTraceErrorf("failed to reorder widgets: %w", err))
return
}
if group == nil || group.ProjectId != projectId {
@@ -218,50 +210,44 @@ func (c *widgetController) Move(ctx *gin.Context) {
allWidgets, err := repositories.WidgetGroupRepository.FindWidgetsByGroup(tx, groupId)
if err != nil {
- ctx.AbortWithError(http.StatusInternalServerError, traceway.NewStackTraceErrorf("failed to move widget: %w", err))
+ ctx.AbortWithError(http.StatusInternalServerError, traceway.NewStackTraceErrorf("failed to reorder widgets: %w", err))
return
}
- sort.Slice(allWidgets, func(i, j int) bool {
- return allWidgets[i].Position < allWidgets[j].Position
- })
-
- currentIndex := -1
- for i, w := range allWidgets {
- if w.Id == widgetId {
- currentIndex = i
- break
- }
- }
- if currentIndex == -1 {
- ctx.JSON(http.StatusNotFound, gin.H{"error": "Widget not found"})
- return
+ byId := make(map[int]*models.WidgetGroupWidget, len(allWidgets))
+ for _, w := range allWidgets {
+ byId[w.Id] = w
}
- targetIndex := currentIndex + req.Offset
- if targetIndex < 0 || targetIndex >= len(allWidgets) {
- ctx.JSON(http.StatusBadRequest, gin.H{"error": "cannot move beyond boundary"})
+ if len(req.WidgetIds) != len(allWidgets) {
+ ctx.JSON(http.StatusUnprocessableEntity, gin.H{"error": "The widget list is out of date. Please refresh and try again."})
return
}
- widget := allWidgets[currentIndex]
- targetWidget := allWidgets[targetIndex]
+ seen := make(map[int]bool, len(req.WidgetIds))
+ for _, id := range req.WidgetIds {
+ if byId[id] == nil || seen[id] {
+ ctx.JSON(http.StatusUnprocessableEntity, gin.H{"error": "The widget list is out of date. Please refresh and try again."})
+ return
+ }
+ seen[id] = true
+ }
now := time.Now().UTC()
- widget.Position, targetWidget.Position = targetWidget.Position, widget.Position
- widget.UpdatedAt = now
- targetWidget.UpdatedAt = now
-
- if err := repositories.WidgetGroupRepository.UpdateWidget(tx, targetWidget); err != nil {
- ctx.AbortWithError(http.StatusInternalServerError, traceway.NewStackTraceErrorf("failed to move widget: %w", err))
- return
- }
- if err := repositories.WidgetGroupRepository.UpdateWidget(tx, widget); err != nil {
- ctx.AbortWithError(http.StatusInternalServerError, traceway.NewStackTraceErrorf("failed to move widget: %w", err))
- return
+ for position, id := range req.WidgetIds {
+ w := byId[id]
+ if w.Position == position {
+ continue
+ }
+ w.Position = position
+ w.UpdatedAt = now
+ if err := repositories.WidgetGroupRepository.UpdateWidget(tx, w); err != nil {
+ ctx.AbortWithError(http.StatusInternalServerError, traceway.NewStackTraceErrorf("failed to reorder widgets: %w", err))
+ return
+ }
}
- ctx.JSON(http.StatusOK, gin.H{"moved": true})
+ ctx.JSON(http.StatusOK, gin.H{"reordered": true})
}
func (c *widgetController) Delete(ctx *gin.Context) {
diff --git a/frontend/src/lib/components/dashboard/d3-stacked-area-chart.svelte b/frontend/src/lib/components/dashboard/d3-stacked-area-chart.svelte
index cd5e81d1..8ed787bc 100644
--- a/frontend/src/lib/components/dashboard/d3-stacked-area-chart.svelte
+++ b/frontend/src/lib/components/dashboard/d3-stacked-area-chart.svelte
@@ -3,6 +3,7 @@
import { stack, area, stackOrderReverse } from 'd3-shape';
import { min, max } from 'd3-array';
import { formatDateTime } from '$lib/utils/formatters';
+ import { formatMetricValue } from '$lib/utils/metric-format';
import { getTimezone } from '$lib/state/timezone.svelte';
type DataPoint = {
@@ -23,7 +24,9 @@
padding = { top: 10, right: 4, bottom: 20, left: 55 },
unit = 'ms',
formatValue,
- onRangeSelect
+ onRangeSelect,
+ colors = null,
+ showBuiltinLegend = true
} = $props<{
endpoints: string[];
series: DataPoint[];
@@ -32,6 +35,8 @@
unit?: string;
formatValue?: (value: number) => string;
onRangeSelect?: (from: Date, to: Date) => void;
+ colors?: string[] | null;
+ showBuiltinLegend?: boolean;
}>();
const tz = $derived(getTimezone());
@@ -46,6 +51,8 @@
'var(--muted-foreground)' // For "Other"
];
+ const palette = $derived(colors && colors.length > 0 ? colors : chartColors);
+
let containerRef = $state<HTMLDivElement | null>(null);
let width = $state(300);
@@ -157,14 +164,24 @@
// Generate Y axis ticks
const yTicks = $derived(() => yScale.ticks(4));
- // Format Y axis label
+ // Format Y axis label — scaled number only; the unit is shown once above the axis
function formatYLabel(value: number): string {
+ if (unit) {
+ return formatMetricValue(value, unit).text;
+ }
if (value >= 1000000) return (value / 1000000).toFixed(1) + 'M';
if (value >= 1000) return (value / 1000).toFixed(1) + 'k';
if (Number.isInteger(value)) return value.toString();
return value.toFixed(1);
}
+ const yAxisUnit = $derived(() => {
+ if (!unit) return '';
+ const ticks = yTicks();
+ if (ticks.length === 0) return unit;
+ return formatMetricValue(ticks[ticks.length - 1], unit).unit;
+ });
+
// Generate stacked area paths
const stackedAreas = $derived(() => {
const data = stackedData();
@@ -184,7 +201,7 @@
return stackedSeries.map((s, i) => ({
key: s.key,
path: areaGen(s as unknown as [number, number][]) || '',
- color: chartColors[i % chartColors.length]
+ color: palette[i % palette.length]
}));
});
@@ -321,8 +338,8 @@
// Get color for an endpoint
function getEndpointColor(endpoint: string): string {
const idx = endpoints.indexOf(endpoint);
- if (idx === -1) return chartColors[chartColors.length - 1];
- return chartColors[idx % chartColors.length];
+ if (idx === -1) return palette[palette.length - 1];
+ return palette[idx % palette.length];
}
// Truncate long endpoint names for legend
@@ -377,6 +394,20 @@
</text>
{/each}
+ <!-- Y axis unit label -->
+ {#if yAxisUnit()}
+ <text
+ x={-8}
+ y={-4}
+ text-anchor="end"
+ fill="currentColor"
+ class="text-muted-foreground"
+ font-size="10"
+ >
+ {yAxisUnit()}
+ </text>
+ {/if}
+
<!-- X axis line -->
<line
x1={0}
@@ -477,11 +508,11 @@
</div>
<!-- Legend -->
- {#if hasData}
+ {#if hasData && showBuiltinLegend}
<div class="flex flex-wrap gap-x-4 gap-y-1 px-2 text-xs text-muted-foreground">
{#each endpoints as endpoint, i}
<div class="flex items-center gap-1.5">
- <span class="h-2 w-2 rounded-full flex-shrink-0" style="background-color: {chartColors[i % chartColors.length]};"></span>
+ <span class="h-2 w-2 rounded-full flex-shrink-0" style="background-color: {palette[i % palette.length]};"></span>
<span class="truncate max-w-[180px]" title={endpoint}>{truncateEndpoint(endpoint, 25)}</span>
</div>
{/each}
diff --git a/frontend/src/lib/components/dashboard/sparkline.svelte b/frontend/src/lib/components/dashboard/sparkline.svelte
new file mode 100644
index 00000000..33dba38a
--- /dev/null
+++ b/frontend/src/lib/components/dashboard/sparkline.svelte
@@ -0,0 +1,65 @@
+<script lang="ts">
+ import { scaleUtc, scaleLinear } from 'd3-scale';
+ import { line } from 'd3-shape';
+ import { min, max } from 'd3-array';
+ import type { MetricTrendPoint } from '$lib/types/dashboard';
+
+ let {
+ data = [],
+ color = '#3b82f6',
+ height = 40
+ } = $props<{
+ data: MetricTrendPoint[];
+ color?: string;
+ height?: number;
+ }>();
+
+ let containerRef = $state<HTMLDivElement | null>(null);
+ let width = $state(120);
+
+ $effect(() => {
+ if (!containerRef) return;
+
+ const observer = new ResizeObserver((entries) => {
+ for (const entry of entries) {
+ width = entry.contentRect.width;
+ }
+ });
+
+ observer.observe(containerRef);
+ return () => observer.disconnect();
+ });
+
+ const path = $derived.by(() => {
+ if (data.length < 2 || width <= 0) return '';
+
+ const xScale = scaleUtc()
+ .domain([
+ min(data, (d: MetricTrendPoint) => d.timestamp) ?? new Date(),
+ max(data, (d: MetricTrendPoint) => d.timestamp) ?? new Date()
+ ])
+ .range([1, width - 1]);
+
+ const yMin = min(data, (d: MetricTrendPoint) => d.value) ?? 0;
+ const yMax = max(data, (d: MetricTrendPoint) => d.value) ?? 1;
+ // Flat series would collapse to a zero-height domain; pad so the line stays visible
+ const pad = yMax === yMin ? Math.abs(yMax) * 0.1 || 1 : 0;
+ const yScale = scaleLinear()
+ .domain([yMin - pad, yMax + pad])
+ .range([height - 2, 2]);
+
+ const lineGen = line<MetricTrendPoint>()
+ .x((d) => xScale(d.timestamp))
+ .y((d) => yScale(d.value));
+
+ return lineGen(data) || '';
+ });
+</script>
+
+<div bind:this={containerRef} class="w-full" style="height: {height}px;">
+ {#if path}
+ <svg {width} {height}>
+ <path d={path} fill="none" stroke={color} stroke-width="1.5" stroke-opacity="0.8" />
+ </svg>
+ {/if}
+</div>
diff --git a/frontend/src/lib/components/dashboard/widget-config-panel.svelte b/frontend/src/lib/components/dashboard/widget-config-panel.svelte
index 43874625..8f81d0c6 100644
--- a/frontend/src/lib/components/dashboard/widget-config-panel.svelte
+++ b/frontend/src/lib/components/dashboard/widget-config-panel.svelte
@@ -1,6 +1,7 @@
<script lang="ts">
import { Button } from '$lib/components/ui/button';
import { Input } from '$lib/components/ui/input';
+ import { Checkbox } from '$lib/components/ui/checkbox';
import * as Select from '$lib/components/ui/select';
import * as AlertDialog from '$lib/components/ui/alert-dialog';
import TagFilter from './tag-filter.svelte';
@@ -16,8 +17,17 @@
aggregation: string;
tagFilters?: Record<string, string>;
groupBy?: string;
+ label?: string;
};
+ const CHART_TYPES = ['line_chart', 'area_chart', 'stacked_area'];
+
+ function legendFromConfig(config: any): 'auto' | 'on' | 'off' {
+ if (config?.showLegend === true) return 'on';
+ if (config?.showLegend === false) return 'off';
+ return 'auto';
+ }
+
let {
open = $bindable(false),
widget = null,
@@ -41,6 +51,10 @@
let sources = $state<WidgetSource[]>(
widget?.config?.sources ?? [{ type: 'metric', name: '', aggregation: 'avg' }]
);
+ let colSpan = $state<number>(widget?.config?.colSpan ?? 1);
+ let size = $state<string>(widget?.config?.size ?? 'sm');
+ let legend = $state<'auto' | 'on' | 'off'>(legendFromConfig(widget?.config));
+ let showSparkline = $state(!!widget?.config?.showSparkline);
$effect(() => {
if (open) {
@@ -51,6 +65,10 @@
sources = widget?.config?.sources
? [...widget.config.sources]
: [{ type: 'metric', name: '', aggregation: 'avg' }];
+ colSpan = widget?.config?.colSpan ?? 1;
+ size = widget?.config?.size ?? 'sm';
+ legend = legendFromConfig(widget?.config);
+ showSparkline = !!widget?.config?.showSparkline;
}
});
@@ -84,10 +102,19 @@
}
function handleSave() {
- const validSources = sources.filter((s: WidgetSource) => s.name);
+ const validSources = sources
+ .filter((s: WidgetSource) => s.name)
+ .map((s: WidgetSource) => {
+ const { label, ...rest } = s;
+ return label?.trim() ? { ...rest, label: label.trim() } : rest;
+ });
const displayTitle = title.trim() || validSources[0]?.name || '';
const config: Record<string, any> = { sources: validSources };
if (unit) config.unit = unit;
+ if (colSpan !== 1) config.colSpan = colSpan;
+ if (size !== 'sm') config.size = size;
+ if (CHART_TYPES.includes(widgetType) && legend !== 'auto') config.showLegend = legend === 'on';
+ if (widgetType === 'single_value' && showSparkline) config.showSparkline = true;
onSave({
title: displayTitle,
widgetType,
@@ -129,11 +156,12 @@
}}
>
<Select.Trigger>
- {({ line_chart: 'Line Chart', area_chart: 'Area Chart', bar_chart: 'Bar Chart', single_value: 'Single Value', table: 'Table' } as Record<string, string>)[widgetType] ?? widgetType}
+ {({ line_chart: 'Line Chart', area_chart: 'Area Chart', stacked_area: 'Stacked Area', bar_chart: 'Bar Chart', single_value: 'Single Value', table: 'Table' } as Record<string, string>)[widgetType] ?? widgetType}
</Select.Trigger>
<Select.Content>
<Select.Item value="line_chart">Line Chart</Select.Item>
<Select.Item value="area_chart">Area Chart</Select.Item>
+ <Select.Item value="stacked_area">Stacked Area</Select.Item>
<Select.Item value="bar_chart">Bar Chart</Select.Item>
<Select.Item value="single_value">Single Value</Select.Item>
<Select.Item value="table">Table</Select.Item>
@@ -141,6 +169,86 @@
</Select.Root>
</div>
+ <div class="grid grid-cols-2 gap-2">
+ <div>
+ <label class="text-sm font-medium">Width</label>
+ <Select.Root
+ type="single"
+ value={String(colSpan)}
+ onValueChange={(v) => {
+ if (v) colSpan = Number(v);
+ }}
+ >
+ <Select.Trigger>
+ {({ '1': '1 column', '2': '2 columns', '3': '3 columns (full)' } as Record<string, string>)[String(colSpan)]}
+ </Select.Trigger>
+ <Select.Content>
+ <Select.Item value="1">1 column</Select.Item>
+ <Select.Item value="2">2 columns</Select.Item>
+ <Select.Item value="3">3 columns (full)</Select.Item>
+ </Select.Content>
+ </Select.Root>
+ </div>
+ <div>
+ <label class="text-sm font-medium">Height</label>
+ <Select.Root
+ type="single"
+ value={size}
+ onValueChange={(v) => {
+ if (v) size = v;
+ }}
+ >
+ <Select.Trigger>
+ {({ sm: 'Small', md: 'Medium', lg: 'Large' } as Record<string, string>)[size]}
+ </Select.Trigger>
+ <Select.Content>
+ <Select.Item value="sm">Small</Select.Item>
+ <Select.Item value="md">Medium</Select.Item>
+ <Select.Item value="lg">Large</Select.Item>
+ </Select.Content>
+ </Select.Root>
+ </div>
+ </div>
+
+ {#if CHART_TYPES.includes(widgetType)}
+ <div>
+ <label class="text-sm font-medium">Legend</label>
+ <Select.Root
+ type="single"
+ value={legend}
+ onValueChange={(v) => {
+ if (v) legend = v as 'auto' | 'on' | 'off';
+ }}
+ >
+ <Select.Trigger>
+ {({ auto: 'Auto (when multiple series)', on: 'Always', off: 'Never' } as Record<string, string>)[legend]}
+ </Select.Trigger>
+ <Select.Content>
+ <Select.Item value="auto">Auto (when multiple series)</Select.Item>
+ <Select.Item value="on">Always</Select.Item>
+ <Select.Item value="off">Never</Select.Item>
+ </Select.Content>
+ </Select.Root>
+ </div>
+ {/if}
+
+ {#if widgetType === 'single_value'}
+ <div class="flex items-center gap-2">
+ <Checkbox
+ checked={showSparkline}
+ onCheckedChange={(c) => (showSparkline = c === true)}
+ aria-label="Show sparkline"
+ />
+ <button
+ type="button"
+ class="cursor-pointer text-sm font-medium"
+ onclick={() => (showSparkline = !showSparkline)}
+ >
+ Show sparkline
+ </button>
+ </div>
+ {/if}
+
<div>
<label class="text-sm font-medium" for="widget-unit">Unit (optional)</label>
<Input
@@ -188,6 +296,12 @@
</Select.Root>
</div>
+ <Input
+ bind:value={sources[i].label}
+ placeholder="Label (optional, defaults to metric name)"
+ class="h-8 text-xs"
+ />
+
{#if source.name && getMetricTagKeys(source.name).length > 0}
<div class="space-y-1">
<span class="text-xs text-muted-foreground">Tag Filters</span>
diff --git a/frontend/src/lib/components/dashboard/widget-grid.svelte b/frontend/src/lib/components/dashboard/widget-grid.svelte
index 90a97d9b..f75b9909 100644
--- a/frontend/src/lib/components/dashboard/widget-grid.svelte
+++ b/frontend/src/lib/components/dashboard/widget-grid.svelte
@@ -5,11 +5,8 @@
Plus,
EllipsisVertical,
Pencil,
- Move,
- ArrowUp,
- ArrowDown,
- ArrowLeft,
- ArrowRight,
+ Copy,
+ GripVertical,
Star,
Trash2
} from 'lucide-svelte';
@@ -31,7 +28,8 @@
timeDomain = null,
onEditWidget,
onDeleteWidget,
- onMoveWidget,
+ onReorderWidgets,
+ onDuplicateWidget,
onAddWidget,
onToggleStar,
onRangeSelect
@@ -42,35 +40,99 @@
timeDomain: [Date, Date] | null;
onEditWidget?: (widget: Widget) => void;
onDeleteWidget?: (widget: Widget) => void;
- onMoveWidget?: (widgetId: number, offset: number) => void;
+ onReorderWidgets?: (widgetIds: number[]) => void;
+ onDuplicateWidget?: (widget: Widget) => void;
onAddWidget?: () => void;
onToggleStar?: (widget: Widget) => void;
onRangeSelect?: (from: Date, to: Date) => void;
}>();
let sharedHoverTime = $state<Date | null>(null);
- let cols = $state(3);
-
- $effect(() => {
- const mql = window.matchMedia('(min-width: 768px)');
- const handler = (e: MediaQueryListEvent | MediaQueryList) => {
- cols = e.matches ? 3 : 1;
- };
- handler(mql);
- mql.addEventListener('change', handler);
- return () => mql.removeEventListener('change', handler);
- });
const sortedWidgets = $derived([...widgets].sort((a, b) => a.position - b.position));
+
+ let dragIndex = $state<number | null>(null);
+ let dropIndex = $state<number | null>(null);
+ let cardEls: HTMLElement[] = [];
+
+ function handleDragStart(e: DragEvent, i: number) {
+ dragIndex = i;
+ if (e.dataTransfer) {
+ e.dataTransfer.effectAllowed = 'move';
+ e.dataTransfer.setData('text/plain', String(sortedWidgets[i].id));
+ const card = cardEls[i];
+ if (card) {
+ e.dataTransfer.setDragImage(card, 20, 20);
+ }
+ }
+ }
+
+ function handleDragOver(e: DragEvent, i: number) {
+ if (dragIndex === null) return;
+ e.preventDefault();
+ if (e.dataTransfer) e.dataTransfer.dropEffect = 'move';
+ dropIndex = i;
+ }
+
+ function handleDrop(e: DragEvent, targetIndex: number) {
+ e.preventDefault();
+ if (dragIndex !== null && dragIndex !== targetIndex) {
+ const order = sortedWidgets.map((w: Widget) => w.id);
+ const [moved] = order.splice(dragIndex, 1);
+ order.splice(targetIndex, 0, moved);
+ onReorderWidgets?.(order);
+ }
+ dragIndex = null;
+ dropIndex = null;
+ }
+
+ function handleDragEnd() {
+ dragIndex = null;
+ dropIndex = null;
+ }
+
+ // Static maps — Tailwind can't extract dynamically-built class names
+ const colSpanClass: Record<number, string> = {
+ 1: 'md:col-span-1',
+ 2: 'md:col-span-2',
+ 3: 'md:col-span-3'
+ };
+ const minHeightClass: Record<string, string> = {
+ sm: 'min-h-[240px]',
+ md: 'min-h-[340px]',
+ lg: 'min-h-[460px]'
+ };
</script>
-<div class="grid grid-cols-1 gap-4 md:grid-cols-3">
+<div class="grid grid-cols-1 gap-4 md:grid-cols-3" role="list">
{#each sortedWidgets as widget, i (widget.id)}
- <div>
- <Card.Root class="h-full gap-0">
+ <div
+ bind:this={cardEls[i]}
+ class={colSpanClass[widget.config?.colSpan ?? 1] ?? 'md:col-span-1'}
+ role="listitem"
+ ondragover={(e) => handleDragOver(e, i)}
+ ondrop={(e) => handleDrop(e, i)}
+ >
+ <Card.Root
+ class="group h-full gap-0 {minHeightClass[widget.config?.size ?? 'sm'] ?? 'min-h-[240px]'} transition-opacity {dragIndex === i ? 'opacity-40' : ''} {dropIndex === i && dragIndex !== null && dragIndex !== i ? 'ring-2 ring-primary' : ''}"
+ >
<Card.Header class="pr-2 pb-1">
<div class="flex items-center justify-between">
- <Card.Title class="text-sm font-medium">{widget.title}{#if widget.config?.unit}<span class="text-xs font-normal text-muted-foreground"> ({widget.config.unit})</span>{/if}</Card.Title>
+ <div class="flex min-w-0 items-center gap-1">
+ <span
+ class="-ml-1 inline-flex h-7 w-5 shrink-0 cursor-grab items-center justify-center rounded text-muted-foreground/60 opacity-0 transition-opacity hover:text-foreground focus-visible:opacity-100 group-hover:opacity-100 active:cursor-grabbing"
+ title="Drag to reorder"
+ role="button"
+ tabindex={-1}
+ aria-label="Drag to reorder widget"
+ draggable="true"
+ ondragstart={(e) => handleDragStart(e, i)}
+ ondragend={handleDragEnd}
+ >
+ <GripVertical class="h-4 w-4" />
+ </span>
+ <Card.Title class="truncate text-sm font-medium">{widget.title}{#if widget.config?.unit}<span class="text-xs font-normal text-muted-foreground"> ({widget.config.unit})</span>{/if}</Card.Title>
+ </div>
<div class="flex items-center">
<button
type="button"
@@ -92,44 +154,10 @@
<Pencil class="mr-2 h-4 w-4" />
Edit
</DropdownMenu.Item>
- <DropdownMenu.Sub>
- <DropdownMenu.SubTrigger>
- <Move class="mr-2 h-4 w-4" />
- Move
- </DropdownMenu.SubTrigger>
- <DropdownMenu.SubContent>
- <DropdownMenu.Item
- disabled={i < cols}
- onclick={() => onMoveWidget?.(widget.id, -cols)}
- >
- <ArrowUp class="mr-2 h-4 w-4" />
- Up
- </DropdownMenu.Item>
- <DropdownMenu.Item
- disabled={i > sortedWidgets.length - 1 - cols}
- onclick={() => onMoveWidget?.(widget.id, cols)}
- >
- <ArrowDown class="mr-2 h-4 w-4" />
- Down
- </DropdownMenu.Item>
- {#if cols > 1}
- <DropdownMenu.Item
- disabled={i % cols === 0}
- onclick={() => onMoveWidget?.(widget.id, -1)}
- >
- <ArrowLeft class="mr-2 h-4 w-4" />
- Left
- </DropdownMenu.Item>
- <DropdownMenu.Item
- disabled={i % cols === cols - 1 || i + 1 >= sortedWidgets.length}
- onclick={() => onMoveWidget?.(widget.id, 1)}
- >
- <ArrowRight class="mr-2 h-4 w-4" />
- Right
- </DropdownMenu.Item>
- {/if}
- </DropdownMenu.SubContent>
- </DropdownMenu.Sub>
+ <DropdownMenu.Item onclick={() => onDuplicateWidget?.(widget)}>
+ <Copy class="mr-2 h-4 w-4" />
+ Duplicate
+ </DropdownMenu.Item>
<DropdownMenu.Separator />
<DropdownMenu.Item
class="text-destructive"
@@ -143,7 +171,7 @@
</div>
</div>
</Card.Header>
- <Card.Content class="p-1">
+ <Card.Content class="min-h-0 flex-1 p-1">
<WidgetRenderer
{widget}
{fromDateUTC}
diff --git a/frontend/src/lib/components/dashboard/widget-renderer.svelte b/frontend/src/lib/components/dashboard/widget-renderer.svelte
index 0aebf849..0e972bbe 100644
--- a/frontend/src/lib/components/dashboard/widget-renderer.svelte
+++ b/frontend/src/lib/components/dashboard/widget-renderer.svelte
@@ -1,12 +1,15 @@
<script lang="ts">
import D3LineChart from './d3-line-chart.svelte';
import D3HorizontalBarChart from './d3-horizontal-bar-chart.svelte';
+ import D3StackedAreaChart from './d3-stacked-area-chart.svelte';
import WidgetTable from './widget-table.svelte';
+ import Sparkline from './sparkline.svelte';
+ import { SvelteSet } from 'svelte/reactivity';
import { api } from '$lib/api';
import { projectsState } from '$lib/state/projects.svelte';
import { LoadingCircle } from '$lib/components/ui/loading-circle';
import type { MetricTrendPoint, MetricQueryResponse } from '$lib/types/dashboard';
- import { formatMetricLabel } from '$lib/utils/metric-format';
+ import { formatMetricLabel, formatMetricValue } from '$lib/utils/metric-format';
type WidgetSource = {
type: 'metric';
@@ -14,6 +17,7 @@
tagFilters?: Record<string, string>;
aggregation: string;
groupBy?: string;
+ label?: string;
};
type WidgetConfig = {
@@ -21,6 +25,9 @@
yAxisLabel?: string;
showLegend?: boolean;
unit?: string;
+ colSpan?: 1 | 2 | 3;
+ size?: 'sm' | 'md' | 'lg';
+ showSparkline?: boolean;
};
let {
@@ -57,6 +64,31 @@
const effectiveUnit = $derived(widget.config.unit ?? resolvedUnit);
+ // Fallbacks for the first render; once mounted the chart fills the measured card space
+ const chartHeights: Record<string, number> = { sm: 200, md: 300, lg: 420 };
+ let chartAreaHeight = $state(0);
+ const chartHeight = $derived(
+ chartAreaHeight > 0 ? chartAreaHeight : (chartHeights[widget.config.size ?? 'sm'] ?? 200)
+ );
+
+ let hiddenSeries = new SvelteSet<string>();
+ const visibleSeries = $derived(series.filter((s) => !hiddenSeries.has(s.key)));
+
+ function toggleSeries(key: string) {
+ if (hiddenSeries.has(key)) {
+ hiddenSeries.delete(key);
+ } else {
+ hiddenSeries.add(key);
+ }
+ }
+
+ const legendVisible = $derived(
+ ['line_chart', 'area_chart', 'stacked_area'].includes(widget.widgetType) &&
+ series.length > 0 &&
+ (widget.config.showLegend === true ||
+ (widget.config.showLegend !== false && series.length > 1))
+ );
+
async function loadData() {
const sources = widget.config.sources;
if (!sources || sources.length === 0) {
@@ -83,10 +115,11 @@
);
const units = new Set<string>();
- for (const result of response.results) {
+ for (const [idx, result] of response.results.entries()) {
if (result.unit) units.add(result.unit);
+ const baseName = sources[idx]?.label?.trim() || result.name;
for (const [key, points] of Object.entries(result.series)) {
- const label = Object.keys(result.series).length > 1 ? `${result.name} (${key})` : result.name;
+ const label = Object.keys(result.series).length > 1 ? `${baseName} (${key})` : baseName;
newSeries.push({
key: label,
data: points.map((p) => ({
@@ -124,22 +157,63 @@
value: s.data.length > 0 ? s.data[s.data.length - 1].value : 0
}))
);
+
+ const stackedPoints = $derived(
+ visibleSeries.flatMap((s) =>
+ s.data.map((p) => ({ timestamp: p.timestamp, endpoint: s.key, value: p.value }))
+ )
+ );
+
+ // Widen the y-axis gutter to fit the largest tick label (e.g. "139.7 GB"),
+ // which the charts' fixed default would clip
+ const axisMaxValue = $derived.by(() => {
+ if (widget.widgetType === 'stacked_area') {
+ const sums = new Map<number, number>();
+ for (const s of visibleSeries) {
+ for (const p of s.data) {
+ const t = p.timestamp.getTime();
+ sums.set(t, (sums.get(t) ?? 0) + p.value);
+ }
+ }
+ return sums.size > 0 ? Math.max(...sums.values()) * 1.1 : 0;
+ }
+ let m = 0;
+ for (const s of visibleSeries) {
+ for (const p of s.data) {
+ if (p.value > m) m = p.value;
+ }
+ }
+ return m * 1.1;
+ });
+
+ const chartPadding = $derived.by(() => {
+ // Ticks show the scaled number; the unit renders once above the axis
+ const { text, unit: axisUnit } = formatMetricValue(axisMaxValue || 0, effectiveUnit);
+ const chars = Math.max(text.length, axisUnit.length);
+ return { top: 10, right: 4, bottom: 20, left: Math.max(45, Math.round(chars * 6.5) + 16) };
+ });
</script>
-<div class="h-full w-full min-h-[200px]">
+<div class="flex h-full w-full min-h-[200px] flex-col">
+ <div class="min-h-0 w-full flex-1" bind:clientHeight={chartAreaHeight}>
{#if loading}
<div class="flex h-full items-center justify-center">
<LoadingCircle size="md" />
</div>
{:else if widget.widgetType === 'single_value'}
- <div class="flex h-full flex-col items-center justify-center">
+ <div class="flex h-full flex-col items-center justify-center gap-2">
<span class="text-3xl font-bold">
{singleValue !== null ? formatMetricLabel(singleValue, effectiveUnit) : '-'}
</span>
+ {#if widget.config.showSparkline && series[0]?.data && series[0].data.length > 1}
+ <div class="w-full px-6">
+ <Sparkline data={series[0].data} color={series[0].color} />
+ </div>
+ {/if}
</div>
{:else if widget.widgetType === 'bar_chart'}
{#if barData.length > 0}
- <D3HorizontalBarChart data={barData} height={200} unit={effectiveUnit} formatValue={(v) => formatMetricLabel(v, effectiveUnit)} />
+ <D3HorizontalBarChart data={barData} height={chartHeight} unit={effectiveUnit} formatValue={(v) => formatMetricLabel(v, effectiveUnit)} />
{:else}
<div class="flex h-full items-center justify-center text-sm text-muted-foreground">
No data
@@ -156,12 +230,12 @@
{:else if widget.widgetType === 'area_chart'}
{#if series.length > 0}
<D3LineChart
- {series}
+ series={visibleSeries}
xDomain={timeDomain ?? undefined}
- height={200}
- padding={{ top: 10, right: 4, bottom: 20, left: 45 }}
+ height={chartHeight}
+ padding={chartPadding}
{onRangeSelect}
- data={series[0]?.data ?? []}
+ data={visibleSeries[0]?.data ?? []}
areaFill={true}
unit={effectiveUnit}
formatValue={(v) => formatMetricLabel(v, effectiveUnit)}
@@ -174,14 +248,32 @@
No data
</div>
{/if}
+ {:else if widget.widgetType === 'stacked_area'}
+ {#if series.length > 0}
+ <D3StackedAreaChart
+ endpoints={visibleSeries.map((s) => s.key)}
+ series={stackedPoints}
+ height={chartHeight}
+ padding={chartPadding}
+ unit={effectiveUnit}
+ formatValue={(v) => formatMetricLabel(v, effectiveUnit)}
+ {onRangeSelect}
+ colors={visibleSeries.map((s) => s.color)}
+ showBuiltinLegend={false}
+ />
+ {:else}
+ <div class="flex h-full items-center justify-center text-sm text-muted-foreground">
+ No data
+ </div>
+ {/if}
{:else if series.length > 0}
<D3LineChart
- {series}
+ series={visibleSeries}
xDomain={timeDomain ?? undefined}
- height={200}
- padding={{ top: 10, right: 4, bottom: 20, left: 45 }}
+ height={chartHeight}
+ padding={chartPadding}
{onRangeSelect}
- data={series[0]?.data ?? []}
+ data={visibleSeries[0]?.data ?? []}
unit={effectiveUnit}
formatValue={(v) => formatMetricLabel(v, effectiveUnit)}
{sharedHoverTime}
@@ -193,4 +285,21 @@
No data
</div>
{/if}
+ </div>
+
+ {#if legendVisible && !loading}
+ <div class="flex flex-wrap gap-x-3 gap-y-1 px-2 pt-1">
+ {#each series as s (s.key)}
+ <button
+ type="button"
+ class="flex items-center gap-1.5 text-xs transition-opacity {hiddenSeries.has(s.key) ? 'opacity-40' : ''}"
+ onclick={() => toggleSeries(s.key)}
+ title={s.key}
+ >
+ <span class="h-2 w-2 flex-shrink-0 rounded-full" style="background-color: {s.color};"></span>
+ <span class="max-w-[180px] truncate text-muted-foreground {hiddenSeries.has(s.key) ? 'line-through' : ''}">{s.key}</span>
+ </button>
+ {/each}
+ </div>
+ {/if}
</div>
diff --git a/frontend/src/routes/metrics/+page.svelte b/frontend/src/routes/metrics/+page.svelte
index 290599b0..d56c6fc9 100644
--- a/frontend/src/routes/metrics/+page.svelte
+++ b/frontend/src/routes/metrics/+page.svelte
@@ -22,7 +22,7 @@
updateUrl
} from '$lib/utils/url-params';
import { CalendarDate } from '@internationalized/date';
- import { Trash2, Plus, RefreshCw, CircleAlert, EllipsisVertical, Sparkles } from 'lucide-svelte';
+ import { Trash2, Plus, Pencil, Check, RefreshCw, CircleAlert, EllipsisVertical, Sparkles } from 'lucide-svelte';
import * as Alert from '$lib/components/ui/alert';
import * as DropdownMenu from '$lib/components/ui/dropdown-menu';
import { toast } from 'svelte-sonner';
@@ -69,6 +69,11 @@
let deleting = $state(false);
let deleteError = $state('');
+ let showRenameDialog = $state(false);
+ let renameName = $state('');
+ let renaming = $state(false);
+ let renameError = $state('');
+
let showWidgetConfig = $state(false);
let editingWidget = $state<Widget | null>(null);
let availableMetrics = $state<DiscoveredMetric[]>([]);
@@ -248,6 +253,37 @@
}
}
+ function openRenameDialog() {
+ renameName = activeGroup?.name ?? activeTabName;
+ renameError = '';
+ showRenameDialog = true;
+ }
+
+ async function renameWidgetGroup() {
+ if (!activeGroup) return;
+ renaming = true;
+ renameError = '';
+ try {
+ await api.put(
+ `/widget-groups/${activeGroup.id}`,
+ { name: renameName, description: activeGroup.description },
+ { projectId: projectsState.currentProjectId ?? undefined }
+ );
+ toast.success('Successfully updated the Widget Group', { position: 'top-center' });
+ showRenameDialog = false;
+ activeGroup.name = renameName;
+ await loadWidgetGroups();
+ } catch (e: any) {
+ if (e?.status === 422) {
+ renameError = e.message;
+ } else {
+ console.error('Failed to rename widget group:', e);
+ }
+ } finally {
+ renaming = false;
+ }
+ }
+
async function deleteWidgetGroup() {
if (!activeGroup) return;
deleting = true;
@@ -375,18 +411,43 @@
}
}
- async function handleMoveWidget(widgetId: number, offset: number) {
+ async function handleReorderWidgets(widgetIds: number[]) {
if (!activeGroup) return;
+ const previousPositions = new Map(activeGroup.widgets.map((w) => [w.id, w.position]));
+ for (const w of activeGroup.widgets) {
+ w.position = widgetIds.indexOf(w.id);
+ }
try {
await api.put(
- `/widget-groups/${activeGroup.id}/widgets/${widgetId}/move`,
- { offset },
+ `/widget-groups/${activeGroup.id}/reorder`,
+ { widgetIds },
{ projectId: projectsState.currentProjectId ?? undefined }
);
+ } catch (e: any) {
+ for (const w of activeGroup.widgets) {
+ w.position = previousPositions.get(w.id) ?? w.position;
+ }
+ toast.error(e?.message || 'Failed to reorder widgets', { position: 'top-center' });
await loadGroupWidgets(activeTabId);
- toast.success('Successfully moved the Widget', { position: 'top-center' });
- } catch (e) {
- console.error('Failed to move widget:', e);
+ }
+ }
+
+ async function handleDuplicateWidget(widget: Widget) {
+ if (!activeGroup) return;
+ try {
+ await api.post(
+ `/widget-groups/${activeGroup.id}/widgets`,
+ {
+ title: `${widget.title} (copy)`,
+ widgetType: widget.widgetType,
+ config: widget.config
+ },
+ { projectId: projectsState.currentProjectId ?? undefined }
+ );
+ toast.success('Successfully duplicated the Widget', { position: 'top-center' });
+ await loadGroupWidgets(activeTabId);
+ } catch (e: any) {
+ toast.error(e?.message || 'Failed to duplicate widget', { position: 'top-center' });
}
}
@@ -526,6 +587,11 @@
{/snippet}
</DropdownMenu.Trigger>
<DropdownMenu.Content align="start">
+ <DropdownMenu.Item onclick={openRenameDialog}>
+ <Pencil class="mr-2 h-4 w-4" />
+ Rename Group
+ </DropdownMenu.Item>
+ <DropdownMenu.Separator />
<DropdownMenu.Item
class="text-destructive"
onclick={() => (showDeleteDialog = true)}
@@ -554,6 +620,11 @@
<EllipsisVertical class="h-4 w-4" />
</DropdownMenu.Trigger>
<DropdownMenu.Content align="end">
+ <DropdownMenu.Item onclick={openRenameDialog}>
+ <Pencil class="mr-2 h-4 w-4" />
+ Rename Group
+ </DropdownMenu.Item>
+ <DropdownMenu.Separator />
<DropdownMenu.Item class="text-destructive" onclick={() => (showDeleteDialog = true)}>
<Trash2 class="mr-2 h-4 w-4" />
Delete Group
@@ -587,7 +658,8 @@
timeDomain={sharedTimeDomain}
onEditWidget={openEditWidget}
onDeleteWidget={openDeleteWidgetDialog}
- onMoveWidget={handleMoveWidget}
+ onReorderWidgets={handleReorderWidgets}
+ onDuplicateWidget={handleDuplicateWidget}
onAddWidget={openAddWidget}
onToggleStar={handleToggleStar}
onRangeSelect={handleChartRangeSelect}
@@ -644,6 +716,43 @@
</AlertDialog.Content>
</AlertDialog.Root>
+<AlertDialog.Root
+ bind:open={showRenameDialog}
+ onOpenChange={(o) => {
+ if (!o) renameError = '';
+ }}
+>
+ <AlertDialog.Content interactOutsideBehavior="close">
+ <AlertDialog.Header>
+ <AlertDialog.Title>Rename Widget Group</AlertDialog.Title>
+ </AlertDialog.Header>
+ {#if renameError}
+ <Alert.Root variant="destructive" class="border-red-200 bg-red-50">
+ <CircleAlert class="h-4 w-4 text-red-700" />
+ <Alert.Title class="text-red-800">Error</Alert.Title>
+ <Alert.Description class="text-red-700">{renameError}</Alert.Description>
+ </Alert.Root>
+ {/if}
+ <div class="space-y-4">
+ <div>
+ <label class="text-sm font-medium" for="rename-group-name">Name</label>
+ <Input
+ id="rename-group-name"
+ bind:value={renameName}
+ placeholder="My Group"
+ maxlength={12}
+ />
+ </div>
+ </div>
+ <AlertDialog.Footer>
+ <Button variant="outline" onclick={() => (showRenameDialog = false)}>Cancel</Button>
+ <Button onclick={renameWidgetGroup} disabled={renaming}>
+ {#if renaming}Updating...{:else}<Check class="mr-1 h-4 w-4" /> Update Widget Group{/if}
+ </Button>
+ </AlertDialog.Footer>
+ </AlertDialog.Content>
+</AlertDialog.Root>
+
<AlertDialog.Root
bind:open={showDeleteDialog}
onOpenChange={(o) => {