Skip to content

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

major metrics improvements

dduxa6bd8fb51314
diff --git a/backend/app/controllers/dashboard.controller.go b/backend/app/controllers/dashboard.controller.go
index baffd2d5..e6e7ebaf 100644
--- a/backend/app/controllers/dashboard.controller.go
+++ b/backend/app/controllers/dashboard.controller.go
@@ -44,52 +44,80 @@ func (d dashboardController) GetDashboard(c *gin.Context) {
projectId := c.Query("projectId")
now := time.Now()
- start := now.Add(-24 * time.Hour)
- prevStart := now.Add(-48 * time.Hour)
+ var start, end time.Time
+
+ // Parse fromDate parameter
+ if fromDateStr := c.Query("fromDate"); fromDateStr != "" {
+ if parsed, err := time.Parse(time.RFC3339, fromDateStr); err == nil {
+ start = parsed
+ } else {
+ start = now.Add(-24 * time.Hour)
+ }
+ } else {
+ start = now.Add(-24 * time.Hour)
+ }
+
+ // Parse toDate parameter
+ if toDateStr := c.Query("toDate"); toDateStr != "" {
+ if parsed, err := time.Parse(time.RFC3339, toDateStr); err == nil {
+ end = parsed
+ } else {
+ end = now
+ }
+ } else {
+ end = now
+ }
+
+ // Calculate previous period for comparison (same duration before start)
+ duration := end.Sub(start)
+ prevStart := start.Add(-duration)
prevEnd := start
+ // Calculate aggregation interval based on time range
+ intervalMinutes := calculateIntervalMinutes(duration)
+
metrics := make([]models.DashboardMetric, 0, 11)
// 1. Requests count
- requestsTrend, err := repositories.TransactionRepository.CountByHour(c, projectId, start, now)
+ requestsTrend, err := repositories.TransactionRepository.CountByInterval(c, projectId, start, end, intervalMinutes)
if err != nil {
panic(err)
}
- requestsCurrent, _ := repositories.TransactionRepository.CountBetween(c, projectId, start, now)
+ requestsCurrent, _ := repositories.TransactionRepository.CountBetween(c, projectId, start, end)
requestsPrev, _ := repositories.TransactionRepository.CountBetween(c, projectId, prevStart, prevEnd)
metrics = append(metrics, buildMetric("requests", "Requests", float64(requestsCurrent), "count", requestsTrend, float64(requestsPrev), "requests"))
// 2. Exceptions count
- exceptionsTrend, err := repositories.ExceptionStackTraceRepository.CountByHour(c, projectId, start, now)
+ exceptionsTrend, err := repositories.ExceptionStackTraceRepository.CountByInterval(c, projectId, start, end, intervalMinutes)
if err != nil {
panic(err)
}
- exceptionsCurrent, _ := repositories.ExceptionStackTraceRepository.CountBetween(c, projectId, start, now)
+ exceptionsCurrent, _ := repositories.ExceptionStackTraceRepository.CountBetween(c, projectId, start, end)
exceptionsPrev, _ := repositories.ExceptionStackTraceRepository.CountBetween(c, projectId, prevStart, prevEnd)
metrics = append(metrics, buildMetric("exceptions", "Exceptions", float64(exceptionsCurrent), "count", exceptionsTrend, float64(exceptionsPrev), "exceptions"))
// 3. Average Response Time
- avgDurationTrend, err := repositories.TransactionRepository.AvgDurationByHour(c, projectId, start, now)
+ avgDurationTrend, err := repositories.TransactionRepository.AvgDurationByInterval(c, projectId, start, end, intervalMinutes)
if err != nil {
panic(err)
}
avgDurationCurrent := getLastValue(avgDurationTrend)
- avgDurationPrevTrend, _ := repositories.TransactionRepository.AvgDurationByHour(c, projectId, prevStart, prevEnd)
+ avgDurationPrevTrend, _ := repositories.TransactionRepository.AvgDurationByInterval(c, projectId, prevStart, prevEnd, intervalMinutes)
avgDurationPrev := getAverageValue(avgDurationPrevTrend)
metrics = append(metrics, buildMetric("avg_response_time", "Avg Response Time", avgDurationCurrent, "ms", avgDurationTrend, avgDurationPrev, "response_time"))
// 4. Error Rate
- errorRateTrend, err := repositories.TransactionRepository.ErrorRateByHour(c, projectId, start, now)
+ errorRateTrend, err := repositories.TransactionRepository.ErrorRateByInterval(c, projectId, start, end, intervalMinutes)
if err != nil {
panic(err)
}
errorRateCurrent := getLastValue(errorRateTrend)
- errorRatePrevTrend, _ := repositories.TransactionRepository.ErrorRateByHour(c, projectId, prevStart, prevEnd)
+ errorRatePrevTrend, _ := repositories.TransactionRepository.ErrorRateByInterval(c, projectId, prevStart, prevEnd, intervalMinutes)
errorRatePrev := getAverageValue(errorRatePrevTrend)
metrics = append(metrics, buildMetric("error_rate", "Error Rate", errorRateCurrent, "%", errorRateTrend, errorRatePrev, "error_rate"))
// 5. CPU Usage
- cpuTrend, err := repositories.MetricRecordRepository.GetAverageByHour(c, projectId, models.MetricNameCpuUsage, start, now)
+ cpuTrend, err := repositories.MetricRecordRepository.GetAverageByInterval(c, projectId, models.MetricNameCpuUsage, start, end, intervalMinutes)
if err != nil {
panic(err)
}
@@ -98,7 +126,7 @@ func (d dashboardController) GetDashboard(c *gin.Context) {
metrics = append(metrics, buildMetric("cpu_usage", "CPU Usage", cpuCurrent, "%", cpuTrend, cpuPrev, "cpu"))
// 6. Memory Usage (MB)
- memTrend, err := repositories.MetricRecordRepository.GetAverageByHour(c, projectId, models.MetricNameMemoryUsage, start, now)
+ memTrend, err := repositories.MetricRecordRepository.GetAverageByInterval(c, projectId, models.MetricNameMemoryUsage, start, end, intervalMinutes)
if err != nil {
panic(err)
}
@@ -107,7 +135,7 @@ func (d dashboardController) GetDashboard(c *gin.Context) {
metrics = append(metrics, buildMetric("memory_usage", "Memory Usage", memCurrent, "MB", memTrend, memPrev, "memory"))
// 7. Memory Usage Percentage
- memPcntTrend, err := repositories.MetricRecordRepository.GetAverageByHour(c, projectId, models.MetricNameMemoryUsagePcnt, start, now)
+ memPcntTrend, err := repositories.MetricRecordRepository.GetAverageByInterval(c, projectId, models.MetricNameMemoryUsagePcnt, start, end, intervalMinutes)
if err != nil {
panic(err)
}
@@ -116,7 +144,7 @@ func (d dashboardController) GetDashboard(c *gin.Context) {
metrics = append(metrics, buildMetric("memory_usage_pcnt", "Memory %", memPcntCurrent, "%", memPcntTrend, memPcntPrev, "memory_pcnt"))
// 8. Go Routines
- goRoutinesTrend, err := repositories.MetricRecordRepository.GetAverageByHour(c, projectId, models.MetricNameGoRoutines, start, now)
+ goRoutinesTrend, err := repositories.MetricRecordRepository.GetAverageByInterval(c, projectId, models.MetricNameGoRoutines, start, end, intervalMinutes)
if err != nil {
panic(err)
}
@@ -125,7 +153,7 @@ func (d dashboardController) GetDashboard(c *gin.Context) {
metrics = append(metrics, buildMetric("go_routines", "Go Routines", goRoutinesCurrent, "", goRoutinesTrend, goRoutinesPrev, "go_routines"))
// 9. Heap Objects
- heapObjectsTrend, err := repositories.MetricRecordRepository.GetAverageByHour(c, projectId, models.MetricNameHeapObjects, start, now)
+ heapObjectsTrend, err := repositories.MetricRecordRepository.GetAverageByInterval(c, projectId, models.MetricNameHeapObjects, start, end, intervalMinutes)
if err != nil {
panic(err)
}
@@ -134,7 +162,7 @@ func (d dashboardController) GetDashboard(c *gin.Context) {
metrics = append(metrics, buildMetric("heap_objects", "Heap Objects", heapObjectsCurrent, "", heapObjectsTrend, heapObjectsPrev, "heap_objects"))
// 10. Num GC
- numGCTrend, err := repositories.MetricRecordRepository.GetAverageByHour(c, projectId, models.MetricNameNumGC, start, now)
+ numGCTrend, err := repositories.MetricRecordRepository.GetAverageByInterval(c, projectId, models.MetricNameNumGC, start, end, intervalMinutes)
if err != nil {
panic(err)
}
@@ -143,7 +171,7 @@ func (d dashboardController) GetDashboard(c *gin.Context) {
metrics = append(metrics, buildMetric("num_gc", "GC Cycles", numGCCurrent, "", numGCTrend, numGCPrev, "num_gc"))
// 11. GC Pause Total (convert from nanoseconds to milliseconds)
- gcPauseTrend, err := repositories.MetricRecordRepository.GetAverageByHour(c, projectId, models.MetricNameGCPauseTotal, start, now)
+ gcPauseTrend, err := repositories.MetricRecordRepository.GetAverageByInterval(c, projectId, models.MetricNameGCPauseTotal, start, end, intervalMinutes)
if err != nil {
panic(err)
}
@@ -291,4 +319,21 @@ func getAverageValue(points []models.TimeSeriesPoint) float64 {
return sum / float64(len(points))
}
+// calculateIntervalMinutes determines the aggregation bucket size based on the time range duration
+func calculateIntervalMinutes(duration time.Duration) int {
+ hours := duration.Hours()
+ switch {
+ case hours < 2:
+ return 1 // 1-minute buckets
+ case hours < 12:
+ return 5 // 5-minute buckets
+ case hours < 48:
+ return 15 // 15-minute buckets
+ case hours < 168: // 7 days
+ return 60 // 1-hour buckets
+ default:
+ return 240 // 4-hour buckets
+ }
+}
+
var DashboardController = dashboardController{}
diff --git a/backend/app/repositories/exception_stack_trace.repository.go b/backend/app/repositories/exception_stack_trace.repository.go
index a07dc630..7fd77443 100644
--- a/backend/app/repositories/exception_stack_trace.repository.go
+++ b/backend/app/repositories/exception_stack_trace.repository.go
@@ -194,6 +194,34 @@ func (e *exceptionStackTraceRepository) CountByHour(ctx context.Context, project
return points, nil
}
+// CountByInterval returns exception counts grouped by configurable interval in minutes
+func (e *exceptionStackTraceRepository) CountByInterval(ctx context.Context, projectId string, start, end time.Time, intervalMinutes int) ([]models.TimeSeriesPoint, error) {
+ query := `SELECT
+ toStartOfInterval(recorded_at, INTERVAL ? MINUTE) as bucket,
+ toFloat64(count()) as count
+ FROM exception_stack_traces
+ WHERE project_id = ? AND recorded_at >= ? AND recorded_at <= ?
+ GROUP BY bucket
+ ORDER BY bucket ASC`
+
+ rows, err := (*chdb.Conn).Query(ctx, query, intervalMinutes, projectId, start, end)
+ if err != nil {
+ return nil, err
+ }
+ defer rows.Close()
+
+ var points []models.TimeSeriesPoint
+ for rows.Next() {
+ var p models.TimeSeriesPoint
+ if err := rows.Scan(&p.Timestamp, &p.Value); err != nil {
+ return nil, err
+ }
+ points = append(points, p)
+ }
+
+ return points, nil
+}
+
// GetHourlyTrendForHashes returns hourly counts for specific exception hashes
func (e *exceptionStackTraceRepository) GetHourlyTrendForHashes(ctx context.Context, projectId string, hashes []string, start, end time.Time) (map[string][]models.ExceptionTrendPoint, error) {
if len(hashes) == 0 {
diff --git a/backend/app/repositories/metric_record.repository.go b/backend/app/repositories/metric_record.repository.go
index 9a631b34..8a188bb4 100644
--- a/backend/app/repositories/metric_record.repository.go
+++ b/backend/app/repositories/metric_record.repository.go
@@ -56,4 +56,32 @@ func (e *metricRecordRepository) GetAverageByHour(ctx context.Context, projectId
return points, nil
}
+// GetAverageByInterval returns metric averages grouped by configurable interval in minutes
+func (e *metricRecordRepository) GetAverageByInterval(ctx context.Context, projectId string, name string, start, end time.Time, intervalMinutes int) ([]models.TimeSeriesPoint, error) {
+ query := `SELECT
+ toStartOfInterval(recorded_at, INTERVAL ? MINUTE) as bucket,
+ avg(value) as avg_value
+ FROM metric_records
+ WHERE project_id = ? AND name = ? AND recorded_at >= ? AND recorded_at <= ?
+ GROUP BY bucket
+ ORDER BY bucket ASC`
+
+ rows, err := (*chdb.Conn).Query(ctx, query, intervalMinutes, projectId, name, start, end)
+ if err != nil {
+ return nil, err
+ }
+ defer rows.Close()
+
+ var points []models.TimeSeriesPoint
+ for rows.Next() {
+ var p models.TimeSeriesPoint
+ if err := rows.Scan(&p.Timestamp, &p.Value); err != nil {
+ return nil, err
+ }
+ points = append(points, p)
+ }
+
+ return points, nil
+}
+
var MetricRecordRepository = metricRecordRepository{}
diff --git a/backend/app/repositories/project.repository.go b/backend/app/repositories/project.repository.go
index 96530ab4..703d53f5 100644
--- a/backend/app/repositories/project.repository.go
+++ b/backend/app/repositories/project.repository.go
@@ -4,9 +4,8 @@ import (
"backend/app/chdb"
"backend/app/models"
"context"
- "crypto/rand"
- "encoding/hex"
"errors"
+ "strings"
"github.com/google/uuid"
)
@@ -66,9 +65,8 @@ func (p *projectRepository) Create(ctx context.Context, name string, framework s
}
func generateSecureToken() string {
- bytes := make([]byte, 32)
- rand.Read(bytes)
- return hex.EncodeToString(bytes)
+ id := uuid.New()
+ return strings.ReplaceAll(id.String(), "-", "")
}
var ProjectRepository = projectRepository{}
diff --git a/backend/app/repositories/transaction.repository.go b/backend/app/repositories/transaction.repository.go
index b6811b14..9a20cea2 100644
--- a/backend/app/repositories/transaction.repository.go
+++ b/backend/app/repositories/transaction.repository.go
@@ -283,6 +283,90 @@ func (e *transactionRepository) ErrorRateByHour(ctx context.Context, projectId s
return points, nil
}
+// CountByInterval returns transaction counts grouped by configurable interval in minutes
+func (e *transactionRepository) CountByInterval(ctx context.Context, projectId string, start, end time.Time, intervalMinutes int) ([]models.TimeSeriesPoint, error) {
+ query := `SELECT
+ toStartOfInterval(recorded_at, INTERVAL ? MINUTE) as bucket,
+ toFloat64(count()) as count
+ FROM transactions
+ WHERE project_id = ? AND recorded_at >= ? AND recorded_at <= ?
+ GROUP BY bucket
+ ORDER BY bucket ASC`
+
+ rows, err := (*chdb.Conn).Query(ctx, query, intervalMinutes, projectId, start, end)
+ if err != nil {
+ return nil, err
+ }
+ defer rows.Close()
+
+ var points []models.TimeSeriesPoint
+ for rows.Next() {
+ var p models.TimeSeriesPoint
+ if err := rows.Scan(&p.Timestamp, &p.Value); err != nil {
+ return nil, err
+ }
+ points = append(points, p)
+ }
+
+ return points, nil
+}
+
+// AvgDurationByInterval returns average response time in ms grouped by configurable interval
+func (e *transactionRepository) AvgDurationByInterval(ctx context.Context, projectId string, start, end time.Time, intervalMinutes int) ([]models.TimeSeriesPoint, error) {
+ query := `SELECT
+ toStartOfInterval(recorded_at, INTERVAL ? MINUTE) as bucket,
+ avg(duration) / 1000000 as avg_duration_ms
+ FROM transactions
+ WHERE project_id = ? AND recorded_at >= ? AND recorded_at <= ?
+ GROUP BY bucket
+ ORDER BY bucket ASC`
+
+ rows, err := (*chdb.Conn).Query(ctx, query, intervalMinutes, projectId, start, end)
+ if err != nil {
+ return nil, err
+ }
+ defer rows.Close()
+
+ var points []models.TimeSeriesPoint
+ for rows.Next() {
+ var p models.TimeSeriesPoint
+ if err := rows.Scan(&p.Timestamp, &p.Value); err != nil {
+ return nil, err
+ }
+ points = append(points, p)
+ }
+
+ return points, nil
+}
+
+// ErrorRateByInterval returns error rate (percentage) grouped by configurable interval
+func (e *transactionRepository) ErrorRateByInterval(ctx context.Context, projectId string, start, end time.Time, intervalMinutes int) ([]models.TimeSeriesPoint, error) {
+ query := `SELECT
+ toStartOfInterval(recorded_at, INTERVAL ? MINUTE) as bucket,
+ countIf(status_code >= 400) * 100.0 / count() as error_rate
+ FROM transactions
+ WHERE project_id = ? AND recorded_at >= ? AND recorded_at <= ?
+ GROUP BY bucket
+ ORDER BY bucket ASC`
+
+ rows, err := (*chdb.Conn).Query(ctx, query, intervalMinutes, projectId, start, end)
+ if err != nil {
+ return nil, err
+ }
+ defer rows.Close()
+
+ var points []models.TimeSeriesPoint
+ for rows.Next() {
+ var p models.TimeSeriesPoint
+ if err := rows.Scan(&p.Timestamp, &p.Value); err != nil {
+ return nil, err
+ }
+ points = append(points, p)
+ }
+
+ return points, nil
+}
+
// FindWorstEndpoints returns endpoints ordered by impact score (count * variance)
// Higher call volume + larger variance = higher impact
func (e *transactionRepository) FindWorstEndpoints(ctx context.Context, projectId string, start, end time.Time, limit int) ([]models.EndpointStats, error) {
diff --git a/frontend/package-lock.json b/frontend/package-lock.json
index 8b59d230..e5a1d8c1 100644
--- a/frontend/package-lock.json
+++ b/frontend/package-lock.json
@@ -8,7 +8,8 @@
"name": "frontend",
"version": "0.0.1",
"dependencies": {
- "lucide-svelte": "^0.562.0"
+ "lucide-svelte": "^0.562.0",
+ "svelte-highlight": "^7.9.0"
},
"devDependencies": {
"@eslint/compat": "^1.4.0",
@@ -3093,6 +3094,15 @@
"node": ">=8"
}
},
+ "node_modules/highlight.js": {
+ "version": "11.11.1",
+ "resolved": "https://registry.npmjs.org/highlight.js/-/highlight.js-11.11.1.tgz",
+ "integrity": "sha512-Xwwo44whKBVCYoliBQwaPvtd/2tYFkRQtXDWj1nackaV2JPXx3L0+Jvd8/qCJ2p+ML0/XVkJ2q+Mr+UVdpJK5w==",
+ "license": "BSD-3-Clause",
+ "engines": {
+ "node": ">=12.0.0"
+ }
+ },
"node_modules/iconv-lite": {
"version": "0.6.3",
"resolved": "https://registry.npmjs.org/iconv-lite/-/iconv-lite-0.6.3.tgz",
@@ -4445,6 +4455,15 @@
}
}
},
+ "node_modules/svelte-highlight": {
+ "version": "7.9.0",
+ "resolved": "https://registry.npmjs.org/svelte-highlight/-/svelte-highlight-7.9.0.tgz",
+ "integrity": "sha512-226LBTtvTnM2L2JkQq8mZeKEeMfPLYyta7VxZatFT4UPX5zdHEerKeMTvrfbxm7MVTWc7TPThsNoVdhWC177KQ==",
+ "license": "MIT",
+ "dependencies": {
+ "highlight.js": "11.11.1"
+ }
+ },
"node_modules/svelte-toolbelt": {
"version": "0.10.6",
"resolved": "https://registry.npmjs.org/svelte-toolbelt/-/svelte-toolbelt-0.10.6.tgz",
diff --git a/frontend/package.json b/frontend/package.json
index a01a6f91..63eeacea 100644
--- a/frontend/package.json
+++ b/frontend/package.json
@@ -52,6 +52,7 @@
"vite": "^7.2.6"
},
"dependencies": {
- "lucide-svelte": "^0.562.0"
+ "lucide-svelte": "^0.562.0",
+ "svelte-highlight": "^7.9.0"
}
}
diff --git a/frontend/src/lib/components/dashboard/metric-card.svelte b/frontend/src/lib/components/dashboard/metric-card.svelte
index 0ea3744c..7f78009f 100644
--- a/frontend/src/lib/components/dashboard/metric-card.svelte
+++ b/frontend/src/lib/components/dashboard/metric-card.svelte
@@ -2,15 +2,16 @@
import * as Card from '$lib/components/ui/card';
import * as Chart from "$lib/components/ui/chart/index.js";
import { TrendingUp, TrendingDown, Minus } from 'lucide-svelte';
- import { AreaChart, LineChart, Svg, Area } from 'layerchart';
- import { scaleUtc, scaleLinear } from 'd3-scale';
- import { curveLinear } from "d3-shape";
+ import { LineChart, Points } from 'layerchart';
+ import { scaleUtc } from 'd3-scale';
import type { DashboardMetric, MetricTrendPoint } from '$lib/types/dashboard';
import { min, max } from 'd3-array';
+ import MetricChartOverlay from './metric-chart-overlay.svelte';
- let { metric, timeDomain = null } = $props<{
+ let { metric, timeDomain = null, onRangeSelect } = $props<{
metric: DashboardMetric;
timeDomain?: [Date, Date] | null;
+ onRangeSelect?: (from: Date, to: Date) => void;
}>();
const statusColors: Record<string, string> = {
@@ -81,56 +82,77 @@
const yMax = $derived(max(metric.trend, (d: MetricTrendPoint) => d.value) ?? 0);
const padding = $derived((yMax - yMin) * 0.1 || 1);
- // Calculate xScale with shared time domain
- const xScaleWithDomain = $derived(() => {
- const scale = scaleUtc();
+ // Calculate X domain from timeDomain or data
+ const xDomainValue = $derived(() => {
if (timeDomain) {
- return scale.domain(timeDomain);
+ return timeDomain;
}
// Fallback to data range
if (metric.trend.length > 0) {
const minTime = min(metric.trend, (d: MetricTrendPoint) => d.timestamp);
const maxTime = max(metric.trend, (d: MetricTrendPoint) => d.timestamp);
if (minTime && maxTime) {
- return scale.domain([minTime, maxTime]);
+ return [minTime, maxTime] as [Date, Date];
}
}
- return scale;
+ return undefined;
});
- // Detect expected interval and filter out gaps for sparse data
- const expectedIntervalMs = $derived(() => {
+ // Calculate expected interval from actual data and use 2x as gap threshold
+ const gapThresholdMs = $derived(() => {
if (metric.trend.length < 2) return 3600000; // 1 hour default
const intervals: number[] = [];
for (let i = 1; i < Math.min(metric.trend.length, 10); i++) {
intervals.push(metric.trend[i].timestamp.getTime() - metric.trend[i - 1].timestamp.getTime());
}
- // Use median interval * 2 as threshold
intervals.sort((a, b) => a - b);
const median = intervals[Math.floor(intervals.length / 2)];
- return median * 2;
+ return median * 2; // Gap threshold = 2x median interval
});
- // Split data into continuous segments to avoid drawing lines across gaps
- function splitIntoSegments(data: MetricTrendPoint[], maxGapMs: number): MetricTrendPoint[][] {
- if (data.length === 0) return [];
- const segments: MetricTrendPoint[][] = [];
- let current: MetricTrendPoint[] = [data[0]];
-
- for (let i = 1; i < data.length; i++) {
- const gap = data[i].timestamp.getTime() - data[i - 1].timestamp.getTime();
- if (gap <= maxGapMs) {
- current.push(data[i]);
- } else {
- if (current.length > 0) segments.push(current);
- current = [data[i]];
+ // Create lookup set for gap points - marks points that have a gap before them
+ const gapPoints = $derived(() => {
+ const gaps = new Set<number>();
+ const threshold = gapThresholdMs();
+ for (let i = 1; i < metric.trend.length; i++) {
+ const gap = metric.trend[i].timestamp.getTime() - metric.trend[i - 1].timestamp.getTime();
+ if (gap > threshold) {
+ // Mark the point AFTER the gap as "undefined" to break the line
+ gaps.add(metric.trend[i].timestamp.getTime());
}
}
- if (current.length > 0) segments.push(current);
- return segments;
+ return gaps;
+ });
+
+ // Function to determine if a point should be connected to the previous point
+ // A point is "defined" (line should be drawn TO it) if there's no gap before it
+ function isDefined(d: MetricTrendPoint): boolean {
+ return !gapPoints().has(d.timestamp.getTime());
}
- const dataSegments = $derived(splitIntoSegments(metric.trend, expectedIntervalMs()));
+ // Calculate isolated points - points that have gaps BOTH before AND after them
+ // These are the only points that should show dots
+ const isolatedPoints = $derived(() => {
+ if (metric.trend.length === 0) return [];
+ if (metric.trend.length === 1) return metric.trend; // Single point is always isolated
+
+ const threshold = gapThresholdMs();
+ const isolated: MetricTrendPoint[] = [];
+
+ for (let i = 0; i < metric.trend.length; i++) {
+ const hasGapBefore = i === 0 ||
+ (metric.trend[i].timestamp.getTime() - metric.trend[i - 1].timestamp.getTime() > threshold);
+ const hasGapAfter = i === metric.trend.length - 1 ||
+ (metric.trend[i + 1].timestamp.getTime() - metric.trend[i].timestamp.getTime() > threshold);
+
+ if (hasGapBefore && hasGapAfter) {
+ isolated.push(metric.trend[i]);
+ }
+ }
+
+ return isolated;
+ });
+
const hasData = $derived(metric.trend.length > 0 && metric.trend.some((d: MetricTrendPoint) => d.value !== 0));
</script>
@@ -168,40 +190,63 @@
</Svg>
</Chart> -->
- <Chart.Container config={chartConfig}>
- {#if hasData}
- <LineChart
- data={metric.trend}
- x="timestamp"
- xScale={xScaleWithDomain()}
- series={[
- {
- key: "value",
- label: "Value",
- color: chartConfig.value.color,
- },
- ]}
- yDomain={[Math.max(0, yMin - padding), yMax + padding]}
- seriesLayout="stack"
- props={{
- xAxis: {
- format: () => ""
- },
- yAxis: {
- format: (a: number) => a > 999 ? (a/1000).toFixed(0) + "k" : `${a}`,
- },
- }}
- >
- {#snippet tooltip()}
- <Chart.Tooltip hideLabel />
- {/snippet}
- </LineChart>
- {:else}
- <div class="flex h-[100px] items-center justify-center text-sm text-muted-foreground">
- No data in this period
- </div>
- {/if}
- </Chart.Container>
+ <MetricChartOverlay
+ fromTime={xDomainValue()?.[0] ?? new Date()}
+ toTime={xDomainValue()?.[1] ?? new Date()}
+ {onRangeSelect}
+ data={metric.trend}
+ unit={metric.unit}
+ formatValue={(v) => metric.formatValue ? metric.formatValue(v) : formatMetricValue(v, metric.unit)}
+ >
+ <Chart.Container config={chartConfig}>
+ {#if hasData}
+ <LineChart
+ data={metric.trend}
+ x="timestamp"
+ xScale={scaleUtc()}
+ xDomain={xDomainValue()}
+ series={[
+ {
+ key: "value",
+ label: "Value",
+ color: chartConfig.value.color,
+ },
+ ]}
+ yDomain={[Math.max(0, yMin - padding), yMax + padding]}
+ seriesLayout="stack"
+ props={{
+ xAxis: {
+ format: () => ""
+ },
+ yAxis: {
+ format: (a: number) => a > 999 ? (a/1000).toFixed(0) + "k" : `${a}`,
+ },
+ spline: {
+ defined: isDefined
+ }
+ }}
+ tooltip={false}
+ >
+ {#snippet aboveMarks()}
+ <!-- Isolated points (dots only where no line) -->
+ {#if isolatedPoints().length > 0}
+ <Points
+ data={isolatedPoints()}
+ x="timestamp"
+ y="value"
+ r={2}
+ fill={chartConfig.value.color}
+ />
+ {/if}
+ {/snippet}
+ </LineChart>
+ {:else}
+ <div class="flex h-[100px] items-center justify-center text-sm text-muted-foreground">
+ No data in this period
+ </div>
+ {/if}
+ </Chart.Container>
+ </MetricChartOverlay>
<!-- 24h Change -->
<div class="flex items-center text-xs {trendChangeColor}">
diff --git a/frontend/src/lib/components/dashboard/metric-chart-overlay.svelte b/frontend/src/lib/components/dashboard/metric-chart-overlay.svelte
new file mode 100644
index 00000000..e7bcda1a
--- /dev/null
+++ b/frontend/src/lib/components/dashboard/metric-chart-overlay.svelte
@@ -0,0 +1,299 @@
+<script lang="ts">
+ import type { Snippet } from 'svelte';
+
+ type DataPoint = {
+ timestamp: Date;
+ value: number;
+ };
+
+ let {
+ fromTime,
+ toTime,
+ children,
+ onRangeSelect,
+ chartPadding = { left: 20, right: 4 },
+ data = [],
+ unit = '',
+ formatValue
+ } = $props<{
+ fromTime: Date;
+ toTime: Date;
+ children: Snippet;
+ onRangeSelect?: (from: Date, to: Date) => void;
+ chartPadding?: { left: number; right: number };
+ data?: DataPoint[];
+ unit?: string;
+ formatValue?: (value: number) => string;
+ }>();
+
+ let containerRef = $state<HTMLDivElement | null>(null);
+ let isHovering = $state(false);
+ let mouseX = $state(0);
+ let mouseY = $state(0);
+
+ // Drag selection state
+ let isDragging = $state(false);
+ let dragStartX = $state(0);
+ let dragEndX = $state(0);
+
+ // Calculate gap threshold from data (2x median interval)
+ const gapThresholdMs = $derived(() => {
+ if (data.length < 2) return 3600000; // 1 hour default
+ const intervals: number[] = [];
+ for (let i = 1; i < Math.min(data.length, 10); i++) {
+ intervals.push(data[i].timestamp.getTime() - data[i - 1].timestamp.getTime());
+ }
+ intervals.sort((a, b) => a - b);
+ const median = intervals[Math.floor(intervals.length / 2)];
+ return median * 2;
+ });
+
+ // Get container width
+ function getContainerWidth(): number {
+ return containerRef?.getBoundingClientRect().width ?? 0;
+ }
+
+ // Get the actual chart plotting area width (container minus padding on both sides)
+ function getChartAreaWidth(): number {
+ return getContainerWidth() - chartPadding.left - chartPadding.right;
+ }
+
+ // Check if mouse X is within the chart area
+ function isInChartArea(): boolean {
+ return mouseX >= chartPadding.left && mouseX <= getContainerWidth() - chartPadding.right;
+ }
+
+ // Calculate time based on X position (relative to chart area, not container)
+ function getTimeAtPosition(x: number): Date {
+ if (!containerRef) return fromTime;
+ const chartAreaWidth = getChartAreaWidth();
+ if (chartAreaWidth <= 0) return fromTime;
+ // Adjust x to be relative to chart area start
+ const chartX = x - chartPadding.left;
+ const percentage = Math.max(0, Math.min(1, chartX / chartAreaWidth));
+ const timeDiff = toTime.getTime() - fromTime.getTime();
+ return new Date(fromTime.getTime() + timeDiff * percentage);
+ }
+
+ // Find the value at a given time, interpolating for line sections
+ function getValueAtTime(time: Date): { value: number; isInterpolated: boolean } | null {
+ if (data.length === 0) return null;
+
+ const targetMs = time.getTime();
+ const threshold = gapThresholdMs();
+
+ // Find the bracketing points
+ let leftIdx = -1;
+ let rightIdx = -1;
+
+ for (let i = 0; i < data.length; i++) {
+ const pointMs = data[i].timestamp.getTime();
+ if (pointMs <= targetMs) {
+ leftIdx = i;
+ }
+ if (pointMs >= targetMs && rightIdx === -1) {
+ rightIdx = i;
+ }
+ }
+
+ // If exact match
+ if (leftIdx >= 0 && data[leftIdx].timestamp.getTime() === targetMs) {
+ return { value: data[leftIdx].value, isInterpolated: false };
+ }
+
+ // If we have both bracketing points
+ if (leftIdx >= 0 && rightIdx >= 0 && leftIdx !== rightIdx) {
+ const leftPoint = data[leftIdx];
+ const rightPoint = data[rightIdx];
+ const gap = rightPoint.timestamp.getTime() - leftPoint.timestamp.getTime();
+
+ // Check if this is a continuous line section (no gap)
+ if (gap <= threshold) {
+ // Interpolate linearly
+ const t = (targetMs - leftPoint.timestamp.getTime()) / gap;
+ const interpolatedValue = leftPoint.value + t * (rightPoint.value - leftPoint.value);
+ return { value: interpolatedValue, isInterpolated: true };
+ }
+ }
+
+ // Check if we're close to a single point (for isolated points or edges)
+ if (leftIdx >= 0) {
+ const leftPoint = data[leftIdx];
+ const distToLeft = targetMs - leftPoint.timestamp.getTime();
+ if (distToLeft <= threshold / 2) {
+ return { value: leftPoint.value, isInterpolated: false };
+ }
+ }
+
+ if (rightIdx >= 0) {
+ const rightPoint = data[rightIdx];
+ const distToRight = rightPoint.timestamp.getTime() - targetMs;
+ if (distToRight <= threshold / 2) {
+ return { value: rightPoint.value, isInterpolated: false };
+ }
+ }
+
+ return null; // In a gap, no value to show
+ }
+
+ // Calculate time based on mouse X position (for hover display)
+ const calculatedTime = $derived(() => {
+ if (!containerRef || !isHovering) return null;
+ return getTimeAtPosition(mouseX);
+ });
+
+ // Calculate the value at the current hover position
+ const calculatedValue = $derived(() => {
+ const time = calculatedTime();
+ if (!time) return null;
+ return getValueAtTime(time);
+ });
+
+ // Format value for display
+ function formatDisplayValue(value: number): string {
+ if (formatValue) {
+ return formatValue(value);
+ }
+ // Default formatting based on value magnitude
+ if (Number.isInteger(value)) return value.toString();
+ if (Math.abs(value) < 0.01) return value.toFixed(4);
+ if (Math.abs(value) < 1) return value.toFixed(2);
+ if (Math.abs(value) < 10) return value.toFixed(1);
+ return Math.round(value).toString();
+ }
+
+ // Selection region computed values (clamped to chart area)
+ const selectionLeft = $derived(Math.max(chartPadding.left, Math.min(dragStartX, dragEndX)));
+ const selectionRight = $derived(() => {
+ return Math.min(getContainerWidth() - chartPadding.right, Math.max(dragStartX, dragEndX));
+ });
+ const selectionWidth = $derived(selectionRight() - selectionLeft);
+ const selectionStartTime = $derived(() => getTimeAtPosition(selectionLeft));
+ const selectionEndTime = $derived(() => getTimeAtPosition(selectionLeft + selectionWidth));
+
+ function handleMouseMove(e: MouseEvent) {
+ if (!containerRef) return;
+ const rect = containerRef.getBoundingClientRect();
+ mouseX = e.clientX - rect.left;
+ mouseY = e.clientY - rect.top;
+
+ if (isDragging) {
+ dragEndX = mouseX;
+ }
+ }
+
+ function handleMouseEnter() {
+ isHovering = true;
+ }
+
+ function handleMouseLeave() {
+ isHovering = false;
+ // Cancel drag if mouse leaves
+ if (isDragging) {
+ isDragging = false;
+ }
+ }
+
+ function handleMouseDown(e: MouseEvent) {
+ if (!containerRef || e.button !== 0) return; // Only left click
+ const rect = containerRef.getBoundingClientRect();
+ const x = e.clientX - rect.left;
+
+ // Only start drag if within chart area
+ if (x < chartPadding.left || x > rect.width - chartPadding.right) return;
+
+ isDragging = true;
+ dragStartX = x;
+ dragEndX = x;
+
+ // Prevent text selection during drag
+ e.preventDefault();
+ }
+
+ function handleMouseUp(e: MouseEvent) {
+ if (!isDragging || !containerRef) return;
+
+ isDragging = false;
+
+ // Only trigger if selection is meaningful (at least 10px)
+ if (selectionWidth > 10 && onRangeSelect) {
+ const startTime = getTimeAtPosition(Math.min(dragStartX, dragEndX));
+ const endTime = getTimeAtPosition(Math.max(dragStartX, dragEndX));
+ onRangeSelect(startTime, endTime);
+ }
+ }
+
+ // Format time for display
+ function formatTime(date: Date | null): string {
+ if (!date) return '';
+ return date.toLocaleTimeString('en-US', { hour: '2-digit', minute: '2-digit' });
+ }
+</script>
+
+<div
+ bind:this={containerRef}
+ class="relative select-none"
+ onmouseenter={handleMouseEnter}
+ onmouseleave={handleMouseLeave}
+ onmousemove={handleMouseMove}
+ onmousedown={handleMouseDown}
+ onmouseup={handleMouseUp}
+ role="application"
+ aria-label="Chart with drag-to-zoom"
+ style="cursor: {isDragging ? 'col-resize' : (isInChartArea() ? 'crosshair' : 'default')};"
+>
+ {@render children()}
+
+ {#if isDragging && selectionWidth > 0}
+ <!-- Selection region overlay -->
+ <div
+ class="absolute top-0 bottom-0 bg-primary/20 border-x border-primary/40 pointer-events-none"
+ style="left: {selectionLeft}px; width: {selectionWidth}px;"
+ >
+ <!-- Selection time labels -->
+ <div class="absolute -top-5 left-0 -translate-x-full text-[9px] font-medium text-primary whitespace-nowrap">
+ {formatTime(selectionStartTime())}
+ </div>
+ <div class="absolute -top-5 right-0 translate-x-full text-[9px] font-medium text-primary whitespace-nowrap">
+ {formatTime(selectionEndTime())}
+ </div>
+ </div>
+ {/if}
+
+ {#if isHovering && !isDragging && isInChartArea()}
+ {@const clampedX = Math.max(chartPadding.left, Math.min(mouseX, getContainerWidth() - chartPadding.right))}
+ {@const valueData = calculatedValue()}
+
+ <!-- Vertical line at mouse X position (clamped to chart area) -->
+ <div
+ class="absolute top-0 bottom-0 w-px bg-muted-foreground/50 pointer-events-none"
+ style="left: {clampedX}px;"
+ ></div>
+
+ <!-- Value tooltip at top -->
+ {#if valueData}
+ <div
+ class="absolute top-0 -translate-x-1/2 -translate-y-full pointer-events-none"
+ style="left: {clampedX}px;"
+ >
+ <div
+ class="bg-foreground text-background rounded px-2 py-1 text-xs font-medium whitespace-nowrap shadow-lg mb-1"
+ >
+ {formatDisplayValue(valueData.value)}{#if unit}<span class="text-background/70 ml-0.5">{unit}</span>{/if}
+ </div>
+ </div>
+ {/if}
+
+ <!-- Time label at bottom, positioned at mouse X -->
+ <div
+ class="absolute bottom-0 -translate-x-1/2 translate-y-full pointer-events-none"
+ style="left: {clampedX}px;"
+ >
+ <div
+ class="bg-background border border-border rounded px-1.5 py-0.5 text-[10px] text-muted-foreground whitespace-nowrap shadow-sm mt-1"
+ >
+ {formatTime(calculatedTime())}
+ </div>
+ </div>
+ {/if}
+</div>
diff --git a/frontend/src/lib/components/ui/time-range-picker/time-range-picker.svelte b/frontend/src/lib/components/ui/time-range-picker/time-range-picker.svelte
index 6bc3cba6..2c16d18f 100644
--- a/frontend/src/lib/components/ui/time-range-picker/time-range-picker.svelte
+++ b/frontend/src/lib/components/ui/time-range-picker/time-range-picker.svelte
@@ -20,7 +20,8 @@
toDate?: CalendarDate;
fromTime?: string;
toTime?: string;
- onApply?: (from: { date: CalendarDate; time: string }, to: { date: CalendarDate; time: string }) => void;
+ preset?: string | null;
+ onApply?: (from: { date: CalendarDate; time: string }, to: { date: CalendarDate; time: string }, preset: string | null) => void;
}
let {
@@ -28,6 +29,7 @@
toDate = $bindable(today(getLocalTimeZone())),
fromTime = $bindable('00:00'),
toTime = $bindable('23:59'),
+ preset = $bindable<string | null>('6h'),
onApply
}: Props = $props();
@@ -62,8 +64,89 @@
];
let isOpen = $state(false);
- let showCustom = $state(false);
- let selectedPreset = $state<string | null>('7d');
+ let showCustom = $state(preset === null);
+ let selectedPreset = $state<string | null>(preset);
+
+ // Flag to ignore external change detection when we're applying our own changes
+ let isApplyingInternally = $state(false);
+
+ // Sync internal selectedPreset with external preset prop
+ $effect(() => {
+ if (preset !== selectedPreset) {
+ selectedPreset = preset;
+ showCustom = preset === null;
+
+ // If preset is set, calculate the time range
+ if (preset) {
+ const presetDef = presetGroups.flatMap(g => g.presets).find(p => p.value === preset);
+ if (presetDef) {
+ const now = new Date();
+ const fromDateTime = new Date(now.getTime() - presetDef.minutes * 60 * 1000);
+
+ tempFromDateTime = new CalendarDateTime(
+ fromDateTime.getFullYear(),
+ fromDateTime.getMonth() + 1,
+ fromDateTime.getDate(),
+ fromDateTime.getHours(),
+ fromDateTime.getMinutes(),
+ fromDateTime.getSeconds()
+ );
+ tempToDateTime = new CalendarDateTime(
+ now.getFullYear(),
+ now.getMonth() + 1,
+ now.getDate(),
+ now.getHours(),
+ now.getMinutes(),
+ now.getSeconds()
+ );
+ }
+ }
+ }
+ });
+
+ // Track last known bound values to detect external changes
+ let lastFromDate = $state(fromDate);
+ let lastToDate = $state(toDate);
+ let lastFromTime = $state(fromTime);
+ let lastToTime = $state(toTime);
+
+ // Detect external value changes and switch to custom mode
+ $effect(() => {
+ const fromDateChanged = fromDate.year !== lastFromDate.year ||
+ fromDate.month !== lastFromDate.month ||
+ fromDate.day !== lastFromDate.day;
+ const toDateChanged = toDate.year !== lastToDate.year ||
+ toDate.month !== lastToDate.month ||
+ toDate.day !== lastToDate.day;
+ const fromTimeChanged = fromTime !== lastFromTime;
+ const toTimeChanged = toTime !== lastToTime;
+
+ if (fromDateChanged || toDateChanged || fromTimeChanged || toTimeChanged) {
+ // Update last known values
+ lastFromDate = fromDate;
+ lastToDate = toDate;
+ lastFromTime = fromTime;
+ lastToTime = toTime;
+
+ // If picker is not open AND we're not applying internally, this was an external change
+ if (!isOpen && !isApplyingInternally) {
+ showCustom = true;
+ selectedPreset = null;
+
+ // Sync temp values with the new bound values
+ const [fromHour, fromMinute] = fromTime.split(':').map(Number);
+ const [toHour, toMinute] = toTime.split(':').map(Number);
+ tempFromDateTime = new CalendarDateTime(
+ fromDate.year, fromDate.month, fromDate.day,
+ fromHour || 0, fromMinute || 0, 0
+ );
+ tempToDateTime = new CalendarDateTime(
+ toDate.year, toDate.month, toDate.day,
+ toHour || 23, toMinute || 59, 0
+ );
+ }
+ }
+ });
// DateTime picker popover states
let fromPickerOpen = $state(false);
@@ -130,13 +213,14 @@
return `${hours12}:${String(minutes).padStart(2, '0')} ${period}`;
}
- function selectPreset(preset: TimeRangePreset) {
- selectedPreset = preset.value;
+ function selectPreset(presetDef: TimeRangePreset) {
+ selectedPreset = presetDef.value;
+ preset = presetDef.value; // Sync with external prop
showCustom = false;
// Calculate the date range for this preset
const now = new Date();
- const fromDateTime = new Date(now.getTime() - preset.minutes * 60 * 1000);
+ const fromDateTime = new Date(now.getTime() - presetDef.minutes * 60 * 1000);
// Update temp values only - don't close or apply yet
tempFromDateTime = new CalendarDateTime(
@@ -161,6 +245,7 @@
showCustom = !showCustom;
if (showCustom) {
selectedPreset = null;
+ preset = null; // Sync with external prop
}
}
@@ -190,11 +275,21 @@
!dateTimesEqual(tempToDateTime, initialToDateTime);
if (hasChanged) {
+ // Set flag to prevent external change detection from triggering
+ isApplyingInternally = true;
+
fromDate = new CalendarDate(tempFromDateTime.year, tempFromDateTime.month, tempFromDateTime.day);
toDate = new CalendarDate(tempToDateTime.year, tempToDateTime.month, tempToDateTime.day);
fromTime = `${String(tempFromDateTime.hour).padStart(2, '0')}:${String(tempFromDateTime.minute).padStart(2, '0')}`;
toTime = `${String(tempToDateTime.hour).padStart(2, '0')}:${String(tempToDateTime.minute).padStart(2, '0')}`;
- onApply?.({ date: fromDate, time: fromTime }, { date: toDate, time: toTime });
+
+ // Pass current preset (null if custom mode)
+ const currentPreset = showCustom ? null : selectedPreset;
+ preset = currentPreset; // Sync external prop
+ onApply?.({ date: fromDate, time: fromTime }, { date: toDate, time: toTime }, currentPreset);
+
+ // Reset flag after a tick to allow effects to settle
+ setTimeout(() => { isApplyingInternally = false; }, 0);
}
// Keep showCustom state (don't reset it) so it remembers custom mode
diff --git a/frontend/src/routes/connection/+page.svelte b/frontend/src/routes/connection/+page.svelte
index b7ca4275..fceac7e6 100644
--- a/frontend/src/routes/connection/+page.svelte
+++ b/frontend/src/routes/connection/+page.svelte
@@ -7,6 +7,11 @@
import { projectsState, type ProjectWithToken, type Framework } from '$lib/state/projects.svelte';
import { Skeleton } from '$lib/components/ui/skeleton';
import FrameworkIcon from '$lib/components/framework-icon.svelte';
+ import Highlight from 'svelte-highlight';
+ import go from 'svelte-highlight/languages/go';
+ import bash from 'svelte-highlight/languages/bash';
+ import { themeState } from '$lib/state/theme.svelte';
+ import 'svelte-highlight/styles/github-dark.css';
let projectWithToken = $state<ProjectWithToken | null>(null);
let loading = $state(true);
@@ -54,35 +59,11 @@
switch (framework) {
case 'gin':
- return `package main
-
-import (
- "github.com/gin-gonic/gin"
- "github.com/traceway-io/go-client"
- "github.com/traceway-io/go-client/traceway_gin"
-)
+ return `import "github.com/traceway-io/go-client/traceway_gin"
func main() {
r := gin.Default()
-
- // Add Traceway middleware with optional version and server name
- r.Use(traceway_gin.New(
- "${connectionString}",
- traceway.WithVersion("1.0.0"), // Optional: your app version
- traceway.WithServerName("api-server"), // Optional: defaults to hostname
- ))
-
- // Your routes
- r.GET("/", func(c *gin.Context) {
- c.JSON(200, gin.H{"message": "Hello World"})
- })
-
- // Capture custom messages
- r.GET("/action", func(c *gin.Context) {
- traceway.CaptureMessage("User performed action")
- c.JSON(200, gin.H{"status": "ok"})
- })
-
+ r.Use(traceway_gin.New("${connectionString}"))
r.Run(":8080")
}`;
@@ -279,7 +260,9 @@ func main() {
{/if}
</Button>
</div>
- <pre class="bg-muted p-4 rounded-lg overflow-x-auto text-sm font-mono leading-relaxed"><code class="language-go">{sdkCode}</code></pre>
+ <div class="rounded-lg overflow-hidden text-sm {themeState.isDark ? 'dark-code' : 'light-code'}">
+ <Highlight language={go} code={sdkCode} />
+ </div>
</div>
</CardContent>
</Card>
@@ -308,7 +291,9 @@ func main() {
{/if}
</Button>
</div>
- <pre class="bg-muted p-4 rounded-lg overflow-x-auto text-sm font-mono">{installCommand}</pre>
+ <div class="rounded-lg overflow-hidden text-sm {themeState.isDark ? 'dark-code' : 'light-code'}">
+ <Highlight language={bash} code={installCommand} />
+ </div>
</div>
</CardContent>
</Card>
@@ -322,3 +307,53 @@ func main() {
</Card>
{/if}
</div>
+
+<style>
+ /* Light theme - override dark theme defaults */
+ :global(.light-code .hljs) {
+ background: #f6f8fa;
+ color: #24292e;
+ }
+ :global(.light-code .hljs-keyword),
+ :global(.light-code .hljs-selector-tag) {
+ color: #d73a49;
+ }
+ :global(.light-code .hljs-string),
+ :global(.light-code .hljs-attr) {
+ color: #032f62;
+ }
+ :global(.light-code .hljs-function),
+ :global(.light-code .hljs-title) {
+ color: #6f42c1;
+ }
+ :global(.light-code .hljs-comment) {
+ color: #6a737d;
+ }
+ :global(.light-code .hljs-built_in) {
+ color: #005cc5;
+ }
+
+ /* Dark theme - ensure dark styles apply */
+ :global(.dark-code .hljs) {
+ background: #0d1117;
+ color: #c9d1d9;
+ }
+ :global(.dark-code .hljs-keyword),
+ :global(.dark-code .hljs-selector-tag) {
+ color: #ff7b72;
+ }
+ :global(.dark-code .hljs-string),
+ :global(.dark-code .hljs-attr) {
+ color: #a5d6ff;
+ }
+ :global(.dark-code .hljs-function),
+ :global(.dark-code .hljs-title) {
+ color: #d2a8ff;
+ }
+ :global(.dark-code .hljs-comment) {
+ color: #8b949e;
+ }
+ :global(.dark-code .hljs-built_in) {
+ color: #79c0ff;
+ }
+</style>
diff --git a/frontend/src/routes/metrics/+page.svelte b/frontend/src/routes/metrics/+page.svelte
index fbf2fa5e..07c26c2a 100644
--- a/frontend/src/routes/metrics/+page.svelte
+++ b/frontend/src/routes/metrics/+page.svelte
@@ -1,5 +1,6 @@
<script lang="ts">
import { onMount } from 'svelte';
+ import { browser } from '$app/environment';
import { Button } from '$lib/components/ui/button';
import { Skeleton } from '$lib/components/ui/skeleton';
import { RefreshCw } from 'lucide-svelte';
@@ -10,20 +11,130 @@
import { ErrorDisplay } from '$lib/components/ui/error-display';
import { projectsState } from '$lib/state/projects.svelte';
import { TimeRangePicker } from '$lib/components/ui/time-range-picker';
- import { CalendarDate, getLocalTimeZone, today } from '@internationalized/date';
+ import { CalendarDate } from '@internationalized/date';
let dashboardData = $state<DashboardData | null>(null);
let loading = $state(true);
let error = $state('');
let errorStatus = $state<number>(0);
- // Date Range State - default to last 24 hours
- let fromDate = $state<CalendarDate>(today(getLocalTimeZone()).subtract({ days: 1 }));
- let toDate = $state<CalendarDate>(today(getLocalTimeZone()));
- let fromTime = $state('00:00');
- let toTime = $state('23:59');
+ // Preset definitions (must match TimeRangePicker)
+ const presetMinutes: Record<string, number> = {
+ '30m': 30,
+ '60m': 60,
+ '3h': 180,
+ '6h': 360,
+ '12h': 720,
+ '24h': 1440,
+ '3d': 4320,
+ '7d': 10080,
+ '1M': 43200,
+ '3M': 129600,
+ };
+
+ // Calculate time range from preset
+ function getTimeRangeFromPreset(presetValue: string): { from: Date; to: Date } {
+ const minutes = presetMinutes[presetValue] || 360; // Default to 6h
+ const now = new Date();
+ const from = new Date(now.getTime() - minutes * 60 * 1000);
+ return { from, to: now };
+ }
+
+ // Parse URL params
+ function parseUrlParams(): { preset: string | null; from: Date | null; to: Date | null } {
+ if (!browser) return { preset: '6h', from: null, to: null };
+ const params = new URLSearchParams(window.location.search);
+ const presetParam = params.get('preset');
+ const fromParam = params.get('from');
+ const toParam = params.get('to');
+
+ // If preset is specified, use it
+ if (presetParam && presetMinutes[presetParam]) {
+ return { preset: presetParam, from: null, to: null };
+ }
+
+ // If custom from/to specified
+ if (fromParam && toParam) {
+ const from = new Date(fromParam);
+ const to = new Date(toParam);
+ if (!isNaN(from.getTime()) && !isNaN(to.getTime())) {
+ return { preset: null, from, to };
+ }
+ }
+
+ // Default to 6h preset
+ return { preset: '6h', from: null, to: null };
+ }
+
+ function dateToCalendarDate(date: Date): CalendarDate {
+ return new CalendarDate(date.getFullYear(), date.getMonth() + 1, date.getDate());
+ }
+
+ function dateToTimeString(date: Date): string {
+ return `${String(date.getHours()).padStart(2, '0')}:${String(date.getMinutes()).padStart(2, '0')}`;
+ }
+
+ // Initialize from URL or defaults
+ const initialUrlParams = parseUrlParams();
+ const initialRange = initialUrlParams.preset
+ ? getTimeRangeFromPreset(initialUrlParams.preset)
+ : { from: initialUrlParams.from!, to: initialUrlParams.to! };
+
+ let selectedPreset = $state<string | null>(initialUrlParams.preset);
+ let fromDate = $state<CalendarDate>(dateToCalendarDate(initialRange.from));
+ let toDate = $state<CalendarDate>(dateToCalendarDate(initialRange.to));
+ let fromTime = $state(dateToTimeString(initialRange.from));
+ let toTime = $state(dateToTimeString(initialRange.to));
let sharedTimeDomain = $state<[Date, Date] | null>(null);
+ // Update URL with current time range
+ function updateUrl(pushState = true) {
+ if (!browser) return;
+
+ const params = new URLSearchParams();
+
+ if (selectedPreset) {
+ // Store preset in URL
+ params.set('preset', selectedPreset);
+ } else {
+ // Store custom from/to in URL
+ const fromDateTime = new Date(getFromDateTime());
+ const toDateTime = new Date(getToDateTime());
+ params.set('from', fromDateTime.toISOString());
+ params.set('to', toDateTime.toISOString());
+ }
+
+ const newUrl = `${window.location.pathname}?${params.toString()}`;
+
+ if (pushState) {
+ window.history.pushState({}, '', newUrl);
+ } else {
+ window.history.replaceState({}, '', newUrl);
+ }
+ }
+
+ // Handle browser back/forward navigation
+ function handlePopState() {
+ const urlParams = parseUrlParams();
+
+ if (urlParams.preset) {
+ selectedPreset = urlParams.preset;
+ const range = getTimeRangeFromPreset(urlParams.preset);
+ fromDate = dateToCalendarDate(range.from);
+ fromTime = dateToTimeString(range.from);
+ toDate = dateToCalendarDate(range.to);
+ toTime = dateToTimeString(range.to);
+ } else if (urlParams.from && urlParams.to) {
+ selectedPreset = null;
+ fromDate = dateToCalendarDate(urlParams.from);
+ fromTime = dateToTimeString(urlParams.from);
+ toDate = dateToCalendarDate(urlParams.to);
+ toTime = dateToTimeString(urlParams.to);
+ }
+
+ loadDashboard(false); // Don't push to history on popstate
+ }
+
// Combine date and time into ISO datetime string
function getFromDateTime(): string {
const dateStr = `${fromDate.year}-${String(fromDate.month).padStart(2, '0')}-${String(fromDate.day).padStart(2, '0')}`;
@@ -35,19 +146,33 @@
return `${dateStr}T${toTime || '23:59'}`;
}
- function handleTimeRangeChange(from: { date: CalendarDate; time: string }, to: { date: CalendarDate; time: string }) {
+ function handleTimeRangeChange(from: { date: CalendarDate; time: string }, to: { date: CalendarDate; time: string }, preset: string | null) {
fromDate = from.date;
fromTime = from.time;
toDate = to.date;
toTime = to.time;
+ selectedPreset = preset;
+ loadDashboard();
+ }
+
+ // Handle drag-to-zoom selection from chart overlay
+ function handleChartRangeSelect(from: Date, to: Date) {
+ selectedPreset = null; // Chart selection is always custom
+ fromDate = new CalendarDate(from.getFullYear(), from.getMonth() + 1, from.getDate());
+ fromTime = `${String(from.getHours()).padStart(2, '0')}:${String(from.getMinutes()).padStart(2, '0')}`;
+ toDate = new CalendarDate(to.getFullYear(), to.getMonth() + 1, to.getDate());
+ toTime = `${String(to.getHours()).padStart(2, '0')}:${String(to.getMinutes()).padStart(2, '0')}`;
loadDashboard();
}
- async function loadDashboard() {
+ async function loadDashboard(pushToHistory = true) {
loading = true;
error = '';
errorStatus = 0;
+ // Update URL with current time range
+ updateUrl(pushToHistory);
+
try {
const fromDateTime = new Date(getFromDateTime());
const toDateTime = new Date(getToDateTime());
@@ -90,7 +215,15 @@
}
onMount(() => {
- loadDashboard();
+ // On initial load, use replaceState to set URL without creating history entry
+ loadDashboard(false);
+
+ // Listen for browser back/forward navigation
+ window.addEventListener('popstate', handlePopState);
+
+ return () => {
+ window.removeEventListener('popstate', handlePopState);
+ };
});
const lastUpdatedFormatted = $derived(
@@ -120,9 +253,10 @@
bind:toDate
bind:fromTime
bind:toTime
+ bind:preset={selectedPreset}
onApply={handleTimeRangeChange}
/>
- <Button variant="outline" size="sm" onclick={loadDashboard} disabled={loading}>
+ <Button variant="outline" size="sm" onclick={() => loadDashboard()} disabled={loading}>
<RefreshCw class="h-4 w-4 {loading ? 'animate-spin' : ''}" />
</Button>
</div>
@@ -156,7 +290,7 @@
{/each}
{:else if dashboardData}
{#each dashboardData.metrics as metric (metric.id)}
- <MetricCard {metric} timeDomain={sharedTimeDomain} />
+ <MetricCard {metric} timeDomain={sharedTimeDomain} onRangeSelect={handleChartRangeSelect} />
{/each}
{/if}
</div>