Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
165 changes: 152 additions & 13 deletions timeserieschart/src/TimeSeriesChartBase.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -28,6 +28,7 @@ import {
DEFAULT_TOOLTIP_CONFIG,
EChart,
enableDataZoom,
ExemplarMetadataTooltip,
getClosestTimestamp,
getCommonTimeScale,
getFormattedAxis,
Expand All @@ -37,7 +38,7 @@ import {
useChartsContext,
useTimeZone,
} from '@perses-dev/components';
import type { TimeScale, TimeSeries } from '@perses-dev/spec';
import type { Exemplar, Labels, TimeScale, TimeSeries } from '@perses-dev/spec';
import type {
DatasetComponentOption as DatasetOption,
EChartsCoreOption,
Expand All @@ -46,7 +47,11 @@ import type {
YAXisComponentOption,
TooltipComponentOption,
} from 'echarts';
import { LineChart as EChartsLineChart, BarChart as EChartsBarChart } from 'echarts/charts';
import {
LineChart as EChartsLineChart,
BarChart as EChartsBarChart,
ScatterChart as EChartsScatterChart,
} from 'echarts/charts';
import {
GridComponent,
DatasetComponent,
Expand All @@ -68,11 +73,14 @@ import { forwardRef, useCallback, useEffect, useImperativeHandle, useMemo, useRe

import { AnnotationTooltip, buildAnnotationSeries } from './annotations/AnnotationTooltip';
import type { TimeSeriesAnnotation } from './utils/annotation';
import type { ExemplarChartData } from './utils/data-transform';
import { EXEMPLAR_SERIES_ID_PREFIX, EXEMPLAR_SYMBOL_SIZE, getExemplarSeries } from './utils/data-transform';
import { createTimezoneAwareAxisFormatter } from './utils/timezone-formatter';

registerECharts([
EChartsLineChart,
EChartsBarChart,
EChartsScatterChart,
GridComponent,
DatasetComponent,
DataZoomComponent,
Expand All @@ -85,10 +93,27 @@ registerECharts([
CanvasRenderer,
]);

interface HoveredExemplar {
exemplar: Exemplar;
seriesLabels?: Labels;
/**
* The Y value actually plotted for the marker. Differs from `exemplar.value` when the
* matching series is rendered with the negativeY transform (value negated for display).
*/
plottedValue: number;
}

/**
* Maximum pixel distance from an exemplar marker center for the cursor to count as still
* hovering it (covers the full diamond bounding box, corners included).
*/
const EXEMPLAR_HOVER_RADIUS = (Math.SQRT2 * EXEMPLAR_SYMBOL_SIZE) / 2;

export interface TimeChartProps {
height: number;
data: TimeSeries[];
seriesMapping: TimeChartSeriesMapping;
exemplars?: ExemplarChartData[];
annotations?: TimeSeriesAnnotation[];
timeScale?: TimeScale;
yAxis?: YAXisComponentOption | YAXisComponentOption[];
Expand All @@ -112,6 +137,7 @@ export const TimeSeriesChartBase = forwardRef<ChartInstance, TimeChartProps>(fun
height,
data,
seriesMapping,
exemplars,
annotations,
timeScale: timeScaleProp,
yAxis,
Expand Down Expand Up @@ -139,6 +165,9 @@ export const TimeSeriesChartBase = forwardRef<ChartInstance, TimeChartProps>(fun
const [startX, setStartX] = useState(0);
const [hoveredAnnotation, setHoveredAnnotation] = useState<TimeSeriesAnnotation | null>(null);
const [pinnedAnnotation, setPinnedAnnotation] = useState<TimeSeriesAnnotation | null>(null);
const [hoveredExemplar, setHoveredExemplar] = useState<HoveredExemplar | null>(null);
const [pinnedExemplar, setPinnedExemplar] = useState<HoveredExemplar | null>(null);
const [pinnedExemplarPos, setPinnedExemplarPos] = useState<CursorCoordinates | null>(null);
const [pinnedAnnotationPos, setPinnedAnnotationPos] = useState<CursorCoordinates | null>(null);
const { timeZone, formatWithUserTimeZone } = useTimeZone();

Expand Down Expand Up @@ -212,6 +241,22 @@ export const TimeSeriesChartBase = forwardRef<ChartInstance, TimeChartProps>(fun
},
// eslint-disable-next-line @typescript-eslint/no-explicit-any
mouseover: (params: any): void => {
if (
params.componentType === 'series' &&
params.seriesType === 'scatter' &&
typeof params.seriesId === 'string' &&
params.seriesId.startsWith(EXEMPLAR_SERIES_ID_PREFIX)
) {
if (params.data?.exemplar) {
setHoveredExemplar({
exemplar: params.data.exemplar,
seriesLabels: params.data.seriesLabels,
plottedValue: params.data?.value?.[1] ?? params.data.exemplar.value,
});
return;
}
}
setHoveredExemplar(null);
// Only markPoint (triangles under the X-axis) opens the annotation tooltip.
// Hovering markLine or anything else keeps the regular TimeSeries tooltip visible
// and clears any stale hovered annotation (mouseout is sometimes missed by ECharts).
Expand All @@ -226,6 +271,15 @@ export const TimeSeriesChartBase = forwardRef<ChartInstance, TimeChartProps>(fun
},
// eslint-disable-next-line @typescript-eslint/no-explicit-any
mouseout: (params: any): void => {
if (
params.componentType === 'series' &&
params.seriesType === 'scatter' &&
typeof params.seriesId === 'string' &&
params.seriesId.startsWith(EXEMPLAR_SERIES_ID_PREFIX)
) {
setHoveredExemplar(null);
return;
}
if (
annotations &&
params.componentType === 'markPoint' &&
Expand All @@ -243,13 +297,16 @@ export const TimeSeriesChartBase = forwardRef<ChartInstance, TimeChartProps>(fun
// Cursor left the chart canvas — guarantee the annotation tooltip is dismissed.
setHoveredAnnotation(null);
}
setHoveredExemplar(null);
},
};
}, [annotations, onDataZoom]);

// Generate annotation series for ECharts markArea (range), markLine (point), and markPoint (markers under X-axis)
const annotationSeries = useMemo(() => buildAnnotationSeries(annotations), [annotations]);

const exemplarSeries = useMemo(() => exemplars?.map(getExemplarSeries) ?? [], [exemplars]);

const { noDataOption } = chartsTheme;

const option: EChartsCoreOption = useMemo(() => {
Expand All @@ -270,8 +327,8 @@ export const TimeSeriesChartBase = forwardRef<ChartInstance, TimeChartProps>(fun

const updatedSeriesMapping =
enablePinning && pinnedCrosshair !== null
? [...seriesMapping, pinnedCrosshair, ...annotationSeries]
: [...seriesMapping, ...annotationSeries];
? [...seriesMapping, pinnedCrosshair, ...annotationSeries, ...exemplarSeries]
: [...seriesMapping, ...annotationSeries, ...exemplarSeries];

const option: EChartsCoreOption = {
dataset: dataset,
Expand Down Expand Up @@ -327,6 +384,7 @@ export const TimeSeriesChartBase = forwardRef<ChartInstance, TimeChartProps>(fun
data,
seriesMapping,
annotationSeries,
exemplarSeries,
timeScale,
yAxis,
format,
Expand All @@ -353,6 +411,16 @@ export const TimeSeriesChartBase = forwardRef<ChartInstance, TimeChartProps>(fun
}
}
}
// A pinned exemplar tooltip is also unpinned when a tooltip is pinned in another chart,
// unless it is the one just pinned by this chart at these exact coordinates.
if (
pinnedExemplarPos !== null &&
lastTooltipPinnedCoords !== null &&
!isEqual(lastTooltipPinnedCoords, pinnedExemplarPos)
) {
setPinnedExemplar(null);
setPinnedExemplarPos(null);
}
// tooltipPinnedCoords CANNOT be in dep array or tooltip pinning breaks in the current chart's onClick
// eslint-disable-next-line react-hooks/exhaustive-deps
}, [lastTooltipPinnedCoords, seriesMapping]);
Expand All @@ -365,6 +433,45 @@ export const TimeSeriesChartBase = forwardRef<ChartInstance, TimeChartProps>(fun
// e.preventDefault(); // Prevent the default behaviour when right clicked
// }}
onClick={(e) => {
// Allows user to opt-in to multi tooltip pinning when Ctrl or Cmd key held down
const isControlKeyPressed = e.ctrlKey || e.metaKey;
if (isControlKeyPressed) {
e.preventDefault();
}

// If clicking while hovering an exemplar marker, toggle the exemplar tooltip pin
// instead of pinning the TimeChartTooltip. Pinning an exemplar tooltip unpins the
// pinned TimeChartTooltip, so only one tooltip stays pinned at a time unless
// Ctrl or Cmd is held down.
if (hoveredExemplar !== null && e.target instanceof HTMLCanvasElement) {
const pinnedPos: CursorCoordinates = {
page: { x: e.pageX, y: e.pageY },
client: { x: e.clientX, y: e.clientY },
plotCanvas: { x: e.nativeEvent.offsetX, y: e.nativeEvent.offsetY },
target: e.target,
};
const isUnpinClick = pinnedExemplar !== null && pinnedExemplar.exemplar === hoveredExemplar.exemplar;
// Compute the next state first and call the setters separately: updater functions
// may run more than once (e.g. StrictMode), so they must stay side-effect free.
setPinnedExemplar(isUnpinClick ? null : hoveredExemplar);
setPinnedExemplarPos(isUnpinClick ? null : pinnedPos);
if (!isUnpinClick && !isControlKeyPressed) {
// Unpin the pinned TimeChartTooltip and let adjacent charts know a tooltip is
// pinned at these coordinates, so only one tooltip is pinned at a time.
setTooltipPinnedCoords(null);
setPinnedCrosshair(null);
setLastTooltipPinnedCoords(pinnedPos);
}
return;
}

// Unpin a pinned exemplar tooltip when clicking elsewhere on the chart canvas,
// so the same click can pin the TimeChartTooltip instead. Ctrl or Cmd keeps both.
if (pinnedExemplar !== null && !isControlKeyPressed && e.target instanceof HTMLCanvasElement) {
setPinnedExemplar(null);
setPinnedExemplarPos(null);
}

// If clicking while hovering an annotation, toggle the annotation tooltip pin
// instead of pinning the TimeChartTooltip, so pinned TimeChartTooltip is preserved.
if (hoveredAnnotation !== null && e.target instanceof HTMLCanvasElement) {
Expand All @@ -385,12 +492,6 @@ export const TimeSeriesChartBase = forwardRef<ChartInstance, TimeChartProps>(fun
return;
}

// Allows user to opt-in to multi tooltip pinning when Ctrl or Cmd key held down
const isControlKeyPressed = e.ctrlKey || e.metaKey;
if (isControlKeyPressed) {
e.preventDefault();
}

// Determine where on chart canvas to plot pinned crosshair as markLine.
const pointInGrid = getPointInGrid(e.nativeEvent.offsetX, e.nativeEvent.offsetY, chartRef.current);
if (pointInGrid === null) {
Expand Down Expand Up @@ -467,6 +568,25 @@ export const TimeSeriesChartBase = forwardRef<ChartInstance, TimeChartProps>(fun
return;
}
const { clientX } = e;
// ECharts does not reliably emit mouseout when the cursor moves off an exemplar marker
// onto the plain plot area, which would keep the exemplar tooltip stuck on screen and
// hide the regular TimeChartTooltip. Clear the hovered exemplar as soon as the cursor
// is no longer within its marker, so the next hover can take over.
setHoveredExemplar((current) => {
if (current === null || chartRef.current === undefined) return current;
let markerPixel: number[] | undefined;
try {
// Use the plotted value so negated markers (negativeY) are tracked correctly.
markerPixel = chartRef.current.convertToPixel('grid', [current.exemplar.timestamp, current.plottedValue]);
} catch {
// Coordinates cannot be resolved (e.g. grid not ready yet), keep the current hover.
return current;
}
const [markerPixelX, markerPixelY] = markerPixel ?? [];
if (markerPixelX === undefined || markerPixelY === undefined) return current;
const distance = Math.hypot(e.nativeEvent.offsetX - markerPixelX, e.nativeEvent.offsetY - markerPixelY);
return distance <= EXEMPLAR_HOVER_RADIUS ? current : null;
});
if (isDragging) {
const deltaX = clientX - startX;
if (deltaX > 0) {
Expand All @@ -484,8 +604,9 @@ export const TimeSeriesChartBase = forwardRef<ChartInstance, TimeChartProps>(fun
if (tooltipPinnedCoords === null) {
setShowTooltip(false);
}
// Defensive: clear hovered annotation in case ECharts missed a mouseout event.
// Defensive: clear hovered annotation and exemplar in case ECharts missed a mouseout event.
setHoveredAnnotation(null);
setHoveredExemplar(null);
if (chartRef.current !== undefined) {
clearHighlightedSeries(chartRef.current);
}
Expand All @@ -509,9 +630,11 @@ export const TimeSeriesChartBase = forwardRef<ChartInstance, TimeChartProps>(fun
}}
>
{/* Allows overrides prop to hide custom tooltip and use the ECharts option.tooltip instead.
Keep the time chart tooltip visible when pinned even if user hovers an annotation. */}
Keep the time chart tooltip visible when pinned even if user hovers an annotation or exemplar,
but do not show the mouse-following tooltip on top of a pinned exemplar tooltip. */}
{showTooltip === true &&
(tooltipPinnedCoords !== null || hoveredAnnotation === null) &&
(tooltipPinnedCoords !== null ||
(pinnedExemplar === null && hoveredAnnotation === null && hoveredExemplar === null)) &&
(option.tooltip as TooltipComponentOption)?.showContent === false &&
tooltipConfig.hidden !== true && (
<TimeChartTooltip
Expand All @@ -532,6 +655,22 @@ export const TimeSeriesChartBase = forwardRef<ChartInstance, TimeChartProps>(fun
}}
/>
)}
{/* Pinned exemplar takes priority over hovered. While a TimeChartTooltip is pinned, the
mouse-following exemplar tooltip is not rendered so it does not appear on top of it. */}
{(pinnedExemplar !== null || (hoveredExemplar !== null && tooltipPinnedCoords === null)) && (
<ExemplarMetadataTooltip
exemplar={(pinnedExemplar ?? hoveredExemplar)!.exemplar}
seriesLabels={(pinnedExemplar ?? hoveredExemplar)!.seriesLabels}
containerId={chartsTheme.tooltipPortalContainerId}
format={format}
pinnedPos={pinnedExemplar !== null ? pinnedExemplarPos : null}
enablePinning={isPinningEnabled}
onUnpinClick={() => {
setPinnedExemplar(null);
setPinnedExemplarPos(null);
}}
/>
)}
{/* Pinned annotation takes priority over hovered. */}
{(pinnedAnnotation ?? hoveredAnnotation) && (
<AnnotationTooltip
Expand Down
Loading
Loading