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.
Go aialertsdashboarddockerdocker-monitoringgohomelabinfrastructure-monitoringkubernetesmonitoringmspproxmoxproxmox-backup-serverproxmox-mail-gatewayproxmox-veself-hostedtruenastypescriptvspherewebhooks
Delete InteractiveSparkline model + state hook orphaned by Cleanup N
rcourtman4926119d0ffc
diff --git a/frontend-modern/src/components/shared/interactiveSparklineModel.ts b/frontend-modern/src/components/shared/interactiveSparklineModel.tsdeleted file mode 100644index ff90f696dc..0000000000--- a/frontend-modern/src/components/shared/interactiveSparklineModel.ts+++ /dev/null@@ -1,760 +0,0 @@-import type { MetricPoint, TimeRange } from '@/api/charts';-import { downsampleLTTB, calculateOptimalPoints } from '@/utils/downsample';-import { timeRangeToMs } from '@/utils/timeRange';-import type { SummaryChartHoverSync } from './contextualFocus';-import type { SummaryCardInteractionState } from './summaryCardInteraction';--export interface InteractiveSparklineSeries {- id?: string;- data: MetricPoint[];- color: string;- name?: string;-}--export interface InteractiveSparklineProps {- series: InteractiveSparklineSeries[];- rangeLabel?: string;- timeRange?: TimeRange;- renderMode?: 'auto' | 'svg' | 'canvas';- activeSeriesDisplay?: 'emphasize' | 'isolate';- yMode?: 'percent' | 'auto';- size?: 'sm' | 'md' | 'lg';- bridgeLeadingGap?: boolean;- formatValue?: (value: number) => string;- formatTopLabel?: (maxValue: number) => string;- sortTooltipByValue?: boolean;- maxTooltipRows?: number;- highlightNearestSeriesOnHover?: boolean;- highlightSeriesId?: string | null;- hoverSourceKey?: string;- hoverSync?: SummaryChartHoverSync | null;- onHoverSyncChange?: (value: SummaryChartHoverSync | null) => void;- interactionState?: SummaryCardInteractionState;-}--export interface InteractiveSparklineChartSeries extends InteractiveSparklineSeries {- hoverData: MetricPoint[];- drawData: MetricPoint[];- segments: MetricPoint[][];-}--export interface InteractiveSparklinePathData {- path: string;- areaPath?: string;- color: string;- seriesIndex: number;-}--export interface InteractiveSparklineChartData {- validSeries: InteractiveSparklineChartSeries[];- paths: InteractiveSparklinePathData[];- windowStart: number;- rangeMs: number;- scaleMax: number;-}--export interface InteractiveSparklineDisplayValue {- name: string;- color: string;- value: number;- seriesIndex: number;-}--export interface InteractiveSparklineHoverState {- x: number;- tooltipX: number;- tooltipY: number;- timestamp: number;- totalValues: number;- nearestSeriesIndex: number | null;- highlightedSeriesIndex: number | null;- focusedTooltip: boolean;- values: InteractiveSparklineDisplayValue[];-}--interface HoverSeriesValue extends InteractiveSparklineDisplayValue {- timestamp: number;-}--const INTERACTIVE_SPARKLINE_TOOLTIP_GAP = 12;-const INTERACTIVE_SPARKLINE_TOOLTIP_MAX_WIDTH = 220;-const INTERACTIVE_SPARKLINE_VIEWPORT_PADDING = 4;--export const formatInteractiveSparklineHoverTime = (timestamp: number): string =>- new Date(timestamp).toLocaleString([], {- year: 'numeric',- month: 'short',- day: '2-digit',- hour: '2-digit',- minute: '2-digit',- second: '2-digit',- hour12: false,- });--export const clampInteractiveSparklineValue = (value: number, min: number, max: number): number =>- Math.max(min, Math.min(value, max));--export const formatInteractiveSparklineRelativeOffset = (offsetMs: number): string => {- if (offsetMs <= 0) return 'now';- const dayMs = 24 * 60 * 60_000;- const hourMs = 60 * 60_000;- const minuteMs = 60_000;-- if (offsetMs >= dayMs) {- return `-${Math.round(offsetMs / dayMs)}d`;- }- if (offsetMs >= hourMs) {- return `-${Math.round(offsetMs / hourMs)}h`;- }- return `-${Math.max(1, Math.round(offsetMs / minuteMs))}m`;-};--const findNearestMetricPoint = (- points: MetricPoint[],- targetTimestamp: number,-): { point: MetricPoint; index: number } | null => {- if (points.length === 0) return null;-- let low = 0;- let high = points.length - 1;- while (low < high) {- const mid = Math.floor((low + high) / 2);- if (points[mid].timestamp < targetTimestamp) {- low = mid + 1;- } else {- high = mid;- }- }-- const candidate = points[low];- const previous = low > 0 ? points[low - 1] : candidate;- if (- Math.abs(previous.timestamp - targetTimestamp) <=- Math.abs(candidate.timestamp - targetTimestamp)- ) {- return { point: previous, index: low > 0 ? low - 1 : low };- }- return { point: candidate, index: low };-};--const ensureRenderablePoints = (points: MetricPoint[], windowStart: number): MetricPoint[] => {- if (points.length === 0) return [];- if (points.length >= 2) return points;- const point = points[0];- return [- {- timestamp: Math.max(windowStart, point.timestamp - 1_000),- value: point.value,- },- point,- ];-};--const splitPointsOnGaps = (- points: MetricPoint[],- gapThresholdMs: number,- windowStart: number,- bridgeLeadingGap: boolean,-): MetricPoint[][] => {- if (points.length === 0) return [];- const segments: MetricPoint[][] = [];- let currentSegment: MetricPoint[] = [points[0]];-- for (let index = 1; index < points.length; index++) {- const previous = points[index - 1];- const current = points[index];- const hasGap = current.timestamp - previous.timestamp > gapThresholdMs;- const isLeadingBridgeGap =- bridgeLeadingGap &&- segments.length === 0 &&- currentSegment.length === 1 &&- currentSegment[0].timestamp <= windowStart + 1_000;-- if (hasGap && !isLeadingBridgeGap) {- segments.push(ensureRenderablePoints(currentSegment, windowStart));- currentSegment = [current];- continue;- }- currentSegment.push(current);- }-- segments.push(ensureRenderablePoints(currentSegment, windowStart));- return segments;-};--const inferGapThresholdMs = (points: MetricPoint[], rangeMs: number): number => {- if (points.length < 3) return rangeMs + 1;-- const deltas: number[] = [];- for (let index = 1; index < points.length; index++) {- const delta = points[index].timestamp - points[index - 1].timestamp;- if (delta > 0) {- deltas.push(delta);- }- }- if (deltas.length < 2) return rangeMs + 1;-- deltas.sort((left, right) => left - right);- const p90Delta = deltas[Math.floor(deltas.length * 0.9)];- const minThreshold = Math.max(15_000, Math.floor(rangeMs / 120));- const maxThreshold = Math.max(minThreshold, Math.floor(rangeMs / 2));- return clampInteractiveSparklineValue(p90Delta * 3, minThreshold, maxThreshold);-};--const selectTopValuesByValue = (values: HoverSeriesValue[], limit: number): HoverSeriesValue[] => {- if (limit <= 0 || values.length === 0) return [];- if (values.length <= limit) {- return [...values].sort((left, right) => right.value - left.value);- }-- const top: HoverSeriesValue[] = [];- for (const value of values) {- let insertAt = top.length;- for (let index = 0; index < top.length; index++) {- if (value.value > top[index].value) {- insertAt = index;- break;- }- }- if (insertAt >= limit && top.length >= limit) continue;- top.splice(insertAt, 0, value);- if (top.length > limit) {- top.pop();- }- }- return top;-};--export const getInteractiveSparklineShouldUseCanvas = (- series: InteractiveSparklineSeries[],- renderMode: InteractiveSparklineProps['renderMode'],- canvasSeriesThreshold = 120,- canvasPointThreshold = 15_000,-) => {- if (renderMode === 'svg') return false;- if (renderMode === 'canvas') return true;- const totalPoints = series.reduce((sum, item) => sum + item.data.length, 0);- return series.length >= canvasSeriesThreshold || totalPoints >= canvasPointThreshold;-};--export const buildInteractiveSparklineChartData = ({- series,- timeRange,- yMode,- vbW,- vbH,- shouldUseCanvas,- bridgeLeadingGap,-}: {- series: InteractiveSparklineSeries[];- timeRange: TimeRange;- yMode: 'percent' | 'auto';- vbW: number;- vbH: number;- shouldUseCanvas: boolean;- bridgeLeadingGap: boolean;-}): InteractiveSparklineChartData => {- const rangeMs = timeRangeToMs(timeRange);- const windowEnd = Date.now();- const windowStart = windowEnd - rangeMs;- const targetPoints = calculateOptimalPoints(vbW, 'sparkline');- const validSeries = series- .map((item) => {- const inWindow = item.data.filter(- (point) => point.timestamp >= windowStart && point.timestamp <= windowEnd,- );- if (inWindow.length < 2) return null;- const renderable = ensureRenderablePoints(inWindow, windowStart);- if (renderable.length === 0) return null;- const drawData =- renderable.length > targetPoints * 1.5- ? downsampleLTTB(renderable, targetPoints)- : renderable;- const segments = splitPointsOnGaps(- drawData,- inferGapThresholdMs(drawData, rangeMs),- windowStart,- bridgeLeadingGap,- );- return {- ...item,- hoverData: renderable,- drawData,- segments,- };- })- .filter((item): item is InteractiveSparklineChartSeries => item !== null);-- if (validSeries.length === 0) {- return {- validSeries: [],- paths: [],- windowStart,- rangeMs,- scaleMax: 0,- };- }-- let scaleMax = 100;- if (yMode === 'auto') {- scaleMax = 0;- for (const item of validSeries) {- for (const point of item.hoverData) {- if (point.value > scaleMax) scaleMax = point.value;- }- }- if (scaleMax <= 0) {- return {- validSeries,- paths: [],- windowStart,- rangeMs,- scaleMax: 0,- };- }- }-- const paths = shouldUseCanvas- ? []- : validSeries.flatMap((item, seriesIndex) =>- item.segments.map((segment) => {- const coords = segment.map((point) => {- const x = clampInteractiveSparklineValue(- ((point.timestamp - windowStart) / rangeMs) * vbW,- 0,- vbW,- );- const normalized =- yMode === 'auto'- ? Math.max(0, point.value) / scaleMax- : Math.min(Math.max(point.value, 0), 100) / 100;- const y = vbH - normalized * vbH;- return { x, y };- });- const pathStrings = coords.map((coord) => `${coord.x.toFixed(1)},${coord.y.toFixed(1)}`);- const path = `M${pathStrings.join('L')}`;- let areaPath = '';- if (validSeries.length === 1 && coords.length > 1) {- areaPath = `${path} L${coords[coords.length - 1].x.toFixed(1)},${vbH} L${coords[0].x.toFixed(1)},${vbH} Z`;- }- return { path, areaPath, color: item.color, seriesIndex };- }),- );-- return {- validSeries,- paths,- windowStart,- rangeMs,- scaleMax,- };-};--export const createInteractiveSparklineValueToY = (- yMode: 'percent' | 'auto',- scaleMax: number,- vbH: number,-) => {- return (value: number): number => {- if (yMode === 'auto') {- if (scaleMax <= 0) return vbH;- return vbH - (Math.max(0, value) / scaleMax) * vbH;- }- return vbH - (Math.min(Math.max(value, 0), 100) / 100) * vbH;- };-};--export const buildInteractiveSparklineTopLabel = ({- yMode,- scaleMax,- formatTopLabel,-}: {- yMode: 'percent' | 'auto';- scaleMax: number;- formatTopLabel?: (maxValue: number) => string;-}) => {- if (yMode === 'percent') return '100%';- if (scaleMax <= 0) return '0';- return formatTopLabel ? formatTopLabel(scaleMax) : scaleMax.toFixed(1);-};--export const buildInteractiveSparklineAxisTicks = (- yMode: 'percent' | 'auto',- topLabel: string,- vbH: number,-) => {- if (yMode === 'percent') {- return [- { label: '100%', y: 0, anchor: 'top' as const },- { label: '80%', y: vbH * 0.2, anchor: 'middle' as const },- { label: '60%', y: vbH * 0.4, anchor: 'middle' as const },- { label: '40%', y: vbH * 0.6, anchor: 'middle' as const },- { label: '20%', y: vbH * 0.8, anchor: 'middle' as const },- { label: '0%', y: vbH, anchor: 'bottom' as const },- ];- }-- return [- { label: topLabel, y: 0, anchor: 'top' as const },- { label: '0', y: vbH, anchor: 'bottom' as const },- ];-};--export const buildInteractiveSparklineGridLineY = (yMode: 'percent' | 'auto', vbH: number) => {- if (yMode === 'percent') {- return [vbH * 0.2, vbH * 0.4, vbH * 0.6, vbH * 0.8];- }- return [vbH * 0.25, vbH * 0.5, vbH * 0.75];-};--export const buildInteractiveSparklineGridLineX = (vbW: number) => [vbW * 0.5];--export const buildInteractiveSparklineXAxisTicks = ({- rangeMs,- rangeLabel,- timeRange,- vbW,-}: {- rangeMs: number;- rangeLabel?: string;- timeRange: TimeRange;- vbW: number;-}) => {- const rangeToken = rangeLabel || timeRange;- return [- { x: 0, label: `-${rangeToken}`, anchor: 'start' as const },- {- x: vbW * 0.5,- label: formatInteractiveSparklineRelativeOffset(rangeMs / 2),- anchor: 'middle' as const,- },- { x: vbW, label: 'now', anchor: 'end' as const },- ];-};--export const getInteractiveSparklineExternalSeriesIndex = (- chartData: InteractiveSparklineChartData,- highlightSeriesId?: string | null,-) => {- if (!highlightSeriesId) return null;- const index = chartData.validSeries.findIndex((series) => series.id === highlightSeriesId);- return index >= 0 ? index : null;-};--export const getInteractiveSparklineCursorXForTimestamp = ({- chartData,- timestamp,- vbW,-}: {- chartData: InteractiveSparklineChartData;- timestamp: number | null | undefined;- vbW: number;-}): number | null => {- if (timestamp === null || timestamp === undefined || chartData.rangeMs <= 0) {- return null;- }- const clampedTimestamp = clampInteractiveSparklineValue(- timestamp,- chartData.windowStart,- chartData.windowStart + chartData.rangeMs,- );- return ((clampedTimestamp - chartData.windowStart) / chartData.rangeMs) * vbW;-};--export const getInteractiveSparklineTooltipSideX = ({- chartRect,- mouseX,- viewportWidth,-}: {- chartRect: DOMRect;- mouseX: number;- viewportWidth?: number;-}): number => {- const resolvedViewportWidth =- viewportWidth ??- (typeof window === 'undefined'- ? chartRect.right- : Math.max(chartRect.right, window.innerWidth));- const absoluteCursorX = chartRect.left + mouseX;- const rightX = absoluteCursorX + INTERACTIVE_SPARKLINE_TOOLTIP_GAP;- const leftX =- absoluteCursorX - INTERACTIVE_SPARKLINE_TOOLTIP_MAX_WIDTH - INTERACTIVE_SPARKLINE_TOOLTIP_GAP;- const maxRight = Math.max(- INTERACTIVE_SPARKLINE_VIEWPORT_PADDING,- resolvedViewportWidth - INTERACTIVE_SPARKLINE_VIEWPORT_PADDING,- );- const canPlaceRight = rightX + INTERACTIVE_SPARKLINE_TOOLTIP_MAX_WIDTH <= maxRight;- const canPlaceLeft = leftX >= INTERACTIVE_SPARKLINE_VIEWPORT_PADDING;-- if (canPlaceRight || !canPlaceLeft) {- return rightX;- }- return leftX;-};--export const getInteractiveSparklineActiveEmphasisSeriesIndex = ({- highlightNearestSeriesOnHover,- lockedSeriesIndex,- hoveredState,- externalSeriesIndex,-}: {- highlightNearestSeriesOnHover: boolean;- lockedSeriesIndex: number | null;- hoveredState: InteractiveSparklineHoverState | null;- externalSeriesIndex: number | null;-}) => {- if (highlightNearestSeriesOnHover && lockedSeriesIndex !== null) {- return lockedSeriesIndex;- }- if (- highlightNearestSeriesOnHover &&- hoveredState?.highlightedSeriesIndex !== null &&- hoveredState- ) {- return hoveredState.highlightedSeriesIndex;- }- return externalSeriesIndex;-};--export const buildInteractiveSparklineSynchronizedHoverState = ({- chartData,- hoverSync,- vbW,-}: {- chartData: InteractiveSparklineChartData;- hoverSync?: SummaryChartHoverSync | null;- vbW: number;-}): InteractiveSparklineHoverState | null => {- if (!hoverSync || chartData.validSeries.length === 0 || chartData.rangeMs <= 0) {- return null;- }-- const seriesIndex = chartData.validSeries.findIndex((series) => series.id === hoverSync.seriesId);- if (seriesIndex < 0) {- return null;- }-- const clampedTimestamp = clampInteractiveSparklineValue(- hoverSync.timestamp,- chartData.windowStart,- chartData.windowStart + chartData.rangeMs,- );- const series = chartData.validSeries[seriesIndex];- const nearest = findNearestMetricPoint(series.hoverData, clampedTimestamp);- if (!nearest) {- return null;- }-- const chartX = ((clampedTimestamp - chartData.windowStart) / chartData.rangeMs) * vbW;-- return {- x: chartX,- tooltipX: 0,- tooltipY: 0,- timestamp: clampedTimestamp,- totalValues: 1,- nearestSeriesIndex: seriesIndex,- highlightedSeriesIndex: seriesIndex,- focusedTooltip: true,- values: [- {- name: series.name || 'Series',- color: series.color,- value: nearest.point.value,- seriesIndex,- },- ],- };-};--export const buildInteractiveSparklineSynchronizedReadout = ({- formatValue,- hoverSourceKey,- hoverSync,- series,- timeRange,-}: {- formatValue?: (value: number) => string;- hoverSourceKey?: string;- hoverSync?: SummaryChartHoverSync | null;- series: InteractiveSparklineSeries[];- timeRange?: TimeRange;-}): { empty?: boolean; timestamp: number; value: string } | null => {- if (!hoverSync) {- return null;- }- if (hoverSourceKey && hoverSync.sourceKey === hoverSourceKey) {- return null;- }-- const targetSeries = series.find((entry) => entry.id?.trim() === hoverSync.seriesId);- if (!targetSeries) {- return null;- }-- const range = timeRange ?? '1h';- const rangeMs = timeRangeToMs(range);- const windowEnd = Date.now();- const windowStart = windowEnd - rangeMs;- const inWindow = targetSeries.data.filter(- (point) => point.timestamp >= windowStart && point.timestamp <= windowEnd,- );- if (inWindow.length === 0) {- return null;- }-- const clampedTimestamp = clampInteractiveSparklineValue(- hoverSync.timestamp,- windowStart,- windowEnd,- );- const nearest = findNearestMetricPoint(inWindow, clampedTimestamp);- if (!nearest) {- return null;- }-- return {- timestamp: nearest.point.timestamp,- value: formatValue ? formatValue(nearest.point.value) : `${nearest.point.value.toFixed(1)}%`,- };-};--export const computeInteractiveSparklineHoverState = ({- chartData,- chartRect,- clientX,- clientY,- vbW,- vbH,- yMode,- maxRows,- sortTooltipByValue,- highlightNearestSeriesOnHover,- lockedSeriesIndex,-}: {- chartData: InteractiveSparklineChartData;- chartRect: DOMRect;- clientX: number;- clientY: number;- vbW: number;- vbH: number;- yMode: 'percent' | 'auto';- maxRows: number;- sortTooltipByValue?: boolean;- highlightNearestSeriesOnHover?: boolean;- lockedSeriesIndex: number | null;-}): InteractiveSparklineHoverState | null => {- if (chartData.validSeries.length === 0 || chartData.rangeMs <= 0 || chartRect.width <= 0) {- return null;- }-- const mouseX = Math.max(0, Math.min(clientX - chartRect.left, chartRect.width));- const mouseY = Math.max(0, Math.min(clientY - chartRect.top, chartRect.height));- const chartX = (mouseX / chartRect.width) * vbW;- const targetTimestamp = chartData.windowStart + (chartX / vbW) * chartData.rangeMs;- const shouldTrackNearest = highlightNearestSeriesOnHover === true;- const chartY = shouldTrackNearest- ? (mouseY / chartRect.height) * vbH- : 0;- const valueToChartY = createInteractiveSparklineValueToY(yMode, chartData.scaleMax, vbH);-- let nearestSeriesIndex: number | null = null;- let nearestDistance = Number.POSITIVE_INFINITY;- const values: HoverSeriesValue[] = [];-- for (let seriesIndex = 0; seriesIndex < chartData.validSeries.length; seriesIndex++) {- const series = chartData.validSeries[seriesIndex];- const nearest = findNearestMetricPoint(series.hoverData, targetTimestamp);- if (!nearest) continue;- const point = nearest.point;- const pointY = valueToChartY(point.value);-- if (shouldTrackNearest) {- const distance = Math.abs(pointY - chartY);- if (distance < nearestDistance) {- nearestDistance = distance;- nearestSeriesIndex = seriesIndex;- }- }-- values.push({- name: series.name || 'Series',- color: series.color,- value: point.value,- timestamp: point.timestamp,- seriesIndex,- });- }-- if (values.length === 0) {- return null;- }-- const nearLineThresholdPx = 6;- const nearLineThresholdChartUnits = (nearLineThresholdPx / Math.max(1, chartRect.height)) * vbH;- const effectiveSeriesIndex =- lockedSeriesIndex !== null- ? lockedSeriesIndex- : shouldTrackNearest &&- nearestSeriesIndex !== null &&- nearestDistance <= nearLineThresholdChartUnits- ? nearestSeriesIndex- : null;- const focusedTooltip = effectiveSeriesIndex !== null;-- let groupedValues = values;- if (!focusedTooltip) {- const byValue = new Map<number, HoverSeriesValue[]>();- for (const value of values) {- const key = Math.round(value.value * 1000) / 1000;- if (!byValue.has(key)) byValue.set(key, []);- byValue.get(key)!.push(value);- }- groupedValues = [];- for (const group of byValue.values()) {- if (group.length > 1) {- groupedValues.push({- name: `${group.length} Series`,- color: 'currentColor',- value: group[0].value,- timestamp: group[0].timestamp,- seriesIndex: -1,- });- } else {- groupedValues.push(group[0]);- }- }- }-- const tooltipValues =- focusedTooltip && effectiveSeriesIndex !== null- ? values.filter((value) => value.seriesIndex === effectiveSeriesIndex)- : sortTooltipByValue- ? selectTopValuesByValue(groupedValues, maxRows)- : groupedValues.slice(0, maxRows);- if (tooltipValues.length === 0) {- return null;- }-- const totalValues = focusedTooltip ? tooltipValues.length : values.length;- const tooltipX = getInteractiveSparklineTooltipSideX({ chartRect, mouseX });- const tooltipY = chartRect.top + mouseY - 6;-- return {- x: chartX,- tooltipX,- tooltipY,- timestamp: tooltipValues[0].timestamp,- totalValues,- nearestSeriesIndex,- highlightedSeriesIndex:- highlightNearestSeriesOnHover && focusedTooltip ? effectiveSeriesIndex : null,- focusedTooltip,- values: tooltipValues.map((value) => ({- name: value.name,- color: value.color,- value: value.value,- seriesIndex: value.seriesIndex,- })),- };-};diff --git a/frontend-modern/src/components/shared/useInteractiveSparklineState.ts b/frontend-modern/src/components/shared/useInteractiveSparklineState.tsdeleted file mode 100644index 3aed3db386..0000000000--- a/frontend-modern/src/components/shared/useInteractiveSparklineState.ts+++ /dev/null@@ -1,499 +0,0 @@-import { createEffect, createMemo, createSignal, onCleanup } from 'solid-js';-import { scheduleSparkline, setupCanvasDPR } from '@/utils/canvasRenderQueue';-import {- buildInteractiveSparklineAxisTicks,- buildInteractiveSparklineChartData,- getInteractiveSparklineCursorXForTimestamp,- buildInteractiveSparklineGridLineX,- buildInteractiveSparklineGridLineY,- buildInteractiveSparklineSynchronizedHoverState,- buildInteractiveSparklineTopLabel,- buildInteractiveSparklineXAxisTicks,- clampInteractiveSparklineValue,- computeInteractiveSparklineHoverState,- createInteractiveSparklineValueToY,- getInteractiveSparklineActiveEmphasisSeriesIndex,- getInteractiveSparklineExternalSeriesIndex,- getInteractiveSparklineShouldUseCanvas,- type InteractiveSparklineHoverState,- type InteractiveSparklineProps,-} from './interactiveSparklineModel';--interface InteractiveSparklineRefs {- getCanvas: () => HTMLCanvasElement | undefined;- getCanvasHost: () => HTMLDivElement | undefined;- getChartSurface: () => Element | undefined;-}--export function useInteractiveSparklineState(- props: InteractiveSparklineProps,- refs: InteractiveSparklineRefs,-) {- const vbH = 100;- const vbW = 200;- const xAxisBandPx = 16;- const maxRows = () => props.maxTooltipRows ?? 6;- const yMode = () => props.yMode ?? 'percent';- const activeSeriesDisplay = () => props.activeSeriesDisplay ?? 'emphasize';- const shouldUseCanvas = createMemo(() =>- getInteractiveSparklineShouldUseCanvas(props.series, props.renderMode),- );- const formatValue = (value: number) =>- props.formatValue ? props.formatValue(value) : `${value.toFixed(1)}%`;- const interactionOpacityMultiplier = () => (props.interactionState === 'inactive' ? 0.35 : 1);-- const [hoveredState, setHoveredState] = createSignal<InteractiveSparklineHoverState | null>(null);- const [lockedSeriesIndex, setLockedSeriesIndex] = createSignal<number | null>(null);-- const chartData = createMemo(() =>- buildInteractiveSparklineChartData({- series: props.series,- timeRange: props.timeRange || '1h',- yMode: yMode(),- vbW,- vbH,- shouldUseCanvas: shouldUseCanvas(),- bridgeLeadingGap: props.bridgeLeadingGap === true,- }),- );-- let pendingHoverPosition: { clientX: number; clientY: number } | null = null;- let hoverRafId: number | null = null;- let unregisterCanvasDraw: (() => void) | null = null;-- const computeHoverState = (clientX: number, clientY: number) => {- const chartSurface = refs.getChartSurface();- if (!chartSurface) return;- const computed = computeInteractiveSparklineHoverState({- chartData: chartData(),- chartRect: chartSurface.getBoundingClientRect(),- clientX,- clientY,- vbW,- vbH,- yMode: yMode(),- maxRows: maxRows(),- sortTooltipByValue: props.sortTooltipByValue,- highlightNearestSeriesOnHover: props.highlightNearestSeriesOnHover,- lockedSeriesIndex: props.highlightNearestSeriesOnHover ? lockedSeriesIndex() : null,- });- setHoveredState(computed);- if (!props.onHoverSyncChange || !props.hoverSourceKey) {- return;- }- if (!computed) {- props.onHoverSyncChange(null);- return;- }- const highlightedIndex = computed?.highlightedSeriesIndex;- if (highlightedIndex === null || highlightedIndex === undefined) {- props.onHoverSyncChange(null);- return;- }- const highlightedSeries = chartData().validSeries[highlightedIndex];- const highlightedSeriesId = highlightedSeries?.id?.trim() || '';- if (!highlightedSeriesId) {- props.onHoverSyncChange(null);- return;- }- props.onHoverSyncChange({- sourceKey: props.hoverSourceKey,- seriesId: highlightedSeriesId,- timestamp: computed.timestamp,- });- };-- const flushHoverState = () => {- hoverRafId = null;- if (!pendingHoverPosition) return;- const position = pendingHoverPosition;- pendingHoverPosition = null;- computeHoverState(position.clientX, position.clientY);- };-- const handleMouseMove = (event: MouseEvent) => {- const shouldThrottle = chartData().validSeries.length > 80;- if (typeof window === 'undefined' || !shouldThrottle) {- computeHoverState(event.clientX, event.clientY);- return;- }- pendingHoverPosition = { clientX: event.clientX, clientY: event.clientY };- if (hoverRafId !== null) return;- hoverRafId = window.requestAnimationFrame(flushHoverState);- };-- const handleMouseLeave = () => {- pendingHoverPosition = null;- if (typeof window !== 'undefined' && hoverRafId !== null) {- window.cancelAnimationFrame(hoverRafId);- hoverRafId = null;- }- setHoveredState(null);- props.onHoverSyncChange?.(null);- };-- const handleClick = () => {- if (!props.highlightNearestSeriesOnHover) return;- const locked = lockedSeriesIndex();- if (locked !== null) {- setLockedSeriesIndex(null);- return;- }- const hovered = hoveredState();- if (!hovered) return;- const candidateSeriesIndex = hovered.highlightedSeriesIndex ?? hovered.nearestSeriesIndex;- if (candidateSeriesIndex === null) return;- setLockedSeriesIndex(candidateSeriesIndex);- };-- createEffect(() => {- const locked = lockedSeriesIndex();- if (locked === null) return;- if (locked < 0 || locked >= chartData().validSeries.length) {- setLockedSeriesIndex(null);- }- });-- const topLabel = createMemo(() =>- buildInteractiveSparklineTopLabel({- yMode: yMode(),- scaleMax: chartData().scaleMax,- formatTopLabel: props.formatTopLabel,- }),- );-- const axisTicks = createMemo(() => buildInteractiveSparklineAxisTicks(yMode(), topLabel(), vbH));- const gridLineY = createMemo(() => buildInteractiveSparklineGridLineY(yMode(), vbH));- const gridLineX = createMemo(() => buildInteractiveSparklineGridLineX(vbW));- const xAxisTicks = createMemo(() =>- buildInteractiveSparklineXAxisTicks({- rangeMs: chartData().rangeMs,- rangeLabel: props.rangeLabel,- timeRange: props.timeRange || '1h',- vbW,- }),- );-- const externalSeriesIndex = createMemo(() =>- getInteractiveSparklineExternalSeriesIndex(chartData(), props.highlightSeriesId),- );- const synchronizedHoverState = createMemo(() => {- const hoverSync = props.hoverSync;- if (!hoverSync) {- return null;- }- if (props.hoverSourceKey && hoverSync.sourceKey === props.hoverSourceKey) {- return null;- }- return buildInteractiveSparklineSynchronizedHoverState({- chartData: chartData(),- hoverSync,- vbW,- });- });- const synchronizedHoverTimestamp = createMemo<number | null>(() => {- const hoverSync = props.hoverSync;- if (!hoverSync) {- return null;- }- if (props.hoverSourceKey && hoverSync.sourceKey === props.hoverSourceKey) {- return null;- }- return hoverSync.timestamp;- });- const activeHoverState = createMemo<InteractiveSparklineHoverState | null>(() => {- return hoveredState() ?? synchronizedHoverState();- });- const activeHoverTimestamp = createMemo<number | null>(() => {- return hoveredState()?.timestamp ?? synchronizedHoverTimestamp();- });- const activeHoverCursorX = createMemo<number | null>(() => {- const localHover = hoveredState();- if (localHover) {- return localHover.x;- }- return getInteractiveSparklineCursorXForTimestamp({- chartData: chartData(),- timestamp: synchronizedHoverTimestamp(),- vbW,- });- });- const activeEmphasisSeriesIndex = createMemo(() =>- getInteractiveSparklineActiveEmphasisSeriesIndex({- highlightNearestSeriesOnHover: props.highlightNearestSeriesOnHover === true,- lockedSeriesIndex: lockedSeriesIndex(),- hoveredState: activeHoverState(),- externalSeriesIndex: externalSeriesIndex(),- }),- );- const shouldIsolateActiveSeries = createMemo(- () => activeSeriesDisplay() === 'isolate' && activeEmphasisSeriesIndex() !== null,- );- const shouldRenderSeries = (seriesIndex: number) => {- const active = activeEmphasisSeriesIndex();- if (active === null) {- return true;- }- if (shouldIsolateActiveSeries()) {- return active === seriesIndex;- }- return true;- };- const renderedSeriesCount = createMemo(() => {- const active = activeEmphasisSeriesIndex();- if (active === null) {- return chartData().validSeries.length;- }- if (shouldIsolateActiveSeries()) {- return 1;- }- return chartData().validSeries.length;- });- const lineWidthForSeries = (seriesIndex: number) => {- const active = activeEmphasisSeriesIndex();- const isLg = props.size === 'lg';- if (active === null) {- return isLg ? 2 : 1.5;- }- if (active === seriesIndex) {- return isLg ? 4 : 3.2;- }- if (shouldIsolateActiveSeries()) {- return 0;- }- return isLg ? 0.7 : 0.6;- };- const opacityForSeries = (seriesIndex: number) => {- const active = activeEmphasisSeriesIndex();- if (active === null) {- return 0.75 * interactionOpacityMultiplier();- }- if (active === seriesIndex) {- return interactionOpacityMultiplier();- }- if (shouldIsolateActiveSeries()) {- return 0;- }- return 0.05 * interactionOpacityMultiplier();- };-- const drawCanvas = () => {- const canvas = refs.getCanvas();- if (!canvas) return;- const computed = chartData();- const ctx = canvas.getContext('2d');- if (!ctx) return;-- const rect = canvas.getBoundingClientRect();- const width = rect.width;- const height = rect.height;- if (width <= 0 || height <= 0) return;-- setupCanvasDPR(canvas, ctx, width, height);-- const isDark =- typeof document !== 'undefined' && document.documentElement.classList.contains('dark');- const gridColor = isDark ? 'rgba(255, 255, 255, 0.06)' : 'rgba(17, 24, 39, 0.06)';- const gridColorStrong = isDark ? 'rgba(255, 255, 255, 0.10)' : 'rgba(17, 24, 39, 0.10)';- const hoverLineColor = isDark ? 'rgba(255, 255, 255, 0.45)' : 'rgba(17, 24, 39, 0.45)';- const inactiveSeriesColor = isDark ? 'rgb(148, 163, 184)' : 'rgb(100, 116, 139)';-- const yLines = yMode() === 'percent' ? [0.2, 0.4, 0.6, 0.8] : [0.25, 0.5, 0.75];- ctx.save();- ctx.clearRect(0, 0, width, height);- ctx.lineWidth = 0.5;- for (let index = 0; index < yLines.length; index++) {- const y = yLines[index] * height;- ctx.strokeStyle = index === 1 ? gridColorStrong : gridColor;- ctx.beginPath();- ctx.moveTo(0, y);- ctx.lineTo(width, y);- ctx.stroke();- }- ctx.strokeStyle = isDark ? 'rgba(255, 255, 255, 0.04)' : 'rgba(17, 24, 39, 0.04)';- ctx.beginPath();- ctx.moveTo(width * 0.5, 0);- ctx.lineTo(width * 0.5, height);- ctx.stroke();- ctx.restore();-- if (computed.validSeries.length === 0 || computed.rangeMs <= 0) {- return;- }-- const active = activeEmphasisSeriesIndex();- const valueToY = createInteractiveSparklineValueToY(yMode(), computed.scaleMax, height);-- for (let seriesIndex = 0; seriesIndex < computed.validSeries.length; seriesIndex++) {- if (!shouldRenderSeries(seriesIndex)) {- continue;- }- const series = computed.validSeries[seriesIndex];- const lineWidth = lineWidthForSeries(seriesIndex);- const opacity = opacityForSeries(seriesIndex);-- ctx.save();- ctx.globalAlpha = opacity;- ctx.strokeStyle =- active !== null && active !== seriesIndex ? inactiveSeriesColor : series.color;- ctx.lineWidth = lineWidth;- ctx.lineCap = 'round';- ctx.lineJoin = 'round';-- for (const segment of series.segments) {- if (segment.length === 0) continue;-- if (computed.validSeries.length === 1) {- ctx.beginPath();- for (let index = 0; index < segment.length; index++) {- const point = segment[index];- const x = clampInteractiveSparklineValue(- ((point.timestamp - computed.windowStart) / computed.rangeMs) * width,- 0,- width,- );- const y = valueToY(point.value);- if (index === 0) ctx.moveTo(x, y);- else ctx.lineTo(x, y);- }- const lastPoint = segment[segment.length - 1];- const firstPoint = segment[0];- const lastX = clampInteractiveSparklineValue(- ((lastPoint.timestamp - computed.windowStart) / computed.rangeMs) * width,- 0,- width,- );- const firstX = clampInteractiveSparklineValue(- ((firstPoint.timestamp - computed.windowStart) / computed.rangeMs) * width,- 0,- width,- );-- ctx.lineTo(lastX, height);- ctx.lineTo(firstX, height);- ctx.closePath();-- const areaGradient = ctx.createLinearGradient(0, 0, 0, height);- if (- series.color.startsWith('#') &&- (series.color.length === 7 || series.color.length === 4)- ) {- areaGradient.addColorStop(0, `${series.color}40`);- areaGradient.addColorStop(1, `${series.color}00`);- } else {- areaGradient.addColorStop(0, 'rgba(255, 255, 255, 0.15)');- areaGradient.addColorStop(1, 'rgba(255, 255, 255, 0)');- }- ctx.fillStyle = areaGradient;- ctx.fill();- }-- ctx.beginPath();- for (let index = 0; index < segment.length; index++) {- const point = segment[index];- const x = clampInteractiveSparklineValue(- ((point.timestamp - computed.windowStart) / computed.rangeMs) * width,- 0,- width,- );- const y = valueToY(point.value);- if (index === 0) ctx.moveTo(x, y);- else ctx.lineTo(x, y);- }- ctx.stroke();- }- ctx.restore();- }-- const cursorX = activeHoverCursorX();- if (cursorX === null) return;- ctx.save();- const x = (cursorX / vbW) * width;- const lineStartY = 0;- const hoverLineGradient = ctx.createLinearGradient(0, lineStartY, 0, height);- hoverLineGradient.addColorStop(0, 'transparent');- hoverLineGradient.addColorStop(0.1, hoverLineColor);- hoverLineGradient.addColorStop(1, hoverLineColor);- ctx.strokeStyle = hoverLineGradient;- ctx.lineWidth = 1;- ctx.setLineDash([3, 3]);- ctx.beginPath();- ctx.moveTo(x, lineStartY);- ctx.lineTo(x, height);- ctx.stroke();- ctx.restore();- };-- const queueCanvasDraw = () => {- if (!shouldUseCanvas()) return;- if (unregisterCanvasDraw) {- unregisterCanvasDraw();- }- unregisterCanvasDraw = scheduleSparkline(drawCanvas);- };-- createEffect(() => {- if (!shouldUseCanvas()) {- if (unregisterCanvasDraw) {- unregisterCanvasDraw();- unregisterCanvasDraw = null;- }- return;- }-- void chartData();- void activeEmphasisSeriesIndex();- void activeHoverState();- void activeHoverCursorX();- queueCanvasDraw();- });-- createEffect(() => {- const canvasHost = refs.getCanvasHost();- if (!shouldUseCanvas() || !canvasHost) return;- const observer = new ResizeObserver(() => queueCanvasDraw());- observer.observe(canvasHost);- onCleanup(() => observer.disconnect());- });-- onCleanup(() => {- pendingHoverPosition = null;- if (typeof window !== 'undefined' && hoverRafId !== null) {- window.cancelAnimationFrame(hoverRafId);- hoverRafId = null;- }- if (unregisterCanvasDraw) {- unregisterCanvasDraw();- unregisterCanvasDraw = null;- }- });-- return {- activeEmphasisSeriesIndex,- activeHoverState,- activeHoverCursorX,- activeHoverTimestamp,- activeSeriesDisplay,- axisTicks,- chartData,- externalSeriesIndex,- formatValue,- gridLineX,- gridLineY,- handleClick,- handleMouseLeave,- handleMouseMove,- hoveredState,- lineWidthForSeries,- opacityForSeries,- renderedSeriesCount,- shouldUseCanvas,- shouldRenderSeries,- vbH,- vbW,- xAxisBandPx,- xAxisTicks,- };-}--export type InteractiveSparklineState = ReturnType<typeof useInteractiveSparklineState>;