Skip to content
Merged
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
Original file line number Diff line number Diff line change
Expand Up @@ -27,6 +27,7 @@ import {
LegendState,
ensureIsArray,
} from '@superset-ui/core';
import { useTheme } from '@apache-superset/core/theme';
import type {
ECElementEvent,
ViewRootGroup,
Expand All @@ -35,6 +36,11 @@ import type GlobalModel from 'echarts/types/src/model/Global';
import type ComponentModel from 'echarts/types/src/model/Component';
import { EchartsHandler, EventHandlers } from '../types';
import Echart from '../components/Echart';
import {
rebaseSeriesData,
snapToNearestX,
SeriesDataPoint,
} from './percentChange';
import { OrientationType, TimeseriesChartTransformedProps } from './types';
import { formatSeriesName } from '../utils/series';
import { ExtraControls } from '../components/ExtraControls';
Expand Down Expand Up @@ -63,10 +69,149 @@ export default function EchartsTimeseries({
onLegendScroll,
}: TimeseriesChartTransformedProps) {
const { stack } = formData;
const theme = useTheme();
const echartRef = useRef<EchartsHandler | null>(null);
// eslint-disable-next-line no-param-reassign
refs.echartRef = echartRef;
const clickTimer = useRef<ReturnType<typeof setTimeout>>();

// Draggable percent-change baseline: when the rebase view is active, a
// vertical line is drawn on the plot; dragging it re-indexes every series
// to the hovered point via the composable rebase, entirely client-side.
const rebaseEnabled = Boolean(
(formData as { rebasePercentChange?: boolean }).rebasePercentChange,
);
// Persists the dragged baseline across effect reruns (e.g. resizes or
// other option changes) so those don't silently snap it back to the
// first point.
const baselineXRef = useRef<number | string | null>(null);
useEffect(() => {
if (!rebaseEnabled) return undefined;
const chart = echartRef.current?.getEchartInstance?.();
if (!chart) return undefined;

const option = chart.getOption() as {
series?: { data?: SeriesDataPoint[] }[];
};
const baseSeries = (option.series ?? []).map(s =>
Array.isArray(s.data)
? (s.data.filter(Array.isArray) as SeriesDataPoint[])
: [],
);
// Preserve the axis' native x type: numeric for time/value axes,
// string for category axes (coercing categories with Number() would
// turn them into NaN and break snapping/positioning below).
const xs = Array.from(new Set(baseSeries.flat().map(([x]) => x)));
if (xs.length === 0) return undefined;
if (typeof xs[0] === 'number') {
(xs as number[]).sort((a, b) => a - b);
}
let baselineX =
baselineXRef.current !== null && xs.includes(baselineXRef.current)
? baselineXRef.current
: xs[0];
baselineXRef.current = baselineX;
// Coalesces drag updates to at most one setOption per animation
// frame; rebasing every series on every raw pointer-move event
// can stutter on large charts.
let dragFrame: ReturnType<typeof requestAnimationFrame> | null = null;

const applyBaseline = (newX: number | string) => {
baselineX = newX;
baselineXRef.current = newX;
chart.setOption({
series: baseSeries.map(data => ({
data: rebaseSeriesData(data, newX),
})),
});
};

const drawHandle = () => {
// Cap the handle to the plot area so it doesn't run through the
// legend above or the axis labels below.
let gridRect = { top: 0, height: chart.getHeight() };
try {
const rect = (
chart as unknown as {
getModel: () => {
getComponent: (
type: string,
index: number,
) => {
coordinateSystem: {
getRect: () => { y: number; height: number };
};
};
};
}
)
.getModel()
.getComponent('grid', 0)
.coordinateSystem.getRect();
gridRect = { top: rect.y, height: rect.height };
} catch {
// fall back to the full chart height
}
let px: number;
try {
[px] = [chart.convertToPixel({ xAxisIndex: 0 }, baselineX) as number];
} catch {
return;
}
chart.setOption({
graphic: [
{
id: 'percent-change-baseline',
// only group elements support children in the graphic API
type: 'group',
x: px - 4,
y: gridRect.top,
cursor: 'ew-resize',
draggable: true,
z: 100,
ondrag(this: { x: number; y: number }) {
this.y = gridRect.top;
const dataX = chart.convertFromPixel(
{ xAxisIndex: 0 },
this.x + 4,
) as number | string;
if (dragFrame !== null) return;
dragFrame = requestAnimationFrame(() => {
dragFrame = null;
const snapped = snapToNearestX(xs, dataX);
if (snapped !== undefined && snapped !== baselineX) {
applyBaseline(snapped);
}
});
},
ondragend: () => drawHandle(),
children: [
{
type: 'rect',
shape: { x: 0, y: 0, width: 8, height: gridRect.height },
style: { fill: theme.colorFillSecondary },
},
{
type: 'rect',
shape: { x: 3, y: 0, width: 2, height: gridRect.height },
style: { fill: theme.colorTextSecondary },
},
],
},
],
});
};
drawHandle();

return () => {
if (dragFrame !== null) {
cancelAnimationFrame(dragFrame);
}
chart.setOption({
graphic: [{ id: 'percent-change-baseline', $action: 'remove' }],
});
};
}, [rebaseEnabled, echartOptions, width, height, theme]);
const extraControlRef = useRef<HTMLDivElement>(null);
const [extraControlHeight, setExtraControlHeight] = useState(0);
useEffect(() => {
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -106,6 +106,22 @@ const config: ControlPanelConfig = {
},
},
],
[
{
name: 'rebase_percent_change',
config: {
type: 'CheckboxControl',
label: t('Percent change'),
renderTrigger: true,
default: false,
description: t(
'Rebase each series to its percent change from a baseline ' +
'point, like the legacy Time-series Percent Change chart. ' +
'Drag the vertical baseline on the chart to re-index.',
),
},
},
],
[
{
name: 'markerEnabled',
Expand Down
Original file line number Diff line number Diff line change
@@ -0,0 +1,113 @@
/**
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
*/
import { DataRecord } from '@superset-ui/core';

/**
* Rebases every non-x column of a timeseries result to its percent change
* from that column's first non-null value, restoring the view the legacy
* nvd3 "Time-series Percent Change" chart computed in the renderer:
* y' = y / y0 - 1. Columns whose baseline is 0 (or missing) yield nulls
* since a percent change from zero is undefined.
*/
export function rebaseToPercentChange(
records: DataRecord[],
xAxis: string,
): DataRecord[] {
const baselines: Record<string, number> = {};
records.forEach(record => {
Object.entries(record).forEach(([key, value]) => {
if (
key !== xAxis &&
!(key in baselines) &&
typeof value === 'number' &&
!Number.isNaN(value)
) {
baselines[key] = value;
}
});
});

return records.map(record => {
const rebased: DataRecord = { [xAxis]: record[xAxis] };
Object.entries(record).forEach(([key, value]) => {
if (key === xAxis) return;
const baseline = baselines[key];
rebased[key] =
typeof value === 'number' &&
!Number.isNaN(value) &&
baseline !== undefined &&
baseline !== 0
? value / baseline - 1
: null;
});
return rebased;
});
}

export type SeriesDataPoint = [number | string, number | null];

/**
* Re-indexes already-rebased series data to a new baseline x. Because
* percent-change rebasing is composable, v' = (1 + v) / (1 + vk) - 1
* derives the new view directly from the currently displayed values,
* where vk is the series value at the nearest x at or before the new
* baseline (falling back to the first non-null point).
*/
export function rebaseSeriesData(
data: SeriesDataPoint[],
baselineX: number | string,
): SeriesDataPoint[] {
// the non-null point with the largest x at or before the baseline,
// falling back to the first non-null point
let baselineValue: number | null = null;
data.forEach(([x, y]) => {
if (y == null) return;
if (x <= baselineX || baselineValue === null) {
baselineValue = y;
}
});
if (baselineValue === null || baselineValue === -1) {
return data.map(([x]) => [x, null]);
}
const divisor = 1 + baselineValue;
return data.map(([x, y]) => [x, y == null ? null : (1 + y) / divisor - 1]);
}

/**
* Snaps a dragged x position to the nearest available data x. Time/value
* axes report a continuous pixel-derived number, so the nearest point is
* found by numeric distance. Category axes report the exact category
* value already snapped by ECharts; there's no numeric scale to measure
* distance against, so it's only validated against the known x values
* (falling back to the first one if the pixel landed outside the axis).
*/
export function snapToNearestX(
xs: (number | string)[],
target: number | string,
): number | string | undefined {
if (xs.length === 0) return undefined;
if (typeof target === 'string') {
return xs.includes(target) ? target : xs[0];
}
const numericXs = xs.filter((x): x is number => typeof x === 'number');
if (numericXs.length === 0) return undefined;
return numericXs.reduce((best, x) =>
Math.abs(x - target) < Math.abs(best - target) ? x : best,
);
}
Original file line number Diff line number Diff line change
Expand Up @@ -18,6 +18,7 @@
*/
/* eslint-disable camelcase */
import { invert } from 'lodash-es';
import { rebaseToPercentChange } from './percentChange';
import { t } from '@apache-superset/core/translation';
import {
AnnotationLayer,
Expand Down Expand Up @@ -290,14 +291,24 @@ export default function transformProps(
return { ...acc, [entry[0]]: entry[1] };
}, {});
const colorScale = CategoricalColorNamespace.getScale(colorScheme as string);
const rebasedData = rebaseForecastDatum(data, verboseMap);
const forecastRebasedData = rebaseForecastDatum(data, verboseMap);
let xAxisLabel = getXAxisLabel(chartProps.rawFormData) as string;
if (
isPhysicalColumn(chartProps.rawFormData?.x_axis) &&
isDefined(verboseMap[xAxisLabel])
) {
xAxisLabel = verboseMap[xAxisLabel];
}
// Restores the legacy nvd3 "Time-series Percent Change" view: every series
// rebased client-side to its percent change from the first point. The
// baseline can be re-indexed interactively via the draggable line the
// chart component installs.
const rebasePercentChange = Boolean(
(formData as { rebasePercentChange?: boolean }).rebasePercentChange,
);
const rebasedData = rebasePercentChange
? rebaseToPercentChange(forecastRebasedData, xAxisLabel)
: forecastRebasedData;
const isHorizontal = orientation === OrientationType.Horizontal;
const { totalStackedValues, thresholdValues } = extractDataTotalValues(
rebasedData,
Expand Down Expand Up @@ -349,7 +360,9 @@ export default function transformProps(
const isAreaExpand = stack === StackControlsValue.Expand;
const series: SeriesOption[] = [];

const forcePercentFormatter = Boolean(contributionMode || isAreaExpand);
const forcePercentFormatter = Boolean(
contributionMode || isAreaExpand || rebasePercentChange,
);
const percentFormatter = forcePercentFormatter
? getPercentFormatter(yAxisFormat)
: getPercentFormatter(NumberFormats.PERCENT_2_POINT);
Expand Down
Loading
Loading