Skip to content

Modern Docker Management, Designed for Everyone

5.6 KB
Raw Blame
<script lang="ts">
	import { Temporal } from 'temporal-polyfill';

	import { m } from '#lib/paraglide/messages.js';
	import type { VulnerabilityRiskTrendPoint } from '#lib/types/environment.js';
	import { formatDate, plainDateToInstantString } from '#lib/utils/formatting.js';

	interface Props {
		points: VulnerabilityRiskTrendPoint[];
		/** Number of days shown, ending at the latest point. */
		days: number;
		height?: number;
	}

	let { points, days, height = 120 }: Props = $props();

	const BAND_LINES = [40, 70, 90];
	const PAD_TOP = 8;
	const PAD_BOTTOM = 4;
	const PAD_RIGHT = 24;

	let width = $state(0);
	let hoverIndex = $state<number | null>(null);

	const plotted = $derived.by(() => {
		const last = points.at(-1);
		if (!last) return [];
		const end = Temporal.PlainDate.from(last.date);
		const start = end.subtract({ days: days - 1 });
		return points
			.map((point) => {
				const date = Temporal.PlainDate.from(point.date);
				return { date, day: start.until(date).days, score: point.riskScore };
			})
			.filter((point) => point.day >= 0);
	});

	const plotWidth = $derived(Math.max(width - PAD_RIGHT, 0));
	const xFor = (day: number) => (days <= 1 ? plotWidth : (day / (days - 1)) * plotWidth);
	const yFor = (score: number) => PAD_TOP + (1 - score / 100) * (height - PAD_TOP - PAD_BOTTOM);

	// Consecutive days form a segment; a missing day breaks the line.
	const segments = $derived.by(() => {
		const result: (typeof plotted)[] = [];
		for (const point of plotted) {
			const segment = result.at(-1);
			const previous = segment?.at(-1);
			if (segment && previous && point.day - previous.day === 1) segment.push(point);
			else result.push([point]);
		}
		return result;
	});

	const linePaths = $derived(
		segments.map((segment) => segment.map((p, i) => `${i ? 'L' : 'M'}${xFor(p.day)},${yFor(p.score)}`).join(''))
	);
	const areaPaths = $derived(
		segments.flatMap((segment) => {
			const first = segment.at(0);
			const last = segment.at(-1);
			if (!first || !last || segment.length < 2) return [];
			const line = segment.map((p) => `L${xFor(p.day)},${yFor(p.score)}`).join('');
			return [`M${xFor(first.day)},${yFor(0)}${line}L${xFor(last.day)},${yFor(0)}Z`];
		})
	);

	// Single-day segments have no line, so they get a dot.
	const isolatedPoints = $derived(segments.flatMap((segment) => (segment.length === 1 ? segment : [])));
	const latest = $derived(plotted.at(-1));
	const hovered = $derived(hoverIndex === null ? undefined : plotted.at(hoverIndex));
	const summaryLabel = $derived.by(() => {
		const first = plotted.at(0);
		if (!first || !latest || plotted.length < 2) return m.security_risk_trend_empty();
		return m.security_risk_trend_summary({ from: first.score, to: latest.score, days });
	});

	function formatDay(date: Temporal.PlainDate) {
		return formatDate(plainDateToInstantString(date), { dateStyle: 'month-day' });
	}

	function handlePointerMove(event: PointerEvent) {
		if (plotted.length === 0 || plotWidth === 0) return;
		const rect = (event.currentTarget as SVGRectElement).getBoundingClientRect();
		const day = ((event.clientX - rect.left) / plotWidth) * (days - 1);
		let nearest = 0;
		let nearestDistance = Infinity;
		plotted.forEach((point, i) => {
			const distance = Math.abs(point.day - day);
			if (distance < nearestDistance) {
				nearest = i;
				nearestDistance = distance;
			}
		});
		hoverIndex = nearest;
	}
</script>

<div class="relative h-(--chart-height) w-full" bind:clientWidth={width} style="--chart-height: {height}px;">
	{#if width > 0}
		<svg {width} {height} role="img" aria-label={summaryLabel} class="overflow-visible">
			{#each BAND_LINES as band (band)}
				<line
					x1="0"
					x2={plotWidth}
					y1={yFor(band)}
					y2={yFor(band)}
					stroke="currentColor"
					stroke-width="1"
					class="text-border/60"
				/>
				<text x={plotWidth + 6} y={yFor(band)} dy="0.32em" class="fill-muted-foreground text-3xs tabular-nums">{band}</text>
			{/each}
			<line x1="0" x2={plotWidth} y1={yFor(0)} y2={yFor(0)} stroke="currentColor" stroke-width="1" class="text-border" />

			{#each areaPaths as path, i (i)}
				<path d={path} fill="currentColor" class="text-primary/10" />
			{/each}
			{#each linePaths as path, i (i)}
				<path
					d={path}
					fill="none"
					stroke="currentColor"
					stroke-width="2"
					stroke-linecap="round"
					stroke-linejoin="round"
					class="text-primary"
				/>
			{/each}
			{#each isolatedPoints as point (point.day)}
				<circle cx={xFor(point.day)} cy={yFor(point.score)} r="2.5" class="fill-primary" />
			{/each}

			{#if hovered}
				<line
					x1={xFor(hovered.day)}
					x2={xFor(hovered.day)}
					y1={PAD_TOP}
					y2={yFor(0)}
					stroke="currentColor"
					stroke-width="1"
					class="text-muted-foreground/50"
				/>
				<circle cx={xFor(hovered.day)} cy={yFor(hovered.score)} r="4" class="fill-primary stroke-background" stroke-width="2" />
			{:else if latest}
				<circle cx={xFor(latest.day)} cy={yFor(latest.score)} r="4" class="fill-primary stroke-background" stroke-width="2" />
			{/if}

			<rect
				x="0"
				y="0"
				width={plotWidth}
				{height}
				fill="transparent"
				role="presentation"
				onpointermove={handlePointerMove}
				onpointerleave={() => (hoverIndex = null)}
			/>
		</svg>

		{#if hovered}
			<div
				class="pointer-events-none absolute -top-2 left-(--tooltip-x) -translate-x-1/2 -translate-y-full rounded-md border border-border/60 bg-popover px-2 py-1 text-xs whitespace-nowrap shadow-sm"
				style="--tooltip-x: {xFor(hovered.day)}px;"
			>
				<span class="text-muted-foreground">{formatDay(hovered.date)}</span>
				<span class="ml-1.5 font-semibold tabular-nums">{hovered.score}</span>
			</div>
		{/if}
	{/if}
</div>