mirror of
https://github.com/rcourtman/Pulse.git
synced 2026-12-02 10:09:02 +01:00
Add Grafana-style legend series isolation to history charts (#5397)
Adds interactive legend series isolation and comparison to Pulse's shared multi-series drawer history charts (`GuestDrawerHistory`). ### Changes - **Click-to-isolate**: Clicking a legend item (such as CPU, Memory, or Out) isolates that series, hides sibling traces, spread bands, peak callouts, hover dots, alert threshold lines, and deferred freshness prose, and restores all series when clicked again or via **Show all**. - **Multi-series comparison**: Ctrl/Cmd/Shift+click toggles individual series on or off, and filtered 3+ series panels also provide a tap-accessible **Compare** toggle so touch-only users can compare two of three series (for example CPU and Memory without Disk) without modifier keys. - **Y-axis scaling**: Keeps `%` utilization panels fixed at `0-100%` for consistent capacity reading while auto-scaled rate and temperature panels (`Network I/O`, `Disk I/O`, `°C`) rescale to the visible series. - **Accessibility and state persistence**: Keys legend buttons by stable metric IDs so keyboard activation keeps focus, removes opacity dimming so hidden labels keep high contrast (`7.58:1` in light mode), enforces 24px minimum hit targets, resolves mixed-source readout labels from visible series, preserves isolation across range switches and transient read errors on the same resource, and resets when switching resources. - **Tests**: Added `GuestDrawerHistory.series-isolation.test.tsx` (15 unit tests covering isolation, multi-toggle, Compare mode, I/O and Celsius rescaling, single-series panels, gap preservation, empty-series honesty, keyboard focus retention, mixed sources, deferred notes, failed range recovery, and target resets). ### Verification - Vitest (all 12 `GuestDrawerHistory` suites on `pulse-dev`): 192/192 passed - `npx tsc --noEmit`: 0 errors - `npm run build`: passed - Playwright Chromium verification against the production build across desktop dark/light (`1280x800`) and mobile (`390x844`) viewports with browser verification receipt recorded.
This commit is contained in:
45
frontend-modern/browser-verification/d570c842b6d0c094.json
Normal file
45
frontend-modern/browser-verification/d570c842b6d0c094.json
Normal file
@@ -0,0 +1,45 @@
|
||||
{
|
||||
"version": 1,
|
||||
"base_sha": "027d63bf16bbcdc6812aefc43d916390464b04b8",
|
||||
"verified_at": "2026-11-28T18:14:50Z",
|
||||
"result": "passed",
|
||||
"changed_paths": [
|
||||
"frontend-modern/src/components/Workloads/GuestDrawerHistory.tsx",
|
||||
"frontend-modern/src/components/Workloads/guestDrawerModel.ts"
|
||||
],
|
||||
"content_sha256": {
|
||||
"frontend-modern/src/components/Workloads/GuestDrawerHistory.tsx": "3a58ee186a0e67d3824efc272d33fdcda309d64ff0e316084f338cb36682d1f7",
|
||||
"frontend-modern/src/components/Workloads/guestDrawerModel.ts": "a28348c5faabd6f1721e7d96e3ba6acd6a1d5e7451fe5d8e94fbb92047078428"
|
||||
},
|
||||
"routes": [
|
||||
"/proxmox"
|
||||
],
|
||||
"viewports": [
|
||||
{
|
||||
"width": 1280,
|
||||
"height": 800
|
||||
},
|
||||
{
|
||||
"width": 390,
|
||||
"height": 844
|
||||
}
|
||||
],
|
||||
"states": [
|
||||
"Desktop dark default multi-series Utilization, Network I/O, and Disk I/O charts alongside drag-to-zoom controls",
|
||||
"Desktop dark isolated CPU with 0-100% axis, active CPU warning threshold, hidden Memory critical threshold, and hover peak callout",
|
||||
"Desktop dark multi-selected CPU and Memory alongside isolated Network I/O Out rescaled from 115M/s to 1.4M/s",
|
||||
"Desktop light multi-selected Utilization and rescaled Network I/O with 7.58:1 hidden legend text contrast",
|
||||
"Mobile 390px isolated CPU with Compare and Show all controls (24px min height, 35px min center distance, zero horizontal overflow)",
|
||||
"Mobile 390px tap-only Compare mode with CPU and Memory visible and Disk hidden"
|
||||
],
|
||||
"interactions": [
|
||||
"Click legend item to isolate a single series and hide sibling traces, bands, alert lines, hover markers, and deferred freshness warnings",
|
||||
"Hover plot while isolated to verify single-series crosshair, marker, and peak label",
|
||||
"Ctrl/Cmd/Shift+click legend item to compare multiple series without hiding the last visible series",
|
||||
"Click isolated Network I/O Out series to rescale auto-scaled Y-axis and click again to restore full scale",
|
||||
"Activate Memory legend button via keyboard Space to verify stable DOM node focus retention across isolate and restore",
|
||||
"Activate Show all via keyboard Enter to restore all series and return focus to the first legend button",
|
||||
"Switch time range from 24h to 7d to confirm isolation persists on the same resource and switch to another guest to confirm reset",
|
||||
"Tap Compare then Memory on 390px mobile viewport without modifier keys to compare CPU and Memory with Disk hidden"
|
||||
]
|
||||
}
|
||||
@@ -34,11 +34,13 @@ import {
|
||||
GUEST_DRAWER_HISTORY_GROUPS,
|
||||
buildGuestDrawerHistoryBandPath,
|
||||
buildGuestDrawerHistoryPath,
|
||||
getEffectiveHiddenHistoryMetrics,
|
||||
getGuestDrawerHistoryRangeBounds,
|
||||
getGuestDrawerHistoryScale,
|
||||
getGuestDrawerHistorySegments,
|
||||
getGuestDrawerHistoryValueLabel,
|
||||
normalizeGuestDrawerHistoryPoints,
|
||||
toggleGuestDrawerHistorySeriesVisibility,
|
||||
type GuestDrawerHistoryGroupConfig,
|
||||
type GuestDrawerHistoryDeferredMetric,
|
||||
type GuestDrawerHistoryTarget,
|
||||
@@ -91,15 +93,20 @@ interface GuestDrawerHistoryGroupChartProps {
|
||||
currentMetrics?: Record<string, number | null | undefined>;
|
||||
deferredMetrics?: Record<string, GuestDrawerHistoryDeferredMetric | undefined>;
|
||||
group: GuestDrawerHistoryGroupConfig;
|
||||
hiddenMetrics: ReadonlySet<string>;
|
||||
loading: boolean;
|
||||
metrics: Record<string, AggregatedMetricPoint[] | undefined>;
|
||||
/** Per-metric origin when a reply mixes store, memory, and native readings. */
|
||||
metricSources?: Record<string, HistoryReadoutSource>;
|
||||
onBrushPreviewChange: (preview: HistoryBrushPreview | null) => void;
|
||||
onCommitZoom: (window: GuestDrawerHistoryTimeBounds) => void;
|
||||
onHiddenMetricsChange: (next: ReadonlySet<string>) => void;
|
||||
onResetZoom: () => void;
|
||||
range: HistoryTimeRange;
|
||||
/** Where the reply's readings came from; names the readout's time. */
|
||||
source?: HistoryReadoutSource;
|
||||
sourceKey: string;
|
||||
targetKey: string;
|
||||
timeBounds: GuestDrawerHistoryTimeBounds | null;
|
||||
touchInspection: boolean;
|
||||
}
|
||||
@@ -197,11 +204,18 @@ const getAxisLabel = (
|
||||
return `${Math.round(value)}`;
|
||||
};
|
||||
|
||||
const alertToneClass = (severity: GuestDrawerHistoryAlert['severity'] | undefined) =>
|
||||
const alertToneClass = (
|
||||
severity: GuestDrawerHistoryAlert['severity'] | undefined,
|
||||
muted = false,
|
||||
) =>
|
||||
severity === 'critical'
|
||||
? 'font-semibold text-red-700 dark:text-red-300'
|
||||
? muted
|
||||
? 'font-semibold text-muted'
|
||||
: 'font-semibold text-red-700 dark:text-red-300'
|
||||
: severity === 'warning'
|
||||
? 'font-semibold text-amber-700 dark:text-amber-300'
|
||||
? muted
|
||||
? 'font-semibold text-muted'
|
||||
: 'font-semibold text-amber-700 dark:text-amber-300'
|
||||
: '';
|
||||
|
||||
const clampNumber = (value: number, min: number, max: number): number =>
|
||||
@@ -421,10 +435,57 @@ const GuestDrawerLiveReadings: Component<GuestDrawerLiveReadingsProps> = (props)
|
||||
);
|
||||
};
|
||||
|
||||
const resolveHistoryReadoutSource = (
|
||||
metrics: readonly string[],
|
||||
fallbackSource: HistoryReadoutSource | undefined,
|
||||
metricSources: Record<string, HistoryReadoutSource> | undefined,
|
||||
): HistoryReadoutSource | undefined => {
|
||||
if (!metricSources) return fallbackSource;
|
||||
const origins = new Set(metrics.map((metric) => metricSources[metric]).filter(Boolean));
|
||||
if (origins.size === 0) return fallbackSource ?? 'mixed';
|
||||
// The time readout belongs to the plotted series. Don't call it stored if
|
||||
// the visible series disagree on origin.
|
||||
return origins.size === 1 ? origins.values().next().value : 'mixed';
|
||||
};
|
||||
|
||||
const formatSeriesLabelList = (labels: readonly string[]): string => {
|
||||
if (labels.length <= 1) return labels[0] ?? '';
|
||||
if (labels.length === 2) return `${labels[0]} and ${labels[1]}`;
|
||||
return `${labels.slice(0, -1).join(', ')}, and ${labels[labels.length - 1]}`;
|
||||
};
|
||||
|
||||
const EMPTY_HIDDEN_METRICS: ReadonlySet<string> = new Set();
|
||||
|
||||
const getLegendSeriesTitle = (
|
||||
label: string,
|
||||
visible: boolean,
|
||||
isolated: boolean,
|
||||
filtered: boolean,
|
||||
compareMode: boolean,
|
||||
): string => {
|
||||
if (compareMode) {
|
||||
if (!visible) return `${label} hidden. Click to add ${label}.`;
|
||||
return isolated ? 'Click to show all series.' : `Click to hide ${label}.`;
|
||||
}
|
||||
if (!visible) {
|
||||
return `${label} hidden. Click to show only ${label}, or Ctrl/Cmd+click to add.`;
|
||||
}
|
||||
if (isolated) {
|
||||
return `Showing only ${label}. Click to show all series, or Ctrl/Cmd+click another to compare.`;
|
||||
}
|
||||
if (filtered) {
|
||||
return `Click to show only ${label}, or Ctrl/Cmd+click to hide.`;
|
||||
}
|
||||
return `Click to show only ${label}, or Ctrl/Cmd+click to toggle.`;
|
||||
};
|
||||
|
||||
const GuestDrawerHistoryGroupChart: Component<GuestDrawerHistoryGroupChartProps> = (props) => {
|
||||
const [hoverTimestamp, setHoverTimestamp] = createSignal<number | null>(null);
|
||||
const [selectedTimestamp, setSelectedTimestamp] = createSignal<number | null>(null);
|
||||
const [compareMode, setCompareMode] = createSignal(false);
|
||||
const [seriesAnnouncement, setSeriesAnnouncement] = createSignal('');
|
||||
const inspectionId = `history-inspection-${createUniqueId()}`;
|
||||
let firstLegendButtonRef: HTMLButtonElement | undefined;
|
||||
createEffect(
|
||||
on(
|
||||
() => props.touchInspection,
|
||||
@@ -446,19 +507,96 @@ const GuestDrawerHistoryGroupChart: Component<GuestDrawerHistoryGroupChartProps>
|
||||
},
|
||||
),
|
||||
);
|
||||
createEffect(
|
||||
on(
|
||||
() => props.targetKey,
|
||||
() => {
|
||||
setCompareMode(false);
|
||||
setSeriesAnnouncement('');
|
||||
},
|
||||
),
|
||||
);
|
||||
const series = createMemo(() =>
|
||||
props.group.series.map((config) => ({
|
||||
...config,
|
||||
points: normalizeGuestDrawerHistoryPoints(props.metrics[config.metric], config.unit),
|
||||
})),
|
||||
);
|
||||
// Step through actual stored times, not synthetic points between samples.
|
||||
// Keep the selected time across polls even if its ordinal index changes.
|
||||
const observationTimes = createMemo(() =>
|
||||
const allMetrics = createMemo(() => props.group.series.map((config) => config.metric));
|
||||
const isInteractiveLegend = createMemo(() => props.group.series.length > 1);
|
||||
const supportsCompareMode = createMemo(() => props.group.series.length > 2);
|
||||
const effectiveHiddenMetrics = createMemo(() =>
|
||||
getEffectiveHiddenHistoryMetrics(allMetrics(), props.hiddenMetrics),
|
||||
);
|
||||
const isSeriesFiltered = createMemo(() => effectiveHiddenMetrics().size > 0);
|
||||
const isCompareActive = createMemo(
|
||||
() => supportsCompareMode() && isSeriesFiltered() && compareMode(),
|
||||
);
|
||||
const visibleSeries = createMemo(() => {
|
||||
const hidden = effectiveHiddenMetrics();
|
||||
return hidden.size === 0 ? series() : series().filter((item) => !hidden.has(item.metric));
|
||||
});
|
||||
const effectiveSource = createMemo(() =>
|
||||
resolveHistoryReadoutSource(
|
||||
visibleSeries().map((item) => item.metric),
|
||||
props.source,
|
||||
props.metricSources,
|
||||
),
|
||||
);
|
||||
const visibleSeriesLabels = createMemo(() =>
|
||||
formatSeriesLabelList(visibleSeries().map((item) => item.label)),
|
||||
);
|
||||
const handleSeriesToggle = (metric: string, event: MouseEvent) => {
|
||||
const multiSelect = isCompareActive() || event.ctrlKey || event.metaKey || event.shiftKey;
|
||||
const nextHidden = toggleGuestDrawerHistorySeriesVisibility(
|
||||
allMetrics(),
|
||||
effectiveHiddenMetrics(),
|
||||
metric,
|
||||
multiSelect,
|
||||
);
|
||||
props.onHiddenMetricsChange(nextHidden);
|
||||
if (nextHidden.size === 0) {
|
||||
setCompareMode(false);
|
||||
setSeriesAnnouncement(`${props.group.label}: showing all series.`);
|
||||
} else {
|
||||
const nextLabels = props.group.series
|
||||
.filter((config) => !nextHidden.has(config.metric))
|
||||
.map((config) => config.label);
|
||||
setSeriesAnnouncement(
|
||||
`${props.group.label}: showing ${formatSeriesLabelList(nextLabels)} only.`,
|
||||
);
|
||||
}
|
||||
};
|
||||
const handleToggleCompareMode = () => {
|
||||
const next = !isCompareActive();
|
||||
setCompareMode(next);
|
||||
setSeriesAnnouncement(
|
||||
next
|
||||
? `${props.group.label}: compare mode on. Select series to add or remove.`
|
||||
: `${props.group.label}: compare mode off.`,
|
||||
);
|
||||
};
|
||||
const handleShowAllSeries = () => {
|
||||
setCompareMode(false);
|
||||
props.onHiddenMetricsChange(EMPTY_HIDDEN_METRICS);
|
||||
setSeriesAnnouncement(`${props.group.label}: showing all series.`);
|
||||
firstLegendButtonRef?.focus();
|
||||
};
|
||||
// Full-panel observation times preserve gap detection and width reserves
|
||||
// even while individual series are hidden.
|
||||
const panelObservationTimes = createMemo(() =>
|
||||
[...new Set(series().flatMap((item) => item.points.map((point) => point.timestamp)))].sort(
|
||||
(a, b) => a - b,
|
||||
),
|
||||
);
|
||||
// Step through actual stored times for the visible series, not synthetic
|
||||
// points between samples. Keep the selected time across polls even if its
|
||||
// ordinal index changes.
|
||||
const observationTimes = createMemo(() =>
|
||||
[
|
||||
...new Set(visibleSeries().flatMap((item) => item.points.map((point) => point.timestamp))),
|
||||
].sort((a, b) => a - b),
|
||||
);
|
||||
const selectedIndex = createMemo(() => {
|
||||
const times = observationTimes();
|
||||
const selected = selectedTimestamp();
|
||||
@@ -469,7 +607,7 @@ const GuestDrawerHistoryGroupChart: Component<GuestDrawerHistoryGroupChartProps>
|
||||
const inspectionTimestamp = createMemo(() =>
|
||||
selectedTimestamp() === null ? null : (observationTimes()[selectedIndex()] ?? null),
|
||||
);
|
||||
// Resolve the pointer to one real time across the whole group. Independent
|
||||
// Resolve the pointer to one real time across the visible series. Independent
|
||||
// nearest-series reads would attribute values from different times to the
|
||||
// first metric's timestamp, and can even borrow a live fallback reading.
|
||||
const activeTimestamp = createMemo(() => {
|
||||
@@ -484,9 +622,16 @@ const GuestDrawerHistoryGroupChart: Component<GuestDrawerHistoryGroupChartProps>
|
||||
// values would combine different times (or a live fallback) into a tuple
|
||||
// which never existed, disagreeing with the chart's accessible description.
|
||||
const readoutTimestamp = createMemo(() => activeTimestamp() ?? observationTimes().at(-1) ?? null);
|
||||
const bounds = () => props.timeBounds;
|
||||
const hasStoredData = createMemo(() => panelObservationTimes().length > 0 && bounds() !== null);
|
||||
const hasVisibleStoredData = createMemo(() => observationTimes().length > 0 && bounds() !== null);
|
||||
const observationValueText = (timestamp: number | undefined): string => {
|
||||
if (timestamp === undefined) return 'No stored history observations.';
|
||||
const values = series().map((item) => {
|
||||
if (timestamp === undefined) {
|
||||
return isSeriesFiltered() && hasStoredData()
|
||||
? `No stored history observations for ${visibleSeriesLabels()}.`
|
||||
: 'No stored history observations.';
|
||||
}
|
||||
const values = visibleSeries().map((item) => {
|
||||
const point = item.points.find((point) => point.timestamp === timestamp);
|
||||
if (!point) return `${item.label} no observation`;
|
||||
const value = formatHistoryChartTooltipValue(point.value, item.unit);
|
||||
@@ -503,22 +648,23 @@ const GuestDrawerHistoryGroupChart: Component<GuestDrawerHistoryGroupChartProps>
|
||||
);
|
||||
const chartDescription = createMemo(() => {
|
||||
if (props.loading) return 'Loading history.';
|
||||
const scopePrefix = isSeriesFiltered() ? `Showing ${visibleSeriesLabels()} only. ` : '';
|
||||
const timestamp = activeTimestamp();
|
||||
if (timestamp !== null) return observationValueText(timestamp);
|
||||
if (timestamp !== null) return `${scopePrefix}${observationValueText(timestamp)}`;
|
||||
const count = observationTimes().length;
|
||||
if (count === 0) return inspectionValueText();
|
||||
if (count === 0) return `${scopePrefix}${inspectionValueText()}`;
|
||||
const origin =
|
||||
props.source === 'native'
|
||||
effectiveSource() === 'native'
|
||||
? 'device'
|
||||
: props.source === 'mixed' || props.source === 'memory'
|
||||
: effectiveSource() === 'mixed' || effectiveSource() === 'memory'
|
||||
? 'recorded'
|
||||
: 'stored';
|
||||
return `${count} ${origin} observation ${count === 1 ? 'time' : 'times'}. ${inspectionValueText()}`;
|
||||
return `${scopePrefix}${count} ${origin} observation ${count === 1 ? 'time' : 'times'}. ${inspectionValueText()}`;
|
||||
});
|
||||
const segmentedSeries = createMemo(() =>
|
||||
series().map((item) => ({
|
||||
visibleSeries().map((item) => ({
|
||||
...item,
|
||||
segments: getGuestDrawerHistorySegments(item.points, observationTimes()),
|
||||
segments: getGuestDrawerHistorySegments(item.points, panelObservationTimes()),
|
||||
})),
|
||||
);
|
||||
const gapMessage = createMemo(() => {
|
||||
@@ -543,15 +689,22 @@ const GuestDrawerHistoryGroupChart: Component<GuestDrawerHistoryGroupChartProps>
|
||||
observationTimes().length === 1 ? { timestamp: observationTimes()[0] } : null,
|
||||
);
|
||||
const thresholds = createMemo(() =>
|
||||
series().flatMap((item) => {
|
||||
visibleSeries().flatMap((item) => {
|
||||
const alert = props.alerts?.[item.metric];
|
||||
return alert && typeof alert.value === 'number' && Number.isFinite(alert.value)
|
||||
? [{ metric: item.metric, label: item.label, severity: alert.severity, value: alert.value }]
|
||||
? [
|
||||
{
|
||||
metric: item.metric,
|
||||
label: item.label,
|
||||
severity: alert.severity,
|
||||
value: alert.value,
|
||||
},
|
||||
]
|
||||
: [];
|
||||
}),
|
||||
);
|
||||
const alertDescription = createMemo(() =>
|
||||
series()
|
||||
visibleSeries()
|
||||
.flatMap((item) => {
|
||||
const alert = props.alerts?.[item.metric];
|
||||
if (!alert) return [];
|
||||
@@ -568,7 +721,7 @@ const GuestDrawerHistoryGroupChart: Component<GuestDrawerHistoryGroupChartProps>
|
||||
const scale = createMemo(() =>
|
||||
getGuestDrawerHistoryScale(
|
||||
[
|
||||
...series(),
|
||||
...visibleSeries(),
|
||||
...(observationTimes().length > 0
|
||||
? thresholds().map((threshold) => ({
|
||||
points: [
|
||||
@@ -591,14 +744,12 @@ const GuestDrawerHistoryGroupChart: Component<GuestDrawerHistoryGroupChartProps>
|
||||
[0, 0.5, 1].map((tick) => getAxisLabel(props.group.unit, tick, scale())),
|
||||
),
|
||||
);
|
||||
const bounds = () => props.timeBounds;
|
||||
const hasStoredData = createMemo(() => observationTimes().length > 0 && bounds() !== null);
|
||||
const hoveredSeries = createMemo(() => {
|
||||
const timestamp = activeTimestamp();
|
||||
const rangeBounds = bounds();
|
||||
if (timestamp === null || !rangeBounds) return [];
|
||||
|
||||
return series()
|
||||
return visibleSeries()
|
||||
.map((item) => {
|
||||
const point = item.points.find((point) => point.timestamp === timestamp);
|
||||
if (!point) return null;
|
||||
@@ -666,7 +817,7 @@ const GuestDrawerHistoryGroupChart: Component<GuestDrawerHistoryGroupChartProps>
|
||||
return [
|
||||
item.metric,
|
||||
getReservedTextShapes(
|
||||
observationTimes().map((timestamp) => labels.get(timestamp) ?? 'no reading'),
|
||||
panelObservationTimes().map((timestamp) => labels.get(timestamp) ?? 'no reading'),
|
||||
),
|
||||
] as const;
|
||||
}),
|
||||
@@ -694,20 +845,32 @@ const GuestDrawerHistoryGroupChart: Component<GuestDrawerHistoryGroupChartProps>
|
||||
}
|
||||
return formatHistoryChartTimeLabel(timestamp, props.range);
|
||||
};
|
||||
const timeReserve = createMemo(() =>
|
||||
getReservedTextShapes(
|
||||
observationTimes().flatMap((timestamp) => {
|
||||
const timeReserve = createMemo(() => {
|
||||
const possibleSources = new Set<HistoryReadoutSource | undefined>([
|
||||
effectiveSource(),
|
||||
resolveHistoryReadoutSource(allMetrics(), props.source, props.metricSources),
|
||||
...allMetrics().map((metric) =>
|
||||
resolveHistoryReadoutSource([metric], props.source, props.metricSources),
|
||||
),
|
||||
]);
|
||||
return getReservedTextShapes(
|
||||
panelObservationTimes().flatMap((timestamp) => {
|
||||
const time = formatObservationTime(timestamp);
|
||||
return [false, true].map(
|
||||
(inspected) => `${getHistoryReadoutLabel(props.source, inspected)} · ${time}`,
|
||||
return [...possibleSources].flatMap((source) =>
|
||||
[false, true].map(
|
||||
(inspected) => `${getHistoryReadoutLabel(source, inspected)} · ${time}`,
|
||||
),
|
||||
);
|
||||
}),
|
||||
),
|
||||
);
|
||||
);
|
||||
});
|
||||
const effectiveCurrentMetrics = () => (props.isZoomed ? undefined : props.currentMetrics);
|
||||
const effectiveDeferredMetrics = () => (props.isZoomed ? undefined : props.deferredMetrics);
|
||||
const displaySeries = createMemo(() =>
|
||||
series().map((item, index) => {
|
||||
const displaySeries = createMemo(() => {
|
||||
const hidden = effectiveHiddenMetrics();
|
||||
const visibleCount = visibleSeries().length;
|
||||
const panelHasStored = hasStoredData();
|
||||
return series().map((item, index) => {
|
||||
const timestamp = readoutTimestamp();
|
||||
const point = item.points.find((point) => point.timestamp === timestamp);
|
||||
const reading = getLiveReading(
|
||||
@@ -715,10 +878,14 @@ const GuestDrawerHistoryGroupChart: Component<GuestDrawerHistoryGroupChartProps>
|
||||
effectiveCurrentMetrics(),
|
||||
effectiveDeferredMetrics(),
|
||||
);
|
||||
const isFallback = !props.isZoomed && timestamp === null && reading.value !== undefined;
|
||||
const isFallback =
|
||||
!props.isZoomed && timestamp === null && !panelHasStored && reading.value !== undefined;
|
||||
const alert = props.alerts?.[item.metric];
|
||||
const visible = !hidden.has(item.metric);
|
||||
return {
|
||||
...item,
|
||||
visible,
|
||||
isolated: hidden.size > 0 && visible && visibleCount === 1,
|
||||
// Names the dashed line: its metric's reading carries the trigger.
|
||||
alertLabel:
|
||||
alert && typeof alert.value === 'number' && Number.isFinite(alert.value)
|
||||
@@ -735,13 +902,16 @@ const GuestDrawerHistoryGroupChart: Component<GuestDrawerHistoryGroupChartProps>
|
||||
: // A stored time where this series has no reading says so in place,
|
||||
// rather than through a note that appears and disappears (and moves
|
||||
// the chart) as the inspected time changes.
|
||||
timestamp !== null
|
||||
timestamp !== null || panelHasStored
|
||||
? 'no reading'
|
||||
: reading.value !== undefined
|
||||
? formatHistoryChartTooltipValue(reading.value, item.unit)
|
||||
: '-',
|
||||
};
|
||||
}),
|
||||
});
|
||||
});
|
||||
const displaySeriesByMetric = createMemo(
|
||||
() => new Map(displaySeries().map((item) => [item.metric, item])),
|
||||
);
|
||||
const readoutTime = createMemo(() => {
|
||||
const timestamp = readoutTimestamp();
|
||||
@@ -857,7 +1027,7 @@ const GuestDrawerHistoryGroupChart: Component<GuestDrawerHistoryGroupChartProps>
|
||||
event.button !== 0 ||
|
||||
event.isPrimary === false ||
|
||||
props.loading ||
|
||||
!hasStoredData()
|
||||
!hasVisibleStoredData()
|
||||
) {
|
||||
return;
|
||||
}
|
||||
@@ -872,13 +1042,19 @@ const GuestDrawerHistoryGroupChart: Component<GuestDrawerHistoryGroupChartProps>
|
||||
event.preventDefault();
|
||||
cancelDrag();
|
||||
const clampBounds = props.clampWindow
|
||||
? { startTime: props.clampWindow.startTime, endTime: props.clampWindow.endTime }
|
||||
? {
|
||||
startTime: props.clampWindow.startTime,
|
||||
endTime: props.clampWindow.endTime,
|
||||
}
|
||||
: { startTime: rangeBounds.startTime, endTime: rangeBounds.endTime };
|
||||
activeDrag = {
|
||||
pointerId: event.pointerId,
|
||||
startClientX: event.clientX,
|
||||
startSvgX,
|
||||
bounds: { startTime: rangeBounds.startTime, endTime: rangeBounds.endTime },
|
||||
bounds: {
|
||||
startTime: rangeBounds.startTime,
|
||||
endTime: rangeBounds.endTime,
|
||||
},
|
||||
clampBounds,
|
||||
active: false,
|
||||
};
|
||||
@@ -984,8 +1160,8 @@ const GuestDrawerHistoryGroupChart: Component<GuestDrawerHistoryGroupChartProps>
|
||||
data-phone-collapsed={props.hiddenOnPhone ? 'true' : undefined}
|
||||
data-history-group={props.group.id}
|
||||
>
|
||||
<div class="mb-2 flex flex-wrap items-start justify-between gap-x-4 gap-y-1">
|
||||
<div class="flex min-w-0 flex-wrap items-baseline gap-x-2 gap-y-1">
|
||||
<div class="mb-2 flex flex-wrap items-center justify-between gap-x-3 gap-y-1.5">
|
||||
<div class="flex min-h-6 min-w-0 flex-wrap items-center gap-x-2 gap-y-1">
|
||||
<h4 class="text-xs font-semibold uppercase tracking-wide text-muted">
|
||||
{props.group.label}
|
||||
</h4>
|
||||
@@ -1001,72 +1177,178 @@ const GuestDrawerHistoryGroupChart: Component<GuestDrawerHistoryGroupChartProps>
|
||||
data-testid="guest-history-hover-time"
|
||||
dateTime={time().dateTime}
|
||||
title={time().fullLabel}
|
||||
aria-label={`${getHistoryReadoutLabel(props.source, true)} observation: ${time().fullLabel}`}
|
||||
aria-label={`${getHistoryReadoutLabel(effectiveSource(), true)} observation: ${time().fullLabel}`}
|
||||
>
|
||||
{getHistoryReadoutLabel(props.source, activeTimestamp() !== null)}
|
||||
{getHistoryReadoutLabel(effectiveSource(), activeTimestamp() !== null)}
|
||||
{' · '}
|
||||
{time().label}
|
||||
</time>
|
||||
</span>
|
||||
)}
|
||||
</Show>
|
||||
</div>
|
||||
<div class="flex flex-wrap justify-end gap-x-3 gap-y-1 text-xs text-muted">
|
||||
<For each={displaySeries()}>
|
||||
{(item) => (
|
||||
<span
|
||||
class="inline-flex items-center gap-1"
|
||||
data-history-current={item.isCurrent ? item.metric : undefined}
|
||||
data-history-last-known={item.isLastKnown ? item.metric : undefined}
|
||||
data-history-unknown={item.isUnknown ? item.metric : undefined}
|
||||
aria-describedby={item.deferred ? item.descriptionId : undefined}
|
||||
>
|
||||
<svg aria-hidden="true" class="h-2.5 w-2.5 shrink-0" viewBox="0 0 10 10">
|
||||
<circle cx="5" cy="5" r="4" fill={item.color} />
|
||||
</svg>
|
||||
<span class="font-medium text-base-content">{item.label}</span>
|
||||
<span
|
||||
class={`${RESERVED_TEXT_CLASS} ${alertToneClass(props.alerts?.[item.metric]?.severity)}`}
|
||||
data-reserve-a={item.reserve[0]}
|
||||
data-reserve-b={item.reserve[1]}
|
||||
<Show when={isSeriesFiltered()}>
|
||||
<div class="inline-flex flex-wrap items-center gap-1.5">
|
||||
<Show when={supportsCompareMode()}>
|
||||
<button
|
||||
type="button"
|
||||
data-testid="guest-history-compare-toggle"
|
||||
aria-pressed={isCompareActive()}
|
||||
aria-label={`Compare ${props.group.label} series`}
|
||||
title={
|
||||
isCompareActive()
|
||||
? 'Compare mode on. Tap series to add or remove.'
|
||||
: 'Select multiple series by tapping.'
|
||||
}
|
||||
class={`inline-flex min-h-6 cursor-pointer items-center rounded-xs px-1.5 text-[10px] font-medium transition-colors focus-visible:outline-solid focus-visible:outline-2 focus-visible:outline-offset-1 focus-visible:outline-blue-500 ${
|
||||
isCompareActive()
|
||||
? 'bg-surface-hover text-base-content ring-1 ring-inset ring-border'
|
||||
: 'text-muted underline decoration-border underline-offset-2 hover:bg-surface-hover/70 hover:text-base-content'
|
||||
}`}
|
||||
onClick={handleToggleCompareMode}
|
||||
>
|
||||
<span class="[grid-area:1/1]">{item.valueLabel}</span>
|
||||
</span>
|
||||
<Show when={item.alertLabel}>
|
||||
{(label) => (
|
||||
<span
|
||||
data-history-alert-label={item.metric}
|
||||
class={alertToneClass(props.alerts?.[item.metric]?.severity)}
|
||||
Compare
|
||||
</button>
|
||||
</Show>
|
||||
<button
|
||||
type="button"
|
||||
data-testid="guest-history-show-all"
|
||||
aria-label={`Show all ${props.group.label} series`}
|
||||
class="inline-flex min-h-6 cursor-pointer items-center rounded-xs px-1.5 text-[10px] font-medium text-muted underline decoration-border underline-offset-2 transition-colors hover:bg-surface-hover/70 hover:text-base-content focus-visible:outline-solid focus-visible:outline-2 focus-visible:outline-offset-1 focus-visible:outline-blue-500"
|
||||
onClick={handleShowAllSeries}
|
||||
>
|
||||
Show all
|
||||
</button>
|
||||
</div>
|
||||
</Show>
|
||||
</div>
|
||||
<div class="flex flex-wrap justify-end gap-x-1.5 gap-y-1.5 text-xs text-muted">
|
||||
<For each={allMetrics()}>
|
||||
{(metric, index) => {
|
||||
const item = () => displaySeriesByMetric().get(metric)!;
|
||||
const renderContent = () => (
|
||||
<>
|
||||
<svg aria-hidden="true" class="h-2.5 w-2.5 shrink-0" viewBox="0 0 10 10">
|
||||
<Show
|
||||
when={item().visible}
|
||||
fallback={
|
||||
<circle
|
||||
cx="5"
|
||||
cy="5"
|
||||
r="3.25"
|
||||
fill="none"
|
||||
stroke={item().color}
|
||||
stroke-width="1.75"
|
||||
/>
|
||||
}
|
||||
>
|
||||
{label()}
|
||||
<circle cx="5" cy="5" r="4" fill={item().color} />
|
||||
</Show>
|
||||
</svg>
|
||||
<span
|
||||
class={`font-medium ${item().visible ? 'text-base-content' : 'text-muted'}`}
|
||||
>
|
||||
{item().label}
|
||||
</span>
|
||||
<span
|
||||
class={`${RESERVED_TEXT_CLASS} ${alertToneClass(props.alerts?.[metric]?.severity, !item().visible)}`}
|
||||
data-reserve-a={item().reserve[0]}
|
||||
data-reserve-b={item().reserve[1]}
|
||||
>
|
||||
<span class="[grid-area:1/1]">{item().valueLabel}</span>
|
||||
</span>
|
||||
<Show when={item().alertLabel}>
|
||||
{(label) => (
|
||||
<span
|
||||
data-history-alert-label={metric}
|
||||
class={alertToneClass(props.alerts?.[metric]?.severity, !item().visible)}
|
||||
>
|
||||
{label()}
|
||||
</span>
|
||||
)}
|
||||
</Show>
|
||||
<Show when={item().isCurrent}>
|
||||
<span>current</span>
|
||||
</Show>
|
||||
<Show when={item().isUnknown}>
|
||||
<span>freshness unknown</span>
|
||||
</Show>
|
||||
<Show when={item().isLastKnown}>
|
||||
<span>last known</span>
|
||||
</Show>
|
||||
</>
|
||||
);
|
||||
|
||||
return (
|
||||
<Show
|
||||
when={isInteractiveLegend()}
|
||||
fallback={
|
||||
<span
|
||||
class="inline-flex min-h-6 items-center gap-1"
|
||||
data-history-current={item().isCurrent ? metric : undefined}
|
||||
data-history-last-known={item().isLastKnown ? metric : undefined}
|
||||
data-history-unknown={item().isUnknown ? metric : undefined}
|
||||
aria-describedby={item().deferred ? item().descriptionId : undefined}
|
||||
>
|
||||
{renderContent()}
|
||||
</span>
|
||||
)}
|
||||
}
|
||||
>
|
||||
<button
|
||||
type="button"
|
||||
ref={(el) => {
|
||||
if (index() === 0) firstLegendButtonRef = el;
|
||||
}}
|
||||
class={`inline-flex min-h-6 cursor-pointer items-center gap-1 rounded-xs px-1.5 py-0.5 text-left transition-colors hover:bg-surface-hover/70 focus-visible:outline-solid focus-visible:outline-2 focus-visible:outline-offset-1 focus-visible:outline-blue-500 ${
|
||||
item().visible
|
||||
? isSeriesFiltered()
|
||||
? 'bg-surface-hover/60 ring-1 ring-inset ring-border/70'
|
||||
: ''
|
||||
: 'text-muted hover:text-base-content'
|
||||
}`}
|
||||
aria-pressed={item().visible}
|
||||
data-history-legend-series={metric}
|
||||
data-history-series-state={
|
||||
!item().visible ? 'hidden' : item().isolated ? 'isolated' : 'visible'
|
||||
}
|
||||
data-history-current={item().isCurrent ? metric : undefined}
|
||||
data-history-last-known={item().isLastKnown ? metric : undefined}
|
||||
data-history-unknown={item().isUnknown ? metric : undefined}
|
||||
aria-describedby={item().deferred ? item().descriptionId : undefined}
|
||||
title={getLegendSeriesTitle(
|
||||
item().label,
|
||||
item().visible,
|
||||
item().isolated,
|
||||
isSeriesFiltered(),
|
||||
isCompareActive(),
|
||||
)}
|
||||
onClick={(event) => handleSeriesToggle(metric, event)}
|
||||
>
|
||||
{renderContent()}
|
||||
</button>
|
||||
</Show>
|
||||
<Show when={item.isCurrent}>
|
||||
<span>current</span>
|
||||
</Show>
|
||||
<Show when={item.isUnknown}>
|
||||
<span>freshness unknown</span>
|
||||
</Show>
|
||||
<Show when={item.isLastKnown}>
|
||||
<span>last known</span>
|
||||
</Show>
|
||||
</span>
|
||||
)}
|
||||
);
|
||||
}}
|
||||
</For>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<For each={displaySeries().filter((item) => item.deferred)}>
|
||||
{(item) => (
|
||||
<p
|
||||
id={item.descriptionId}
|
||||
class="mb-2 text-xs leading-relaxed text-muted"
|
||||
data-history-deferred={item.metric}
|
||||
>
|
||||
{item.label} reading: {item.deferred?.message}
|
||||
</p>
|
||||
)}
|
||||
<For each={allMetrics()}>
|
||||
{(metric) => {
|
||||
const item = () => displaySeriesByMetric().get(metric)!;
|
||||
return (
|
||||
<Show when={item().deferred}>
|
||||
{(deferred) => (
|
||||
<p
|
||||
id={item().descriptionId}
|
||||
class={item().visible ? 'mb-2 text-xs leading-relaxed text-muted' : 'sr-only'}
|
||||
data-history-deferred={metric}
|
||||
>
|
||||
{item().label} reading: {deferred().message}
|
||||
</p>
|
||||
)}
|
||||
</Show>
|
||||
);
|
||||
}}
|
||||
</For>
|
||||
|
||||
<div class="relative min-h-24 flex-1">
|
||||
@@ -1126,7 +1408,7 @@ const GuestDrawerHistoryGroupChart: Component<GuestDrawerHistoryGroupChartProps>
|
||||
</For>
|
||||
{/* Before any history the scale is a placeholder, so a trigger line
|
||||
would sit at an arbitrary height (an I/O trigger clamps to the top). */}
|
||||
<For each={hasStoredData() ? thresholds() : []}>
|
||||
<For each={hasVisibleStoredData() ? thresholds() : []}>
|
||||
{(threshold) => (
|
||||
<line
|
||||
data-history-threshold={threshold.metric}
|
||||
@@ -1311,10 +1593,15 @@ const GuestDrawerHistoryGroupChart: Component<GuestDrawerHistoryGroupChartProps>
|
||||
)}
|
||||
</For>
|
||||
<Show when={!hasStoredData() && !props.loading}>
|
||||
<div class="pointer-events-none absolute inset-x-8 inset-y-2 flex items-center justify-center rounded-xs text-xs text-muted">
|
||||
<div class="pointer-events-none absolute inset-x-8 inset-y-2 flex items-center justify-center rounded-xs text-center text-xs text-muted">
|
||||
No stored history in this range
|
||||
</div>
|
||||
</Show>
|
||||
<Show when={hasStoredData() && !hasVisibleStoredData() && !props.loading}>
|
||||
<div class="pointer-events-none absolute inset-x-8 inset-y-2 flex items-center justify-center rounded-xs text-center text-xs text-muted">
|
||||
{`No stored history for ${visibleSeriesLabels()} in this range`}
|
||||
</div>
|
||||
</Show>
|
||||
<Show when={props.loading}>
|
||||
<div class="pointer-events-none absolute inset-x-8 inset-y-2 flex items-center justify-center rounded-xs text-xs text-muted">
|
||||
Loading history
|
||||
@@ -1354,6 +1641,14 @@ const GuestDrawerHistoryGroupChart: Component<GuestDrawerHistoryGroupChartProps>
|
||||
{chartDescription()}
|
||||
{alertDescription() ? ` ${alertDescription()}` : ''}
|
||||
</p>
|
||||
<p
|
||||
class="sr-only"
|
||||
aria-live="polite"
|
||||
aria-atomic="true"
|
||||
data-testid="guest-history-series-status"
|
||||
>
|
||||
{seriesAnnouncement()}
|
||||
</p>
|
||||
<Show when={gapMessage()}>
|
||||
{(message) => (
|
||||
<p id={`${inspectionId}-gaps`} class="mt-2 text-xs text-muted" data-history-gaps>
|
||||
@@ -1410,7 +1705,9 @@ const GuestDrawerHistoryGroupChart: Component<GuestDrawerHistoryGroupChartProps>
|
||||
/>
|
||||
<p id={`${inspectionId}-help`} class="sr-only">
|
||||
Use arrow keys, Home or End to inspect{' '}
|
||||
{props.source === 'native' || props.source === 'mixed' || props.source === 'memory'
|
||||
{effectiveSource() === 'native' ||
|
||||
effectiveSource() === 'mixed' ||
|
||||
effectiveSource() === 'memory'
|
||||
? 'readings'
|
||||
: 'stored observations'}
|
||||
.
|
||||
@@ -1532,18 +1829,6 @@ export const GuestDrawerHistory: Component<GuestDrawerHistoryProps> = (props) =>
|
||||
|
||||
const metrics = createMemo(() => historyQuery.value().metrics ?? {});
|
||||
const groups = createMemo(() => props.groups ?? GUEST_DRAWER_HISTORY_GROUPS);
|
||||
const sourceForGroup = (
|
||||
group: GuestDrawerHistoryGroupConfig,
|
||||
): HistoryReadoutSource | undefined => {
|
||||
const { source, metricSources } = historyQuery.value();
|
||||
if (!metricSources) return source;
|
||||
const origins = new Set(
|
||||
group.series.map(({ metric }) => metricSources[metric]).filter(Boolean),
|
||||
);
|
||||
// The time readout belongs to the whole chart, including all of its
|
||||
// directions. Don't call it stored if the plotted series disagree.
|
||||
return origins.size === 1 ? origins.values().next().value : 'mixed';
|
||||
};
|
||||
const sourceNotice = () => {
|
||||
const { source, metricSources } = historyQuery.value();
|
||||
if (!metricSources) return getHistorySourceNotice(source)?.detail;
|
||||
@@ -1557,6 +1842,15 @@ export const GuestDrawerHistory: Component<GuestDrawerHistoryProps> = (props) =>
|
||||
}
|
||||
return hasMemory ? 'This view includes readings from memory.' : undefined;
|
||||
};
|
||||
const targetKey = () => `${props.target?.resourceType ?? ''}:${props.target?.resourceId ?? ''}`;
|
||||
const [hiddenMetricsByGroup, setHiddenMetricsByGroup] = createSignal<
|
||||
Record<string, ReadonlySet<string>>
|
||||
>({});
|
||||
createEffect(
|
||||
on(targetKey, () => {
|
||||
setHiddenMetricsByGroup({});
|
||||
}),
|
||||
);
|
||||
const sourceKey = () => {
|
||||
const zoom = zoomWindow();
|
||||
return zoom
|
||||
@@ -1643,7 +1937,14 @@ export const GuestDrawerHistory: Component<GuestDrawerHistoryProps> = (props) =>
|
||||
const endText = toDatetimeLocalInputValue(endMs);
|
||||
const startOffset = formatUtcOffsetLabel(startMs);
|
||||
const endOffset = formatUtcOffsetLabel(endMs);
|
||||
setWindowInitialBounds({ startMs, endMs, startText, endText, startOffset, endOffset });
|
||||
setWindowInitialBounds({
|
||||
startMs,
|
||||
endMs,
|
||||
startText,
|
||||
endText,
|
||||
startOffset,
|
||||
endOffset,
|
||||
});
|
||||
setWindowDraftStart(startText);
|
||||
setWindowDraftEnd(endText);
|
||||
setWindowStartOffset(startOffset);
|
||||
@@ -2089,16 +2390,25 @@ export const GuestDrawerHistory: Component<GuestDrawerHistoryProps> = (props) =>
|
||||
hiddenOnPhone={!showAllOnPhone() && phoneCollapsedGroups().includes(group)}
|
||||
isZoomed={isZoomed()}
|
||||
group={group}
|
||||
hiddenMetrics={hiddenMetricsByGroup()[group.id] ?? EMPTY_HIDDEN_METRICS}
|
||||
loading={isInitialLoading()}
|
||||
metrics={metrics()}
|
||||
metricSources={historyQuery.value().metricSources}
|
||||
onBrushPreviewChange={setBrushPreview}
|
||||
onCommitZoom={commitZoom}
|
||||
onHiddenMetricsChange={(next) =>
|
||||
setHiddenMetricsByGroup((previous) => ({
|
||||
...previous,
|
||||
[group.id]: next,
|
||||
}))
|
||||
}
|
||||
onResetZoom={resetZoom}
|
||||
currentMetrics={liveCurrentMetrics()}
|
||||
deferredMetrics={props.deferredMetrics}
|
||||
range={props.range}
|
||||
source={sourceForGroup(group)}
|
||||
source={historyQuery.value().source}
|
||||
sourceKey={sourceKey()}
|
||||
targetKey={targetKey()}
|
||||
timeBounds={timeBounds()}
|
||||
touchInspection={touchInspection()}
|
||||
/>
|
||||
|
||||
@@ -0,0 +1,614 @@
|
||||
import { cleanup, fireEvent, render, screen, waitFor, within } from '@solidjs/testing-library';
|
||||
import { createSignal } from 'solid-js';
|
||||
import { afterEach, describe, expect, it, vi } from 'vitest';
|
||||
import { ChartsAPI, type AllMetricsHistoryResponse, type HistoryTimeRange } from '@/api/charts';
|
||||
import { HOST_METRICS_HISTORY_GROUPS } from '@/components/shared/hostMetricsHistoryModel';
|
||||
import { resetCreateNonSuspendingQueryCacheForTest } from '@/hooks/createNonSuspendingQuery';
|
||||
import { GuestDrawerHistory } from '../GuestDrawerHistory';
|
||||
import {
|
||||
getEffectiveHiddenHistoryMetrics,
|
||||
toggleGuestDrawerHistorySeriesVisibility,
|
||||
type GuestDrawerHistoryTarget,
|
||||
} from '../guestDrawerModel';
|
||||
|
||||
vi.mock('@/stores/license', () => ({
|
||||
loadRuntimeCapabilities: vi.fn(async () => undefined),
|
||||
}));
|
||||
|
||||
afterEach(() => {
|
||||
cleanup();
|
||||
resetCreateNonSuspendingQueryCacheForTest();
|
||||
vi.restoreAllMocks();
|
||||
});
|
||||
|
||||
const start = Date.UTC(2026, 9, 12, 12);
|
||||
const target: GuestDrawerHistoryTarget = { resourceType: 'vm', resourceId: 'fixture:pve:101' };
|
||||
|
||||
const point = (minute: number, value: number, min = value, max = value) => ({
|
||||
timestamp: start + minute * 60_000,
|
||||
value,
|
||||
min,
|
||||
max,
|
||||
});
|
||||
|
||||
const response = (
|
||||
metrics: AllMetricsHistoryResponse['metrics'],
|
||||
overrides: Partial<AllMetricsHistoryResponse> = {},
|
||||
): AllMetricsHistoryResponse => ({
|
||||
...target,
|
||||
range: '24h',
|
||||
start,
|
||||
end: start + 10 * 60_000,
|
||||
source: 'store',
|
||||
metrics,
|
||||
...overrides,
|
||||
});
|
||||
|
||||
const group = (id = 'utilization') =>
|
||||
screen.getAllByTestId('guest-history-group-chart').find((el) => el.dataset.historyGroup === id)!;
|
||||
|
||||
const legendButton = (chart: HTMLElement, metric: string) =>
|
||||
chart.querySelector(`button[data-history-legend-series="${metric}"]`) as HTMLButtonElement;
|
||||
|
||||
const drawnSeries = (chart: HTMLElement) =>
|
||||
[...chart.querySelectorAll('path[data-history-series]')].map((el) =>
|
||||
el.getAttribute('data-history-series'),
|
||||
);
|
||||
|
||||
const drawnBands = (chart: HTMLElement) =>
|
||||
[...chart.querySelectorAll('path[data-history-band]')].map((el) =>
|
||||
el.getAttribute('data-history-band'),
|
||||
);
|
||||
|
||||
const drawnThresholds = (chart: HTMLElement) =>
|
||||
[...chart.querySelectorAll('line[data-history-threshold]')].map((el) =>
|
||||
el.getAttribute('data-history-threshold'),
|
||||
);
|
||||
|
||||
const axisLabels = (chart: HTMLElement) =>
|
||||
[...chart.querySelectorAll('[data-history-axis-label]')].map((el) => el.textContent?.trim());
|
||||
|
||||
const hover = (chart: HTMLElement, minute: number, durationMinutes = 10) => {
|
||||
const plot = within(chart).getByTestId('guest-history-plot');
|
||||
vi.spyOn(plot, 'getBoundingClientRect').mockReturnValue({ left: 0, width: 360 } as DOMRect);
|
||||
fireEvent.mouseMove(plot, { clientX: 34 + (minute / durationMinutes) * 318 });
|
||||
return plot;
|
||||
};
|
||||
|
||||
describe('toggleGuestDrawerHistorySeriesVisibility', () => {
|
||||
const metrics = ['cpu', 'memory', 'disk'];
|
||||
|
||||
it('isolates on regular click, switches isolation directly, and restores on second click', () => {
|
||||
const isolatedCpu = toggleGuestDrawerHistorySeriesVisibility(metrics, new Set(), 'cpu', false);
|
||||
expect([...isolatedCpu]).toEqual(['memory', 'disk']);
|
||||
|
||||
const isolatedMemory = toggleGuestDrawerHistorySeriesVisibility(
|
||||
metrics,
|
||||
isolatedCpu,
|
||||
'memory',
|
||||
false,
|
||||
);
|
||||
expect([...isolatedMemory]).toEqual(['cpu', 'disk']);
|
||||
|
||||
const restored = toggleGuestDrawerHistorySeriesVisibility(
|
||||
metrics,
|
||||
isolatedMemory,
|
||||
'memory',
|
||||
false,
|
||||
);
|
||||
expect([...restored]).toEqual([]);
|
||||
});
|
||||
|
||||
it('toggles individual series with modifier click and restores all instead of hiding the last series', () => {
|
||||
const withoutDisk = toggleGuestDrawerHistorySeriesVisibility(metrics, new Set(), 'disk', true);
|
||||
expect([...withoutDisk]).toEqual(['disk']);
|
||||
|
||||
const onlyCpu = toggleGuestDrawerHistorySeriesVisibility(metrics, withoutDisk, 'memory', true);
|
||||
expect([...onlyCpu]).toEqual(['disk', 'memory']);
|
||||
|
||||
const restoredAll = toggleGuestDrawerHistorySeriesVisibility(metrics, onlyCpu, 'cpu', true);
|
||||
expect([...restoredAll]).toEqual([]);
|
||||
|
||||
const addedBack = toggleGuestDrawerHistorySeriesVisibility(metrics, onlyCpu, 'memory', true);
|
||||
expect([...addedBack]).toEqual(['disk']);
|
||||
});
|
||||
|
||||
it('normalizes stale or full hidden sets cleanly', () => {
|
||||
expect([
|
||||
...getEffectiveHiddenHistoryMetrics(['temperature'], new Set(['temperature'])),
|
||||
]).toEqual([]);
|
||||
expect([
|
||||
...getEffectiveHiddenHistoryMetrics(['cpu', 'memory'], new Set(['cpu', 'memory', 'stale'])),
|
||||
]).toEqual([]);
|
||||
expect([
|
||||
...getEffectiveHiddenHistoryMetrics(['cpu', 'memory'], new Set(['memory', 'stale'])),
|
||||
]).toEqual(['memory']);
|
||||
});
|
||||
});
|
||||
|
||||
describe('GuestDrawerHistory legend series isolation', () => {
|
||||
it('isolates a clicked metric, switches directly to another, and restores all on second click or Show all', async () => {
|
||||
vi.spyOn(ChartsAPI, 'getMetricsHistory').mockResolvedValue(
|
||||
response({
|
||||
cpu: [point(0, 12, 8, 28), point(5, 18, 10, 42), point(10, 24, 15, 36)],
|
||||
memory: [point(0, 62, 60, 64), point(5, 66, 63, 72), point(10, 70, 68, 74)],
|
||||
disk: [point(0, 40), point(5, 42), point(10, 44)],
|
||||
}),
|
||||
);
|
||||
|
||||
render(() => (
|
||||
<GuestDrawerHistory
|
||||
target={target}
|
||||
range="24h"
|
||||
alerts={{
|
||||
cpu: { severity: 'warning', value: 80 },
|
||||
memory: { severity: 'critical', value: 90 },
|
||||
}}
|
||||
/>
|
||||
));
|
||||
|
||||
await screen.findByRole('slider', { name: 'Inspect Utilization history' });
|
||||
const chart = group('utilization');
|
||||
|
||||
expect(drawnSeries(chart)).toEqual(['cpu', 'memory', 'disk']);
|
||||
expect(drawnThresholds(chart)).toEqual(['cpu', 'memory']);
|
||||
expect(within(chart).queryByTestId('guest-history-show-all')).toBeNull();
|
||||
|
||||
// Click CPU -> isolate CPU only, keep fixed 0-100% Y-axis, hide Memory alert line.
|
||||
fireEvent.click(legendButton(chart, 'cpu'));
|
||||
|
||||
expect(drawnSeries(chart)).toEqual(['cpu']);
|
||||
expect(drawnBands(chart)).toEqual(['cpu']);
|
||||
expect(drawnThresholds(chart)).toEqual(['cpu']);
|
||||
expect(axisLabels(chart)).toEqual(['100%', '50%', '0%']);
|
||||
expect(legendButton(chart, 'cpu')).toHaveAttribute('aria-pressed', 'true');
|
||||
expect(legendButton(chart, 'cpu')).toHaveAttribute('data-history-series-state', 'isolated');
|
||||
expect(legendButton(chart, 'memory')).toHaveAttribute('aria-pressed', 'false');
|
||||
expect(legendButton(chart, 'memory')).toHaveAttribute('data-history-series-state', 'hidden');
|
||||
expect(legendButton(chart, 'disk')).toHaveAttribute('aria-pressed', 'false');
|
||||
expect(within(chart).getByTestId('guest-history-series-status')).toHaveTextContent(
|
||||
'Utilization: showing CPU only.',
|
||||
);
|
||||
expect(
|
||||
within(chart).getByRole('img', { name: 'Utilization history' }),
|
||||
).toHaveAccessibleDescription(expect.stringContaining('Showing CPU only.'));
|
||||
expect(
|
||||
within(chart).getByRole('img', { name: 'Utilization history' }),
|
||||
).toHaveAccessibleDescription(expect.not.stringContaining('Memory critical alert'));
|
||||
|
||||
// Hovering plots markers and peak labels only for the visible series.
|
||||
hover(chart, 5);
|
||||
expect(
|
||||
[...chart.querySelectorAll('[data-history-hover-marker]')].map((el) =>
|
||||
el.getAttribute('data-history-hover-marker'),
|
||||
),
|
||||
).toEqual(['cpu']);
|
||||
expect(
|
||||
[...chart.querySelectorAll('[data-history-peak]')].map((el) =>
|
||||
el.getAttribute('data-history-peak'),
|
||||
),
|
||||
).toEqual(['cpu']);
|
||||
|
||||
// Click Memory -> directly switches isolation to Memory.
|
||||
fireEvent.click(legendButton(chart, 'memory'));
|
||||
expect(drawnSeries(chart)).toEqual(['memory']);
|
||||
expect(drawnThresholds(chart)).toEqual(['memory']);
|
||||
expect(legendButton(chart, 'memory')).toHaveAttribute('aria-pressed', 'true');
|
||||
expect(legendButton(chart, 'cpu')).toHaveAttribute('aria-pressed', 'false');
|
||||
|
||||
// Click Memory again -> restores all series.
|
||||
fireEvent.click(legendButton(chart, 'memory'));
|
||||
expect(drawnSeries(chart)).toEqual(['cpu', 'memory', 'disk']);
|
||||
expect(drawnThresholds(chart)).toEqual(['cpu', 'memory']);
|
||||
expect(within(chart).queryByTestId('guest-history-show-all')).toBeNull();
|
||||
|
||||
// Isolate Disk, then restore via Show all and verify focus moves to the first legend button.
|
||||
fireEvent.click(legendButton(chart, 'disk'));
|
||||
expect(drawnSeries(chart)).toEqual(['disk']);
|
||||
const showAll = within(chart).getByTestId('guest-history-show-all');
|
||||
showAll.focus();
|
||||
fireEvent.click(showAll);
|
||||
expect(drawnSeries(chart)).toEqual(['cpu', 'memory', 'disk']);
|
||||
expect(legendButton(chart, 'cpu')).toHaveFocus();
|
||||
});
|
||||
|
||||
it('supports Ctrl/Cmd/Shift multi-toggle and restores all instead of hiding the final visible series', async () => {
|
||||
vi.spyOn(ChartsAPI, 'getMetricsHistory').mockResolvedValue(
|
||||
response({
|
||||
cpu: [point(0, 12), point(10, 24)],
|
||||
memory: [point(0, 62), point(10, 70)],
|
||||
disk: [point(0, 40), point(10, 44)],
|
||||
}),
|
||||
);
|
||||
|
||||
render(() => <GuestDrawerHistory target={target} range="24h" />);
|
||||
await screen.findByRole('slider', { name: 'Inspect Utilization history' });
|
||||
const chart = group('utilization');
|
||||
|
||||
// Cmd+click Disk hides only Disk (CPU + Memory remain visible).
|
||||
fireEvent.click(legendButton(chart, 'disk'), { metaKey: true });
|
||||
expect(drawnSeries(chart)).toEqual(['cpu', 'memory']);
|
||||
expect(legendButton(chart, 'cpu')).toHaveAttribute('data-history-series-state', 'visible');
|
||||
expect(legendButton(chart, 'memory')).toHaveAttribute('data-history-series-state', 'visible');
|
||||
expect(legendButton(chart, 'disk')).toHaveAttribute('data-history-series-state', 'hidden');
|
||||
|
||||
// Ctrl+click Memory leaves only CPU.
|
||||
fireEvent.click(legendButton(chart, 'memory'), { ctrlKey: true });
|
||||
expect(drawnSeries(chart)).toEqual(['cpu']);
|
||||
expect(legendButton(chart, 'cpu')).toHaveAttribute('data-history-series-state', 'isolated');
|
||||
|
||||
// Shift+click CPU (last remaining series) restores all series instead of leaving a blank chart.
|
||||
fireEvent.click(legendButton(chart, 'cpu'), { shiftKey: true });
|
||||
expect(drawnSeries(chart)).toEqual(['cpu', 'memory', 'disk']);
|
||||
});
|
||||
|
||||
it('rescales auto-scaled I/O Y-axis when isolating a quiet series beside a large spike', async () => {
|
||||
vi.spyOn(ChartsAPI, 'getMetricsHistory').mockResolvedValue(
|
||||
response({
|
||||
netin: [point(0, 80 * 1024 * 1024), point(10, 100 * 1024 * 1024)],
|
||||
netout: [point(0, 512 * 1024), point(10, 1024 * 1024)],
|
||||
}),
|
||||
);
|
||||
|
||||
render(() => <GuestDrawerHistory target={target} range="24h" />);
|
||||
await screen.findByRole('slider', { name: 'Inspect Network I/O history' });
|
||||
const network = group('network');
|
||||
|
||||
// Combined scale is dominated by 100 MB/s In.
|
||||
expect(axisLabels(network)[0]).toBe('115M/s');
|
||||
|
||||
// Isolating Out (max 1 MB/s) rescales the Y-axis down from 115M/s to ~1.2M/s.
|
||||
fireEvent.click(legendButton(network, 'netout'));
|
||||
expect(drawnSeries(network)).toEqual(['netout']);
|
||||
expect(axisLabels(network)[0]).toMatch(/^1\.[12]M\/s$/);
|
||||
|
||||
// Clicking Out again restores both series and the full scale.
|
||||
fireEvent.click(legendButton(network, 'netout'));
|
||||
expect(drawnSeries(network)).toEqual(['netin', 'netout']);
|
||||
expect(axisLabels(network)[0]).toBe('115M/s');
|
||||
});
|
||||
|
||||
it('keeps single-series panels non-interactive and isolates state per chart panel', async () => {
|
||||
vi.spyOn(ChartsAPI, 'getMetricsHistory').mockResolvedValue(
|
||||
response({
|
||||
cpu: [point(0, 12), point(10, 24)],
|
||||
memory: [point(0, 62), point(10, 70)],
|
||||
netin: [point(0, 1024), point(10, 2048)],
|
||||
netout: [point(0, 512), point(10, 1024)],
|
||||
temperature: [point(0, 45), point(10, 48)],
|
||||
}),
|
||||
);
|
||||
|
||||
render(() => (
|
||||
<GuestDrawerHistory target={target} range="24h" groups={HOST_METRICS_HISTORY_GROUPS} />
|
||||
));
|
||||
|
||||
await screen.findByRole('slider', { name: 'Inspect Thermals history' });
|
||||
const thermals = group('thermals');
|
||||
const utilization = group('utilization');
|
||||
const network = group('network');
|
||||
|
||||
// Single-series Thermals panel has no legend toggle buttons.
|
||||
expect(thermals.querySelectorAll('button[data-history-legend-series]')).toHaveLength(0);
|
||||
|
||||
// Isolating CPU in Utilization does not affect Network I/O.
|
||||
fireEvent.click(legendButton(utilization, 'cpu'));
|
||||
expect(drawnSeries(utilization)).toEqual(['cpu']);
|
||||
expect(drawnSeries(network)).toEqual(['netin', 'netout']);
|
||||
});
|
||||
|
||||
it('preserves gaps when hiding a sibling series and stays honest when isolating an empty series', async () => {
|
||||
vi.spyOn(ChartsAPI, 'getMetricsHistory').mockResolvedValue(
|
||||
response({
|
||||
cpu: [point(0, 12), point(10, 24)],
|
||||
memory: [point(0, 50), point(5, 55), point(10, 60)],
|
||||
}),
|
||||
);
|
||||
|
||||
render(() => (
|
||||
<GuestDrawerHistory
|
||||
target={target}
|
||||
range="24h"
|
||||
currentMetrics={{ cpu: 99, memory: 98, disk: 77 }}
|
||||
/>
|
||||
));
|
||||
|
||||
await screen.findByRole('slider', { name: 'Inspect Utilization history' });
|
||||
const chart = group('utilization');
|
||||
|
||||
// Isolating CPU keeps its honest missing-observation break across minute 5.
|
||||
fireEvent.click(legendButton(chart, 'cpu'));
|
||||
expect(drawnSeries(chart)).toEqual([]);
|
||||
expect(chart.querySelectorAll('[data-history-observation="cpu"]')).toHaveLength(2);
|
||||
expect(chart.querySelector('[data-history-gaps]')).toHaveTextContent(
|
||||
'Missing observations: CPU.',
|
||||
);
|
||||
|
||||
// Isolating Disk (0 stored points on a stored-history panel) shows an explicit
|
||||
// empty message and never substitutes live fallback current readings.
|
||||
fireEvent.click(legendButton(chart, 'disk'));
|
||||
expect(chart).toHaveTextContent('No stored history for Disk in this range');
|
||||
expect(chart.querySelector('[data-history-current]')).toBeNull();
|
||||
expect(chart).not.toHaveTextContent('77.0%');
|
||||
expect(within(chart).queryByTestId('guest-history-hover-time')).toBeNull();
|
||||
});
|
||||
|
||||
it('persists isolation across range changes on the same resource and resets when switching resources', async () => {
|
||||
vi.spyOn(ChartsAPI, 'getMetricsHistory').mockImplementation(async (params) =>
|
||||
response(
|
||||
{
|
||||
cpu: [point(0, 15), point(10, 25)],
|
||||
memory: [point(0, 50), point(10, 60)],
|
||||
disk: [point(0, 30), point(10, 35)],
|
||||
},
|
||||
{ resourceId: params.resourceId, range: params.range ?? '24h' },
|
||||
),
|
||||
);
|
||||
|
||||
const [currentTarget, setCurrentTarget] = createSignal(target);
|
||||
const [range, setRange] = createSignal<HistoryTimeRange>('24h');
|
||||
|
||||
render(() => <GuestDrawerHistory target={currentTarget()} range={range()} />);
|
||||
await screen.findByRole('slider', { name: 'Inspect Utilization history' });
|
||||
const chart = group('utilization');
|
||||
|
||||
fireEvent.click(legendButton(chart, 'cpu'));
|
||||
expect(drawnSeries(chart)).toEqual(['cpu']);
|
||||
|
||||
// Changing time range on the same resource keeps CPU isolated.
|
||||
setRange('7d');
|
||||
await waitFor(() => expect(ChartsAPI.getMetricsHistory).toHaveBeenCalledTimes(2));
|
||||
await waitFor(() => expect(drawnSeries(chart)).toEqual(['cpu']));
|
||||
expect(legendButton(chart, 'cpu')).toHaveAttribute('data-history-series-state', 'isolated');
|
||||
|
||||
// Switching to another resource resets isolation back to all series.
|
||||
setCurrentTarget({ resourceType: 'vm', resourceId: 'fixture:pve:102' });
|
||||
await waitFor(() => expect(ChartsAPI.getMetricsHistory).toHaveBeenCalledTimes(3));
|
||||
await waitFor(() => expect(drawnSeries(chart)).toEqual(['cpu', 'memory', 'disk']));
|
||||
expect(within(chart).queryByTestId('guest-history-show-all')).toBeNull();
|
||||
});
|
||||
|
||||
it('keeps the exact focused legend button mounted when toggling isolation and restoring', async () => {
|
||||
vi.spyOn(ChartsAPI, 'getMetricsHistory').mockResolvedValue(
|
||||
response({
|
||||
cpu: [point(0, 12), point(10, 24)],
|
||||
memory: [point(0, 62), point(10, 70)],
|
||||
disk: [point(0, 40), point(10, 44)],
|
||||
}),
|
||||
);
|
||||
|
||||
render(() => <GuestDrawerHistory target={target} range="24h" />);
|
||||
await screen.findByRole('slider', { name: 'Inspect Utilization history' });
|
||||
const chart = group('utilization');
|
||||
|
||||
const memoryButton = legendButton(chart, 'memory');
|
||||
memoryButton.focus();
|
||||
expect(document.activeElement).toBe(memoryButton);
|
||||
|
||||
// Isolate Memory via button activation; the exact DOM node stays mounted and focused.
|
||||
fireEvent.keyDown(memoryButton, { key: ' ' });
|
||||
fireEvent.keyUp(memoryButton, { key: ' ' });
|
||||
fireEvent.click(memoryButton);
|
||||
expect(drawnSeries(chart)).toEqual(['memory']);
|
||||
expect(legendButton(chart, 'memory')).toBe(memoryButton);
|
||||
expect(document.activeElement).toBe(memoryButton);
|
||||
|
||||
// Activate Memory again to restore all series; focus remains on the same button.
|
||||
fireEvent.keyDown(memoryButton, { key: ' ' });
|
||||
fireEvent.keyUp(memoryButton, { key: ' ' });
|
||||
fireEvent.click(memoryButton);
|
||||
expect(drawnSeries(chart)).toEqual(['cpu', 'memory', 'disk']);
|
||||
expect(legendButton(chart, 'memory')).toBe(memoryButton);
|
||||
expect(document.activeElement).toBe(memoryButton);
|
||||
});
|
||||
|
||||
it('hides deferred freshness prose visually for hidden series while keeping accessible descriptions', async () => {
|
||||
vi.spyOn(ChartsAPI, 'getMetricsHistory').mockResolvedValue(
|
||||
response({
|
||||
cpu: [point(0, 12), point(10, 24)],
|
||||
memory: [point(0, 62), point(10, 70)],
|
||||
}),
|
||||
);
|
||||
|
||||
render(() => (
|
||||
<GuestDrawerHistory
|
||||
target={target}
|
||||
range="24h"
|
||||
deferredMetrics={{
|
||||
memory: {
|
||||
lastKnownValue: 70,
|
||||
valueLabel: 'freshness unknown',
|
||||
message: 'Freshness unknown. Not a current measurement.',
|
||||
},
|
||||
}}
|
||||
/>
|
||||
));
|
||||
|
||||
await screen.findByRole('slider', { name: 'Inspect Utilization history' });
|
||||
const chart = group('utilization');
|
||||
const deferredNote = chart.querySelector('[data-history-deferred="memory"]') as HTMLElement;
|
||||
const memoryButton = legendButton(chart, 'memory');
|
||||
|
||||
expect(deferredNote).not.toHaveClass('sr-only');
|
||||
expect(memoryButton).toHaveAttribute('aria-describedby', deferredNote.id);
|
||||
|
||||
// Isolating CPU hides Memory's freshness note visually while preserving aria-describedby.
|
||||
fireEvent.click(legendButton(chart, 'cpu'));
|
||||
expect(deferredNote).toHaveClass('sr-only');
|
||||
expect(memoryButton).toHaveAttribute('aria-describedby', deferredNote.id);
|
||||
|
||||
// Restoring all series brings the inline note back.
|
||||
fireEvent.click(legendButton(chart, 'cpu'));
|
||||
expect(deferredNote).not.toHaveClass('sr-only');
|
||||
});
|
||||
|
||||
it('resolves mixed-source readout labels from only the visible series', async () => {
|
||||
vi.spyOn(ChartsAPI, 'getMetricsHistory').mockResolvedValue(
|
||||
response(
|
||||
{
|
||||
diskread: [point(0, 1024), point(10, 2048)],
|
||||
diskwrite: [point(0, 512), point(10, 1024)],
|
||||
},
|
||||
{
|
||||
source: undefined,
|
||||
metricSources: {
|
||||
diskread: 'store',
|
||||
diskwrite: 'memory',
|
||||
},
|
||||
},
|
||||
),
|
||||
);
|
||||
|
||||
render(() => <GuestDrawerHistory target={target} range="24h" />);
|
||||
await screen.findByRole('slider', { name: 'Inspect Disk I/O history' });
|
||||
const diskIo = group('disk-io');
|
||||
const timeReadout = () => within(diskIo).getByTestId('guest-history-hover-time');
|
||||
|
||||
expect(timeReadout()).toHaveTextContent('Latest recorded');
|
||||
|
||||
// Isolating the stored Read series updates the readout origin to Latest stored.
|
||||
fireEvent.click(legendButton(diskIo, 'diskread'));
|
||||
expect(timeReadout()).toHaveTextContent('Latest stored');
|
||||
|
||||
// Isolating the memory-backed Write series uses Latest recorded.
|
||||
fireEvent.click(legendButton(diskIo, 'diskwrite'));
|
||||
expect(timeReadout()).toHaveTextContent('Latest recorded');
|
||||
|
||||
// Restoring both returns to Latest recorded.
|
||||
fireEvent.click(legendButton(diskIo, 'diskwrite'));
|
||||
expect(timeReadout()).toHaveTextContent('Latest recorded');
|
||||
});
|
||||
|
||||
it('rescales both Celsius temperature axis bounds when isolating a cooler series', async () => {
|
||||
vi.spyOn(ChartsAPI, 'getMetricsHistory').mockResolvedValue(
|
||||
response({
|
||||
cpu_temp: [point(0, 68), point(10, 74)],
|
||||
drive_temp: [point(0, 34), point(10, 38)],
|
||||
}),
|
||||
);
|
||||
|
||||
render(() => (
|
||||
<GuestDrawerHistory
|
||||
target={target}
|
||||
range="24h"
|
||||
groups={[
|
||||
{
|
||||
id: 'thermals-multi',
|
||||
label: 'Thermals',
|
||||
unit: 'C',
|
||||
series: [
|
||||
{ metric: 'cpu_temp', label: 'CPU', unit: 'C', color: '#ef4444' },
|
||||
{ metric: 'drive_temp', label: 'Drive', unit: 'C', color: '#3b82f6' },
|
||||
],
|
||||
},
|
||||
]}
|
||||
/>
|
||||
));
|
||||
|
||||
await screen.findByRole('slider', { name: 'Inspect Thermals history' });
|
||||
const thermals = group('thermals-multi');
|
||||
const combinedAxis = axisLabels(thermals);
|
||||
expect(combinedAxis).toEqual(['80°C', '54°C', '28°C']);
|
||||
|
||||
// Isolating Drive moves both the upper and lower Y-axis bounds.
|
||||
fireEvent.click(legendButton(thermals, 'drive_temp'));
|
||||
const isolatedAxis = axisLabels(thermals);
|
||||
expect(isolatedAxis).toEqual(['40°C', '36°C', '32°C']);
|
||||
expect(isolatedAxis[0]).not.toBe(combinedAxis[0]);
|
||||
expect(isolatedAxis[2]).not.toBe(combinedAxis[2]);
|
||||
|
||||
// Restoring all recovers both original bounds.
|
||||
fireEvent.click(legendButton(thermals, 'drive_temp'));
|
||||
expect(axisLabels(thermals)).toEqual(combinedAxis);
|
||||
});
|
||||
|
||||
it('preserves series isolation across a failed range read and subsequent recovery', async () => {
|
||||
const fetch = vi
|
||||
.spyOn(ChartsAPI, 'getMetricsHistory')
|
||||
.mockResolvedValueOnce(
|
||||
response(
|
||||
{
|
||||
cpu: [point(0, 15), point(10, 25)],
|
||||
memory: [point(0, 50), point(10, 60)],
|
||||
disk: [point(0, 30), point(10, 35)],
|
||||
},
|
||||
{ range: '24h' },
|
||||
),
|
||||
)
|
||||
.mockRejectedValueOnce(Object.assign(new Error('temporary outage'), { status: 503 }))
|
||||
.mockResolvedValueOnce(
|
||||
response(
|
||||
{
|
||||
cpu: [point(0, 18), point(10, 28)],
|
||||
memory: [point(0, 52), point(10, 62)],
|
||||
disk: [point(0, 31), point(10, 36)],
|
||||
},
|
||||
{ range: '7d' },
|
||||
),
|
||||
);
|
||||
|
||||
const [range, setRange] = createSignal<HistoryTimeRange>('24h');
|
||||
render(() => <GuestDrawerHistory target={target} range={range()} />);
|
||||
await screen.findByRole('slider', { name: 'Inspect Utilization history' });
|
||||
|
||||
// Isolate CPU at 24h.
|
||||
fireEvent.click(legendButton(group('utilization'), 'cpu'));
|
||||
expect(drawnSeries(group('utilization'))).toEqual(['cpu']);
|
||||
|
||||
// Switch to an uncached 7d range that fails and temporarily unmounts the charts.
|
||||
setRange('7d');
|
||||
const retry = await screen.findByRole('button', { name: 'Retry history' });
|
||||
expect(screen.queryByTestId('guest-history-group-chart')).toBeNull();
|
||||
|
||||
// Retrying succeeds and keeps CPU isolated without losing selection state.
|
||||
fireEvent.click(retry);
|
||||
await waitFor(() => expect(fetch).toHaveBeenCalledTimes(3));
|
||||
await waitFor(() => expect(drawnSeries(group('utilization'))).toEqual(['cpu']));
|
||||
expect(legendButton(group('utilization'), 'cpu')).toHaveAttribute(
|
||||
'data-history-series-state',
|
||||
'isolated',
|
||||
);
|
||||
});
|
||||
|
||||
it('lets tap-only users select two of three series with Compare mode without modifier keys', async () => {
|
||||
vi.spyOn(ChartsAPI, 'getMetricsHistory').mockResolvedValue(
|
||||
response({
|
||||
cpu: [point(0, 12), point(10, 24)],
|
||||
memory: [point(0, 62), point(10, 70)],
|
||||
disk: [point(0, 40), point(10, 44)],
|
||||
netin: [point(0, 1024), point(10, 2048)],
|
||||
netout: [point(0, 512), point(10, 1024)],
|
||||
}),
|
||||
);
|
||||
|
||||
render(() => <GuestDrawerHistory target={target} range="24h" />);
|
||||
await screen.findByRole('slider', { name: 'Inspect Utilization history' });
|
||||
const utilization = group('utilization');
|
||||
const network = group('network');
|
||||
|
||||
// Compare is absent in default state and never shown on 2-series panels.
|
||||
expect(within(utilization).queryByTestId('guest-history-compare-toggle')).toBeNull();
|
||||
fireEvent.click(legendButton(network, 'netout'));
|
||||
expect(within(network).queryByTestId('guest-history-compare-toggle')).toBeNull();
|
||||
|
||||
// Tap CPU -> single-tap isolation still works as default.
|
||||
fireEvent.click(legendButton(utilization, 'cpu'));
|
||||
expect(drawnSeries(utilization)).toEqual(['cpu']);
|
||||
const compareBtn = within(utilization).getByTestId('guest-history-compare-toggle');
|
||||
expect(compareBtn).toHaveAttribute('aria-pressed', 'false');
|
||||
|
||||
// Tap Compare, then tap Memory (no modifier keys) -> CPU + Memory with Disk hidden.
|
||||
fireEvent.click(compareBtn);
|
||||
expect(compareBtn).toHaveAttribute('aria-pressed', 'true');
|
||||
expect(legendButton(utilization, 'cpu')).toHaveAttribute('title', 'Click to show all series.');
|
||||
fireEvent.click(legendButton(utilization, 'memory'));
|
||||
expect(legendButton(utilization, 'cpu')).toHaveAttribute('title', 'Click to hide CPU.');
|
||||
expect(drawnSeries(utilization)).toEqual(['cpu', 'memory']);
|
||||
expect(legendButton(utilization, 'disk')).toHaveAttribute('aria-pressed', 'false');
|
||||
|
||||
// Tapping Disk adds it back and restores all 3 series, exiting Compare mode cleanly.
|
||||
fireEvent.click(legendButton(utilization, 'disk'));
|
||||
expect(drawnSeries(utilization)).toEqual(['cpu', 'memory', 'disk']);
|
||||
expect(within(utilization).queryByTestId('guest-history-compare-toggle')).toBeNull();
|
||||
});
|
||||
});
|
||||
@@ -422,6 +422,54 @@ export const getGuestDrawerHistoryValueLabel = (
|
||||
return formatHistoryChartTooltipValue(latest.value, unit);
|
||||
};
|
||||
|
||||
export const getEffectiveHiddenHistoryMetrics = (
|
||||
allMetrics: readonly string[],
|
||||
hiddenMetrics: ReadonlySet<string>,
|
||||
): ReadonlySet<string> => {
|
||||
if (allMetrics.length <= 1 || hiddenMetrics.size === 0) return new Set();
|
||||
const next = new Set<string>();
|
||||
for (const metric of allMetrics) {
|
||||
if (hiddenMetrics.has(metric)) next.add(metric);
|
||||
}
|
||||
return next.size >= allMetrics.length ? new Set() : next;
|
||||
};
|
||||
|
||||
// Grafana-style legend visibility toggle:
|
||||
// - Regular click isolates the clicked series, or restores all series when that
|
||||
// series is already the only visible one.
|
||||
// - Modifier click (Ctrl, Cmd, or Shift) toggles just the clicked series on or
|
||||
// off, restoring all series instead of hiding the last visible one.
|
||||
export const toggleGuestDrawerHistorySeriesVisibility = (
|
||||
allMetrics: readonly string[],
|
||||
currentHidden: ReadonlySet<string>,
|
||||
clickedMetric: string,
|
||||
multiSelect: boolean,
|
||||
): ReadonlySet<string> => {
|
||||
if (allMetrics.length <= 1 || !allMetrics.includes(clickedMetric)) {
|
||||
return new Set();
|
||||
}
|
||||
const normalizedHidden = getEffectiveHiddenHistoryMetrics(allMetrics, currentHidden);
|
||||
const visible = allMetrics.filter((metric) => !normalizedHidden.has(metric));
|
||||
|
||||
if (!multiSelect) {
|
||||
if (visible.length === 1 && visible[0] === clickedMetric) {
|
||||
return new Set();
|
||||
}
|
||||
return new Set(allMetrics.filter((metric) => metric !== clickedMetric));
|
||||
}
|
||||
|
||||
const next = new Set(normalizedHidden);
|
||||
if (next.has(clickedMetric)) {
|
||||
next.delete(clickedMetric);
|
||||
return next;
|
||||
}
|
||||
if (visible.length <= 1) {
|
||||
return new Set();
|
||||
}
|
||||
next.add(clickedMetric);
|
||||
return next;
|
||||
};
|
||||
|
||||
export const getGuestDrawerHistoryRangeBounds = (
|
||||
groupedSeries: readonly { points: readonly AggregatedMetricPoint[] }[],
|
||||
window?: { start: number; end: number },
|
||||
|
||||
@@ -53,7 +53,9 @@ describe('History interpretation help', () => {
|
||||
"Not necessarily the highest value in the whole selected range or the value at an alert's exact time",
|
||||
);
|
||||
const renderer = read('frontend-modern/src/components/Workloads/GuestDrawerHistory.tsx');
|
||||
expect(renderer).toContain('getHistoryReadoutLabel(props.source, activeTimestamp() !== null)');
|
||||
expect(renderer).toContain(
|
||||
'getHistoryReadoutLabel(effectiveSource(), activeTimestamp() !== null)',
|
||||
);
|
||||
expect(getHistoryReadoutLabel('store', false)).toBe('Latest stored');
|
||||
expect(getHistoryReadoutLabel('store', true)).toBe('Stored');
|
||||
for (const label of ['Latest stored', 'Stored']) {
|
||||
|
||||
Reference in New Issue
Block a user