Skip to content

armgit / Pulse

Public Imported from GitHub
0

Real-time monitoring dashboard for Proxmox VE, PBS, Docker, Kubernetes, TrueNAS and vSphere. Self-hosted, with alerts for failed backups, full disks, unhealthy containers and offline nodes.

Split density map runtime owners

rcourtman99afe449e9c3
diff --git a/docs/release-control/v6/internal/subsystems/frontend-primitives.md b/docs/release-control/v6/internal/subsystems/frontend-primitives.md
index faf071981c..e23dbae271 100644
--- a/docs/release-control/v6/internal/subsystems/frontend-primitives.md
+++ b/docs/release-control/v6/internal/subsystems/frontend-primitives.md
@@ -187,6 +187,14 @@ and `frontend-modern/src/components/shared/interactiveSparklineModel.ts` owns
sparkline downsampling, gap segmentation, axis-tick math, and hover-selection
policy. Future sparkline work should extend those owners instead of pushing
canvas scheduling or chart-shape math back into the shared component shell.
+The shared density map now follows that same owner split.
+`frontend-modern/src/components/shared/DensityMap.tsx` stays the render shell,
+`frontend-modern/src/components/shared/useDensityMapState.ts` owns hover
+signals, canvas draw lifecycle, and resize handling, and
+`frontend-modern/src/components/shared/densityMapModel.ts` owns bucket/window
+math, hover target selection, tooltip time formatting, and density-cell
+opacity rules. Future density-map work should extend those owners instead of
+pushing canvas lifecycle or chart math back into the shared shell.
The shared history chart now follows the same owner shape.
`frontend-modern/src/components/shared/HistoryChart.tsx` stays the render
shell, `frontend-modern/src/components/shared/useHistoryChartState.ts` owns
diff --git a/docs/release-control/v6/internal/subsystems/registry.json b/docs/release-control/v6/internal/subsystems/registry.json
index ebb9dfba9e..b0933250f9 100644
--- a/docs/release-control/v6/internal/subsystems/registry.json
+++ b/docs/release-control/v6/internal/subsystems/registry.json
@@ -2193,6 +2193,7 @@
"exact_files": [
"frontend-modern/src/components/shared/__tests__/CommandPaletteModal.test.tsx",
"frontend-modern/src/components/shared/__tests__/ContainerUpdateBadge.test.tsx",
+ "frontend-modern/src/components/shared/__tests__/DensityMap.test.tsx",
"frontend-modern/src/components/shared/__tests__/Dialog.test.tsx",
"frontend-modern/src/components/shared/__tests__/HelpIcon.test.tsx",
"frontend-modern/src/components/shared/__tests__/HistoryChart.test.tsx",
diff --git a/frontend-modern/src/components/shared/DensityMap.tsx b/frontend-modern/src/components/shared/DensityMap.tsx
index e7034665cb..ef8d044cbf 100644
--- a/frontend-modern/src/components/shared/DensityMap.tsx
+++ b/frontend-modern/src/components/shared/DensityMap.tsx
@@ -1,244 +1,18 @@
-import { Component, createMemo, createEffect, createSignal, onCleanup, Show } from 'solid-js';
+import { Component, Show } from 'solid-js';
import { Portal } from 'solid-js/web';
-import type { TimeRange } from '@/api/charts';
-import { timeRangeToMs } from '@/utils/timeRange';
-import type { InteractiveSparklineSeries } from './InteractiveSparkline';
+import {
+ formatDensityMapHoverTime,
+ type DensityMapProps,
+} from './densityMapModel';
+import { useDensityMapState } from './useDensityMapState';
-interface DensityMapProps {
- series: InteractiveSparklineSeries[];
- rangeLabel?: string;
- timeRange?: TimeRange;
- formatValue?: (value: number) => string;
-}
-
-const formatHoverTime = (timestamp: number): string =>
- new Date(timestamp).toLocaleString([], {
- month: 'short',
- day: '2-digit',
- hour: '2-digit',
- minute: '2-digit',
- hour12: false,
- });
-
-const clamp = (value: number, min: number, max: number): number =>
- Math.max(min, Math.min(value, max));
+export type { DensityMapProps } from './densityMapModel';
export const DensityMap: Component<DensityMapProps> = (props) => {
- let canvasRef: HTMLCanvasElement | undefined;
- let chartSurfaceRef: HTMLDivElement | undefined;
- const COLUMNS = 45; // Fixed number of time buckets
- const PADDING_Y = 2; // Padding between rows
- const PADDING_X = 2; // Padding between columns
-
- const [hoveredState, setHoveredState] = createSignal<{
- tooltipX: number;
- tooltipY: number;
- timestamp: number;
- value: number;
- seriesName: string;
- seriesColor: string;
- } | null>(null);
-
- const formatValue = (v: number) => (props.formatValue ? props.formatValue(v) : `${v.toFixed(1)}`);
-
- // Pre-process data
- const chartData = createMemo(() => {
- const range = props.timeRange || '1h';
- const rangeMs = timeRangeToMs(range);
- const windowEnd = Date.now();
- const windowStart = windowEnd - rangeMs;
- const bucketDuration = rangeMs / COLUMNS;
-
- // Filter series that actually have data
- const activeSeries = props.series.filter((s) => s.data.length > 0);
-
- // Sort series to put the most active ones at the top
- const seriesWithVolume = activeSeries.map((series) => {
- let total = 0;
- for (const p of series.data) {
- if (p.timestamp >= windowStart) total += p.value;
- }
- return { series, total };
- });
- seriesWithVolume.sort((a, b) => b.total - a.total);
-
- // Take top 20 to avoid completely squished rows
- const topSeries = seriesWithVolume.slice(0, 20).map((s) => s.series);
-
- let globalMax = 0;
- const grid: { sum: number; count: number; max: number }[][] = topSeries.map(() =>
- Array(COLUMNS)
- .fill(null)
- .map(() => ({ sum: 0, count: 0, max: 0 })),
- );
-
- // Populate grid
- for (let r = 0; r < topSeries.length; r++) {
- for (const p of topSeries[r].data) {
- if (p.timestamp < windowStart || p.timestamp > windowEnd) continue;
- const col = Math.floor(((p.timestamp - windowStart) / rangeMs) * COLUMNS);
- const c = clamp(col, 0, COLUMNS - 1);
-
- grid[r][c].sum += p.value;
- grid[r][c].count += 1;
- if (p.value > grid[r][c].max) {
- grid[r][c].max = p.value;
- }
- if (p.value > globalMax) {
- globalMax = p.value;
- }
- }
- }
-
- const cellData = topSeries.map((_, r) => {
- return grid[r].map((cell) => {
- const val = cell.count > 0 ? cell.max : 0; // Or average: sum / count
- return val;
- });
- });
-
- return {
- series: topSeries,
- grid: cellData,
- globalMax,
- windowStart,
- rangeMs,
- bucketDuration,
- };
- });
-
- const drawCanvas = () => {
- if (!canvasRef) return;
- const ctx = canvasRef.getContext('2d');
- if (!ctx) return;
-
- const rect = canvasRef.getBoundingClientRect();
- const width = rect.width;
- const height = rect.height;
- if (width <= 0 || height <= 0) return;
-
- // Handle high DPI
- const dpr = typeof window !== 'undefined' ? window.devicePixelRatio || 1 : 1;
- canvasRef.width = width * dpr;
- canvasRef.height = height * dpr;
- ctx.scale(dpr, dpr);
-
- ctx.clearRect(0, 0, width, height);
-
- const data = chartData();
- if (data.series.length === 0 || data.globalMax <= 0) return;
-
- const rows = data.series.length;
- const cellW = width / COLUMNS;
- const cellH = height / rows;
-
- // Draw the grid
- for (let r = 0; r < rows; r++) {
- const cy = r * cellH;
- // Convert series color (e.g., #10b981 or rgb(16, 185, 129)) to base for alpha manipulation
- // To keep it simple, we draw a solid cell with varying opacity.
- // But multiple transparent layers can look messy if overlapping, here they don't overlap.
-
- for (let c = 0; c < COLUMNS; c++) {
- const cx = c * cellW;
- const val = data.grid[r][c];
-
- if (val <= 0) {
- // Empty cell placeholder
- ctx.fillStyle = 'rgba(128, 128, 128, 0.05)';
- ctx.fillRect(
- cx + PADDING_X / 2,
- cy + PADDING_Y / 2,
- cellW - PADDING_X,
- cellH - PADDING_Y,
- );
- continue;
- }
-
- // Logarithmic scale for color intensity (makes smaller spikes visible against massive ones)
- // normalized ranges from ~0.1 to 1.0
- const normalized = Math.log(1 + (val / data.globalMax) * 99) / Math.log(100);
-
- // Base opacity is clamped
- const opacity = clamp(normalized, 0.15, 1.0);
-
- ctx.globalAlpha = opacity;
- ctx.fillStyle = data.series[r].color;
- // Optional: add a tiny border radius using roundRect if browser supports it
- if (ctx.roundRect) {
- ctx.beginPath();
- ctx.roundRect(
- cx + PADDING_X / 2,
- cy + PADDING_Y / 2,
- cellW - PADDING_X,
- cellH - PADDING_Y,
- 2,
- );
- ctx.fill();
- } else {
- ctx.fillRect(
- cx + PADDING_X / 2,
- cy + PADDING_Y / 2,
- cellW - PADDING_X,
- cellH - PADDING_Y,
- );
- }
- }
- }
- ctx.globalAlpha = 1.0;
- };
-
- createEffect(() => drawCanvas());
-
- const handleMouseMove = (e: MouseEvent) => {
- if (!canvasRef) return;
- const rect = canvasRef.getBoundingClientRect();
- const data = chartData();
-
- const mouseX = clamp(e.clientX - rect.left, 0, rect.width - 1);
- const mouseY = clamp(e.clientY - rect.top, 0, rect.height - 1);
-
- const c = Math.floor((mouseX / rect.width) * COLUMNS);
- const r = Math.floor((mouseY / rect.height) * data.series.length);
-
- if (r >= 0 && r < data.series.length && c >= 0 && c < COLUMNS) {
- const val = data.grid[r][c];
-
- // Calculate tooltip position (center of the block)
- const cellW = rect.width / COLUMNS;
- const cellH = rect.height / data.series.length;
- const targetX = rect.left + c * cellW + cellW / 2;
- const targetY = rect.top + r * cellH;
-
- const bucketStartTime = data.windowStart + c * data.bucketDuration;
-
- setHoveredState({
- tooltipX: targetX,
- tooltipY: targetY,
- timestamp: bucketStartTime,
- value: val,
- seriesName: data.series[r].name || 'Unknown',
- seriesColor: data.series[r].color,
- });
- } else {
- setHoveredState(null);
- }
- };
-
- const handleMouseLeave = () => {
- setHoveredState(null);
- };
-
- // Resize listener
- createEffect(() => {
- if (typeof window === 'undefined') return;
- const handleResize = () => drawCanvas();
- window.addEventListener('resize', handleResize);
- onCleanup(() => window.removeEventListener('resize', handleResize));
- });
+ const densityMap = useDensityMapState(props);
return (
- <div class="relative w-full h-full flex flex-col group" ref={chartSurfaceRef}>
+ <div class="relative w-full h-full flex flex-col group">
<div class="flex-1 relative min-h-0 bg-transparent flex">
{/* Y-axis: typically in a density map we might just show "Top Nodes" */}
<div class="absolute left-0 top-0 h-full w-full pointer-events-none flex flex-col justify-between py-1 opacity-0 group-hover:opacity-100 transition-opacity">
@@ -247,10 +21,10 @@ export const DensityMap: Component<DensityMapProps> = (props) => {
<div class="h-full ml-1 mr-1 flex-1">
<canvas
- ref={canvasRef}
+ ref={densityMap.setCanvasRef}
class="w-full h-full cursor-crosshair block"
- onMouseMove={handleMouseMove}
- onMouseLeave={handleMouseLeave}
+ onMouseMove={densityMap.handleMouseMove}
+ onMouseLeave={densityMap.handleMouseLeave}
/>
</div>
</div>
@@ -266,7 +40,7 @@ export const DensityMap: Component<DensityMapProps> = (props) => {
</div>
<Portal>
- <Show when={hoveredState()}>
+ <Show when={densityMap.hoveredState()}>
{(hover) => (
<div
class="fixed pointer-events-none text-xs rounded px-2 py-1.5 shadow-lg border border-slate-600"
@@ -280,12 +54,14 @@ export const DensityMap: Component<DensityMapProps> = (props) => {
}}
>
<div class="font-medium text-center mb-1 text-slate-300">
- {formatHoverTime(hover().timestamp)}
+ {formatDensityMapHoverTime(hover().timestamp)}
</div>
<div class="flex items-center gap-1.5 leading-tight">
<span class="w-2 h-2 rounded-sm" style={{ background: hover().seriesColor }} />
<span class="font-semibold text-white">{hover().seriesName}</span>
- <span class="ml-2 font-medium text-emerald-400">{formatValue(hover().value)}</span>
+ <span class="ml-2 font-medium text-emerald-400">
+ {densityMap.formatValue(hover().value)}
+ </span>
</div>
</div>
)}
diff --git a/frontend-modern/src/components/shared/SharedPrimitives.guardrails.test.ts b/frontend-modern/src/components/shared/SharedPrimitives.guardrails.test.ts
index 946ff5ca40..072153aae9 100644
--- a/frontend-modern/src/components/shared/SharedPrimitives.guardrails.test.ts
+++ b/frontend-modern/src/components/shared/SharedPrimitives.guardrails.test.ts
@@ -2,6 +2,8 @@ import { describe, expect, it } from 'vitest';
import calloutCardSource from '@/components/shared/CalloutCard.tsx?raw';
import containerUpdateBadgeSource from '@/components/shared/ContainerUpdateBadge.tsx?raw';
import containerUpdateBadgeModelSource from '@/components/shared/containerUpdateBadgeModel.ts?raw';
+import densityMapSource from '@/components/shared/DensityMap.tsx?raw';
+import densityMapModelSource from '@/components/shared/densityMapModel.ts?raw';
import filterButtonGroupSource from '@/components/shared/FilterButtonGroup.tsx?raw';
import helpIconSource from '@/components/shared/HelpIcon.tsx?raw';
import helpIconModelSource from '@/components/shared/helpIconModel.ts?raw';
@@ -17,6 +19,7 @@ import monitoredSystemLimitWarningBannerSource from '@/components/shared/Monitor
import selectionCardGroupSource from '@/components/shared/SelectionCardGroup.tsx?raw';
import tagBadgesSource from '@/components/shared/TagBadges.tsx?raw';
import containerUpdateButtonStateSource from '@/components/shared/useContainerUpdateButtonState.ts?raw';
+import densityMapStateSource from '@/components/shared/useDensityMapState.ts?raw';
import helpIconStateSource from '@/components/shared/useHelpIconState.ts?raw';
import historyChartStateSource from '@/components/shared/useHistoryChartState.ts?raw';
import interactiveSparklineStateSource from '@/components/shared/useInteractiveSparklineState.ts?raw';
@@ -173,6 +176,23 @@ describe('shared primitive guardrails', () => {
expect(interactiveSparklineModelSource).toContain('findNearestMetricPoint');
});
+ it('keeps density map on shell, runtime, and model owners', () => {
+ expect(densityMapSource).toContain('useDensityMapState');
+ expect(densityMapSource).not.toContain('timeRangeToMs');
+ expect(densityMapSource).not.toContain('createSignal');
+ expect(densityMapSource).not.toContain('ctx.fillRect');
+
+ expect(densityMapStateSource).toContain('export function useDensityMapState');
+ expect(densityMapStateSource).toContain('createSignal');
+ expect(densityMapStateSource).toContain('canvas.getContext');
+ expect(densityMapStateSource).toContain('window.addEventListener');
+
+ expect(densityMapModelSource).toContain('buildDensityMapChartData');
+ expect(densityMapModelSource).toContain('buildDensityMapHoveredState');
+ expect(densityMapModelSource).toContain('formatDensityMapHoverTime');
+ expect(densityMapModelSource).toContain('getDensityMapCellOpacity');
+ });
+
it('keeps history chart on shell, runtime, and model owners', () => {
expect(historyChartSource).toContain('useHistoryChartState');
expect(historyChartSource).not.toContain('ChartsAPI.getMetricsHistory');
diff --git a/frontend-modern/src/components/shared/__tests__/DensityMap.test.tsx b/frontend-modern/src/components/shared/__tests__/DensityMap.test.tsx
new file mode 100644
index 0000000000..9fe6f45339
--- /dev/null
+++ b/frontend-modern/src/components/shared/__tests__/DensityMap.test.tsx
@@ -0,0 +1,79 @@
+import { fireEvent, render, screen } from '@solidjs/testing-library';
+import { describe, expect, it, vi } from 'vitest';
+import densityMapSource from '@/components/shared/DensityMap.tsx?raw';
+import densityMapModelSource from '@/components/shared/densityMapModel.ts?raw';
+import densityMapStateSource from '@/components/shared/useDensityMapState.ts?raw';
+import { DensityMap } from '@/components/shared/DensityMap';
+
+HTMLCanvasElement.prototype.getContext = vi.fn(() => ({
+ clearRect: vi.fn(),
+ setTransform: vi.fn(),
+ scale: vi.fn(),
+ beginPath: vi.fn(),
+ roundRect: vi.fn(),
+ fill: vi.fn(),
+ fillRect: vi.fn(),
+ globalAlpha: 1,
+ fillStyle: '',
+})) as unknown as typeof HTMLCanvasElement.prototype.getContext;
+
+describe('DensityMap', () => {
+ it('keeps the density map on shell, runtime, and model owners', () => {
+ expect(densityMapSource).toContain('useDensityMapState');
+ expect(densityMapSource).not.toContain('timeRangeToMs');
+ expect(densityMapSource).not.toContain('createSignal');
+ expect(densityMapSource).not.toContain('ctx.fillRect');
+
+ expect(densityMapStateSource).toContain('createSignal');
+ expect(densityMapStateSource).toContain('canvas.getContext');
+ expect(densityMapStateSource).toContain('window.addEventListener');
+ expect(densityMapStateSource).toContain('export function useDensityMapState');
+
+ expect(densityMapModelSource).toContain('buildDensityMapChartData');
+ expect(densityMapModelSource).toContain('buildDensityMapHoveredState');
+ expect(densityMapModelSource).toContain('getDensityMapCellOpacity');
+ });
+
+ it('renders the time range labels and hover tooltip', async () => {
+ const now = Date.now();
+ const { container } = render(() => (
+ <DensityMap
+ timeRange="1h"
+ series={[
+ {
+ name: 'CPU',
+ color: '#10b981',
+ data: [
+ { timestamp: now - 30_000, value: 25 },
+ { timestamp: now - 10_000, value: 55 },
+ ],
+ },
+ ]}
+ />
+ ));
+
+ expect(screen.getByText('-1h')).toBeInTheDocument();
+ expect(screen.getByText('now')).toBeInTheDocument();
+
+ const canvas = container.querySelector('canvas');
+ expect(canvas).not.toBeNull();
+ if (!canvas) return;
+
+ (canvas as unknown as { getBoundingClientRect: () => DOMRect }).getBoundingClientRect = () =>
+ ({
+ left: 0,
+ top: 0,
+ width: 180,
+ height: 80,
+ right: 180,
+ bottom: 80,
+ x: 0,
+ y: 0,
+ toJSON: () => ({}),
+ }) as unknown as DOMRect;
+
+ fireEvent.mouseMove(canvas, { clientX: 160, clientY: 20 });
+
+ expect(await screen.findByText('CPU')).toBeInTheDocument();
+ });
+});
diff --git a/frontend-modern/src/components/shared/densityMapModel.ts b/frontend-modern/src/components/shared/densityMapModel.ts
new file mode 100644
index 0000000000..1b24fe2538
--- /dev/null
+++ b/frontend-modern/src/components/shared/densityMapModel.ts
@@ -0,0 +1,150 @@
+import type { TimeRange } from '@/api/charts';
+import { timeRangeToMs } from '@/utils/timeRange';
+import type { InteractiveSparklineSeries } from './InteractiveSparkline';
+
+export interface DensityMapProps {
+ series: InteractiveSparklineSeries[];
+ rangeLabel?: string;
+ timeRange?: TimeRange;
+ formatValue?: (value: number) => string;
+}
+
+export interface DensityMapHoveredState {
+ tooltipX: number;
+ tooltipY: number;
+ timestamp: number;
+ value: number;
+ seriesName: string;
+ seriesColor: string;
+}
+
+export interface DensityMapChartData {
+ series: InteractiveSparklineSeries[];
+ grid: number[][];
+ globalMax: number;
+ windowStart: number;
+ rangeMs: number;
+ bucketDuration: number;
+}
+
+export const DENSITY_MAP_COLUMNS = 45;
+export const DENSITY_MAP_PADDING_Y = 2;
+export const DENSITY_MAP_PADDING_X = 2;
+
+export function clampDensityMapValue(value: number, min: number, max: number): number {
+ return Math.max(min, Math.min(value, max));
+}
+
+export function formatDensityMapHoverTime(timestamp: number): string {
+ return new Date(timestamp).toLocaleString([], {
+ month: 'short',
+ day: '2-digit',
+ hour: '2-digit',
+ minute: '2-digit',
+ hour12: false,
+ });
+}
+
+export function formatDensityMapValue(
+ value: number,
+ formatter?: (value: number) => string,
+): string {
+ return formatter ? formatter(value) : `${value.toFixed(1)}`;
+}
+
+export function buildDensityMapChartData(options: {
+ series: InteractiveSparklineSeries[];
+ timeRange?: TimeRange;
+ now?: number;
+}): DensityMapChartData {
+ const range = options.timeRange || '1h';
+ const rangeMs = timeRangeToMs(range);
+ const windowEnd = options.now ?? Date.now();
+ const windowStart = windowEnd - rangeMs;
+ const bucketDuration = rangeMs / DENSITY_MAP_COLUMNS;
+
+ const activeSeries = options.series.filter((series) => series.data.length > 0);
+ const seriesWithVolume = activeSeries.map((series) => {
+ let total = 0;
+ for (const point of series.data) {
+ if (point.timestamp >= windowStart) total += point.value;
+ }
+ return { series, total };
+ });
+ seriesWithVolume.sort((left, right) => right.total - left.total);
+
+ const topSeries = seriesWithVolume.slice(0, 20).map((entry) => entry.series);
+ let globalMax = 0;
+ const grid: { sum: number; count: number; max: number }[][] = topSeries.map(() =>
+ Array(DENSITY_MAP_COLUMNS)
+ .fill(null)
+ .map(() => ({ sum: 0, count: 0, max: 0 })),
+ );
+
+ for (let row = 0; row < topSeries.length; row += 1) {
+ for (const point of topSeries[row].data) {
+ if (point.timestamp < windowStart || point.timestamp > windowEnd) continue;
+ const column = Math.floor(((point.timestamp - windowStart) / rangeMs) * DENSITY_MAP_COLUMNS);
+ const clampedColumn = clampDensityMapValue(column, 0, DENSITY_MAP_COLUMNS - 1);
+
+ grid[row][clampedColumn].sum += point.value;
+ grid[row][clampedColumn].count += 1;
+ if (point.value > grid[row][clampedColumn].max) {
+ grid[row][clampedColumn].max = point.value;
+ }
+ if (point.value > globalMax) {
+ globalMax = point.value;
+ }
+ }
+ }
+
+ const cellData = topSeries.map((_, row) =>
+ grid[row].map((cell) => (cell.count > 0 ? cell.max : 0)),
+ );
+
+ return {
+ series: topSeries,
+ grid: cellData,
+ globalMax,
+ windowStart,
+ rangeMs,
+ bucketDuration,
+ };
+}
+
+export function getDensityMapCellOpacity(value: number, globalMax: number): number {
+ if (value <= 0 || globalMax <= 0) return 0;
+ const normalized = Math.log(1 + (value / globalMax) * 99) / Math.log(100);
+ return clampDensityMapValue(normalized, 0.15, 1.0);
+}
+
+export function buildDensityMapHoveredState(options: {
+ clientX: number;
+ clientY: number;
+ rect: DOMRect;
+ data: DensityMapChartData;
+}): DensityMapHoveredState | null {
+ const { rect, data } = options;
+ if (data.series.length === 0) return null;
+
+ const mouseX = clampDensityMapValue(options.clientX - rect.left, 0, rect.width - 1);
+ const mouseY = clampDensityMapValue(options.clientY - rect.top, 0, rect.height - 1);
+ const column = Math.floor((mouseX / rect.width) * DENSITY_MAP_COLUMNS);
+ const row = Math.floor((mouseY / rect.height) * data.series.length);
+
+ if (row < 0 || row >= data.series.length || column < 0 || column >= DENSITY_MAP_COLUMNS) {
+ return null;
+ }
+
+ const cellWidth = rect.width / DENSITY_MAP_COLUMNS;
+ const cellHeight = rect.height / data.series.length;
+
+ return {
+ tooltipX: rect.left + column * cellWidth + cellWidth / 2,
+ tooltipY: rect.top + row * cellHeight,
+ timestamp: data.windowStart + column * data.bucketDuration,
+ value: data.grid[row][column],
+ seriesName: data.series[row].name || 'Unknown',
+ seriesColor: data.series[row].color,
+ };
+}
diff --git a/frontend-modern/src/components/shared/useDensityMapState.ts b/frontend-modern/src/components/shared/useDensityMapState.ts
new file mode 100644
index 0000000000..d3e54fcda9
--- /dev/null
+++ b/frontend-modern/src/components/shared/useDensityMapState.ts
@@ -0,0 +1,136 @@
+import { createEffect, createMemo, createSignal, onCleanup } from 'solid-js';
+import {
+ buildDensityMapChartData,
+ buildDensityMapHoveredState,
+ formatDensityMapValue,
+ getDensityMapCellOpacity,
+ DENSITY_MAP_COLUMNS,
+ DENSITY_MAP_PADDING_X,
+ DENSITY_MAP_PADDING_Y,
+ type DensityMapHoveredState,
+ type DensityMapProps,
+} from './densityMapModel';
+
+export function useDensityMapState(props: DensityMapProps) {
+ const [hoveredState, setHoveredState] = createSignal<DensityMapHoveredState | null>(null);
+ const [canvasRef, setCanvasRef] = createSignal<HTMLCanvasElement>();
+
+ const chartData = createMemo(() =>
+ buildDensityMapChartData({
+ series: props.series,
+ timeRange: props.timeRange,
+ }),
+ );
+
+ const formatValue = (value: number) => formatDensityMapValue(value, props.formatValue);
+
+ const drawCanvas = () => {
+ const canvas = canvasRef();
+ if (!canvas) return;
+
+ const context = canvas.getContext('2d');
+ if (!context) return;
+
+ const rect = canvas.getBoundingClientRect();
+ const width = rect.width;
+ const height = rect.height;
+ if (width <= 0 || height <= 0) return;
+
+ const dpr = typeof window !== 'undefined' ? window.devicePixelRatio || 1 : 1;
+ canvas.width = width * dpr;
+ canvas.height = height * dpr;
+ context.setTransform(1, 0, 0, 1, 0, 0);
+ context.scale(dpr, dpr);
+ context.clearRect(0, 0, width, height);
+
+ const data = chartData();
+ if (data.series.length === 0 || data.globalMax <= 0) return;
+
+ const rows = data.series.length;
+ const cellWidth = width / DENSITY_MAP_COLUMNS;
+ const cellHeight = height / rows;
+
+ for (let row = 0; row < rows; row += 1) {
+ const cellY = row * cellHeight;
+ for (let column = 0; column < DENSITY_MAP_COLUMNS; column += 1) {
+ const cellX = column * cellWidth;
+ const value = data.grid[row][column];
+
+ if (value <= 0) {
+ context.fillStyle = 'rgba(128, 128, 128, 0.05)';
+ context.fillRect(
+ cellX + DENSITY_MAP_PADDING_X / 2,
+ cellY + DENSITY_MAP_PADDING_Y / 2,
+ cellWidth - DENSITY_MAP_PADDING_X,
+ cellHeight - DENSITY_MAP_PADDING_Y,
+ );
+ continue;
+ }
+
+ context.globalAlpha = getDensityMapCellOpacity(value, data.globalMax);
+ context.fillStyle = data.series[row].color;
+ if (context.roundRect) {
+ context.beginPath();
+ context.roundRect(
+ cellX + DENSITY_MAP_PADDING_X / 2,
+ cellY + DENSITY_MAP_PADDING_Y / 2,
+ cellWidth - DENSITY_MAP_PADDING_X,
+ cellHeight - DENSITY_MAP_PADDING_Y,
+ 2,
+ );
+ context.fill();
+ } else {
+ context.fillRect(
+ cellX + DENSITY_MAP_PADDING_X / 2,
+ cellY + DENSITY_MAP_PADDING_Y / 2,
+ cellWidth - DENSITY_MAP_PADDING_X,
+ cellHeight - DENSITY_MAP_PADDING_Y,
+ );
+ }
+ }
+ }
+
+ context.globalAlpha = 1;
+ };
+
+ createEffect(() => {
+ drawCanvas();
+ });
+
+ const handleMouseMove = (event: MouseEvent) => {
+ const canvas = canvasRef();
+ if (!canvas) return;
+
+ setHoveredState(
+ buildDensityMapHoveredState({
+ clientX: event.clientX,
+ clientY: event.clientY,
+ rect: canvas.getBoundingClientRect(),
+ data: chartData(),
+ }),
+ );
+ };
+
+ const handleMouseLeave = () => {
+ setHoveredState(null);
+ };
+
+ createEffect(() => {
+ if (typeof window === 'undefined') return;
+
+ const handleResize = () => drawCanvas();
+ window.addEventListener('resize', handleResize);
+ onCleanup(() => window.removeEventListener('resize', handleResize));
+ });
+
+ return {
+ chartData,
+ formatValue,
+ handleMouseLeave,
+ handleMouseMove,
+ hoveredState,
+ setCanvasRef,
+ };
+}
+
+export type DensityMapState = ReturnType<typeof useDensityMapState>;
diff --git a/frontend-modern/src/utils/__tests__/frontendResourceTypeBoundaries.test.ts b/frontend-modern/src/utils/__tests__/frontendResourceTypeBoundaries.test.ts
index fbf584d007..ee8956ebe9 100644
--- a/frontend-modern/src/utils/__tests__/frontendResourceTypeBoundaries.test.ts
+++ b/frontend-modern/src/utils/__tests__/frontendResourceTypeBoundaries.test.ts
@@ -10,6 +10,8 @@ import alertTargetTypesSource from '@/utils/alertTargetTypes.ts?raw';
import resourceBadgesSource from '@/components/Infrastructure/resourceBadges.ts?raw';
import containerUpdateBadgeSource from '@/components/shared/ContainerUpdateBadge.tsx?raw';
import containerUpdateBadgeModelSource from '@/components/shared/containerUpdateBadgeModel.ts?raw';
+import densityMapSource from '@/components/shared/DensityMap.tsx?raw';
+import densityMapModelSource from '@/components/shared/densityMapModel.ts?raw';
import helpIconSource from '@/components/shared/HelpIcon.tsx?raw';
import helpIconModelSource from '@/components/shared/helpIconModel.ts?raw';
import historyChartSource from '@/components/shared/HistoryChart.tsx?raw';
@@ -28,6 +30,7 @@ import resourceBadgePresentationSource from '@/utils/resourceBadgePresentation.t
import workloadTypeBadgesSource from '@/components/shared/workloadTypeBadges.ts?raw';
import tagBadgesSource from '@/components/shared/TagBadges.tsx?raw';
import emptyStateSource from '@/components/shared/EmptyState.tsx?raw';
+import densityMapStateSource from '@/components/shared/useDensityMapState.ts?raw';
import webInterfaceUrlFieldSource from '@/components/shared/WebInterfaceUrlField.tsx?raw';
import webInterfaceUrlFieldModelSource from '@/components/shared/webInterfaceUrlFieldModel.ts?raw';
import webInterfaceUrlFieldStateSource from '@/components/shared/useWebInterfaceUrlFieldState.ts?raw';
@@ -2645,6 +2648,17 @@ describe('frontend resource type boundaries', () => {
expect(interactiveSparklineModelSource).toContain(
'computeInteractiveSparklineHoverState',
);
+ expect(densityMapSource).toContain('useDensityMapState');
+ expect(densityMapSource).not.toContain('timeRangeToMs');
+ expect(densityMapSource).not.toContain('createSignal');
+ expect(densityMapSource).not.toContain('ctx.fillRect');
+ expect(densityMapStateSource).toContain('createSignal');
+ expect(densityMapStateSource).toContain('canvas.getContext');
+ expect(densityMapStateSource).toContain('window.addEventListener');
+ expect(densityMapModelSource).toContain('buildDensityMapChartData');
+ expect(densityMapModelSource).toContain('buildDensityMapHoveredState');
+ expect(densityMapModelSource).toContain('formatDensityMapHoverTime');
+ expect(densityMapModelSource).toContain('getDensityMapCellOpacity');
expect(historyChartSource).toContain('useHistoryChartState');
expect(historyChartSource).not.toContain('ChartsAPI.getMetricsHistory');
expect(historyChartSource).not.toContain('calculateOptimalPoints');