Skip to content

Commit

Permalink
feat: Utility function to render chart tooltips (apache#27950)
Browse files Browse the repository at this point in the history
  • Loading branch information
michael-s-molina authored May 7, 2024
1 parent 281d7f1 commit 46365a2
Show file tree
Hide file tree
Showing 23 changed files with 512 additions and 425 deletions.
Original file line number Diff line number Diff line change
Expand Up @@ -32,3 +32,4 @@ export * from './featureFlags';
export * from './random';
export * from './typedMemo';
export * from './html';
export * from './tooltip';
57 changes: 57 additions & 0 deletions superset-frontend/packages/superset-ui-core/src/utils/tooltip.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,57 @@
/**
* 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 { t } from '../translation';

const TRUNCATION_STYLE = `
max-width: 300px;
overflow: hidden;
text-overflow: ellipsis;
`;

export function tooltipHtml(
data: string[][],
title?: string,
focusedRow?: number,
) {
const titleRow = title
? `<span style="font-weight: 700;${TRUNCATION_STYLE}">${title}</span>`
: '';
return `
<div>
${titleRow}
<table>
${data.length === 0 ? `<tr><td>${t('No data')}</td></tr>` : ''}
${data
.map((row, i) => {
const rowStyle =
i === focusedRow ? 'font-weight: 700;' : 'opacity: 0.8;';
const cells = row.map((cell, j) => {
const cellStyle = `
text-align: ${j > 0 ? 'right' : 'left'};
padding-left: ${j === 0 ? 0 : 16}px;
${TRUNCATION_STYLE}
`;
return `<td style="${cellStyle}">${cell}</td>`;
});
return `<tr style="${rowStyle}">${cells.join('')}</tr>`;
})
.join('')}
</table>
</div>`;
}
115 changes: 115 additions & 0 deletions superset-frontend/packages/superset-ui-core/test/utils/tooltip.test.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,115 @@
/**
* 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 { tooltipHtml } from '@superset-ui/core';

const TITLE_STYLE =
'style="font-weight: 700;max-width:300px;overflow:hidden;text-overflow:ellipsis;"';
const TR_STYLE = 'style="opacity:0.8;"';
const TR_FOCUS_STYLE = 'style="font-weight:700;"';
const TD_TEXT_STYLE =
'style="text-align:left;padding-left:0px;max-width:300px;overflow:hidden;text-overflow:ellipsis;"';
const TD_NUMBER_STYLE =
'style="text-align:right;padding-left:16px;max-width:300px;overflow:hidden;text-overflow:ellipsis;"';

const data = [
['a', 'b', 'c'],
['1', '2', '3'],
];

function removeWhitespaces(text: string) {
return text.replace(/\s/g, '');
}

test('should return a table with the given data', () => {
const title = 'Title';
const html = removeWhitespaces(tooltipHtml(data, title));
const expectedHtml = removeWhitespaces(`
<div>
<span ${TITLE_STYLE}>Title</span>
<table>
<tr ${TR_STYLE}>
<td ${TD_TEXT_STYLE}>a</td>
<td ${TD_NUMBER_STYLE}>b</td>
<td ${TD_NUMBER_STYLE}>c</td>
</tr>
<tr ${TR_STYLE}>
<td ${TD_TEXT_STYLE}>1</td>
<td ${TD_NUMBER_STYLE}>2</td>
<td ${TD_NUMBER_STYLE}>3</td>
</tr>
</table>
</div>`);
expect(html).toMatch(expectedHtml);
});

test('should return a table with the given data and a focused row', () => {
const title = 'Title';
const focusedRow = 1;
const html = removeWhitespaces(tooltipHtml(data, title, focusedRow));
const expectedHtml = removeWhitespaces(`
<div>
<span ${TITLE_STYLE}>Title</span>
<table>
<tr ${TR_STYLE}>
<td ${TD_TEXT_STYLE}>a</td>
<td ${TD_NUMBER_STYLE}>b</td>
<td ${TD_NUMBER_STYLE}>c</td>
</tr>
<tr ${TR_FOCUS_STYLE}>
<td ${TD_TEXT_STYLE}>1</td>
<td ${TD_NUMBER_STYLE}>2</td>
<td ${TD_NUMBER_STYLE}>3</td>
</tr>
</table>
</div>`);
expect(html).toMatch(expectedHtml);
});

test('should return a table with no data', () => {
const title = 'Title';
const html = removeWhitespaces(tooltipHtml([], title));
const expectedHtml = removeWhitespaces(`
<div>
<span ${TITLE_STYLE}>Title</span>
<table>
<tr><td>No data</td></tr>
</table>
</div>`);
expect(html).toMatch(expectedHtml);
});

test('should return a table with the given data and no title', () => {
const html = removeWhitespaces(tooltipHtml(data));
const expectedHtml = removeWhitespaces(`
<div>
<table>
<tr ${TR_STYLE}>
<td ${TD_TEXT_STYLE}>a</td>
<td ${TD_NUMBER_STYLE}>b</td>
<td ${TD_NUMBER_STYLE}>c</td>
</tr>
<tr ${TR_STYLE}>
<td ${TD_TEXT_STYLE}>1</td>
<td ${TD_NUMBER_STYLE}>2</td>
<td ${TD_NUMBER_STYLE}>3</td>
</tr>
</table>
</div>`);
expect(html).toMatch(expectedHtml);
});
Original file line number Diff line number Diff line change
Expand Up @@ -22,13 +22,11 @@ import {
NumberFormats,
GenericDataType,
getMetricLabel,
t,
smartDateVerboseFormatter,
TimeFormatter,
getXAxisLabel,
Metric,
ValueFormatter,
getValueFormatter,
t,
tooltipHtml,
} from '@superset-ui/core';
import { EChartsCoreOption, graphic } from 'echarts';
import {
Expand All @@ -41,24 +39,6 @@ import { getDateFormatter, parseMetricValue } from '../utils';
import { getDefaultTooltip } from '../../utils/tooltip';
import { Refs } from '../../types';

const defaultNumberFormatter = getNumberFormatter();
export function renderTooltipFactory(
formatDate: TimeFormatter = smartDateVerboseFormatter,
formatValue: ValueFormatter | TimeFormatter = defaultNumberFormatter,
) {
return function renderTooltip(params: { data: TimeSeriesDatum }[]) {
return `
${formatDate(params[0].data[0])}
<br />
<strong>
${
params[0].data[1] === null ? t('N/A') : formatValue(params[0].data[1])
}
</strong>
`;
};
}

const formatPercentChange = getNumberFormatter(
NumberFormats.PERCENT_SIGNED_1_POINT,
);
Expand Down Expand Up @@ -249,7 +229,18 @@ export default function transformProps(
...getDefaultTooltip(refs),
show: !inContextMenu,
trigger: 'axis',
formatter: renderTooltipFactory(formatTime, headerFormatter),
formatter: (params: { data: TimeSeriesDatum }[]) =>
tooltipHtml(
[
[
metricName,
params[0].data[1] === null
? t('N/A')
: headerFormatter.format(params[0].data[1]),
],
],
formatTime(params[0].data[0]),
),
},
aria: {
enabled: true,
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -24,6 +24,7 @@ import {
AxisType,
getMetricLabel,
NumberFormatter,
tooltipHtml,
} from '@superset-ui/core';
import { EchartsBubbleChartProps, EchartsBubbleFormData } from './types';
import { DEFAULT_FORM_DATA, MINIMUM_BUBBLE_SIZE } from './constants';
Expand Down Expand Up @@ -60,13 +61,17 @@ export function formatTooltip(
tooltipSizeFormatter: NumberFormatter,
) {
const title = params.data[4]
? `${params.data[3]} </br> ${params.data[4]}`
? `${params.data[4]} (${params.data[3]})`
: params.data[3];

return `<p>${title}</p>
${xAxisLabel}: ${xAxisFormatter(params.data[0])} <br/>
${yAxisLabel}: ${yAxisFormatter(params.data[1])} <br/>
${sizeLabel}: ${tooltipSizeFormatter(params.data[2])}`;
return tooltipHtml(
[
[xAxisLabel, xAxisFormatter(params.data[0])],
[yAxisLabel, yAxisFormatter(params.data[1])],
[sizeLabel, tooltipSizeFormatter(params.data[2])],
],
title,
);
}

export default function transformProps(chartProps: EchartsBubbleChartProps) {
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -24,6 +24,7 @@ import {
getNumberFormatter,
getValueFormatter,
NumberFormats,
tooltipHtml,
ValueFormatter,
} from '@superset-ui/core';
import { CallbackDataParams } from 'echarts/types/src/util/types';
Expand All @@ -50,19 +51,17 @@ import { Refs } from '../types';

const percentFormatter = getNumberFormatter(NumberFormats.PERCENT_2_POINT);

export function formatFunnelLabel({
export function parseParams({
params,
labelType,
numberFormatter,
percentCalculationType = PercentCalcType.FirstStep,
sanitizeName = false,
}: {
params: Pick<CallbackDataParams, 'name' | 'value' | 'percent' | 'data'>;
labelType: EchartsFunnelLabelTypeType;
numberFormatter: ValueFormatter;
percentCalculationType?: PercentCalcType;
sanitizeName?: boolean;
}): string {
}) {
const { name: rawName = '', value, percent: totalPercent, data } = params;
const name = sanitizeName ? sanitizeHtml(rawName) : rawName;
const formattedValue = numberFormatter(value as number);
Expand All @@ -80,25 +79,7 @@ export function formatFunnelLabel({
percent = firstStepPercent ?? 0;
}
const formattedPercent = percentFormatter(percent);

switch (labelType) {
case EchartsFunnelLabelTypeType.Key:
return name;
case EchartsFunnelLabelTypeType.Value:
return formattedValue;
case EchartsFunnelLabelTypeType.Percent:
return formattedPercent;
case EchartsFunnelLabelTypeType.KeyValue:
return `${name}: ${formattedValue}`;
case EchartsFunnelLabelTypeType.KeyValuePercent:
return `${name}: ${formattedValue} (${formattedPercent})`;
case EchartsFunnelLabelTypeType.KeyPercent:
return `${name}: ${formattedPercent}`;
case EchartsFunnelLabelTypeType.ValuePercent:
return `${formattedValue} (${formattedPercent})`;
default:
return name;
}
return [name, formattedValue, formattedPercent];
}

export default function transformProps(
Expand Down Expand Up @@ -216,13 +197,31 @@ export default function transformProps(
{},
);

const formatter = (params: CallbackDataParams) =>
formatFunnelLabel({
const formatter = (params: CallbackDataParams) => {
const [name, formattedValue, formattedPercent] = parseParams({
params,
numberFormatter,
labelType,
percentCalculationType,
});
switch (labelType) {
case EchartsFunnelLabelTypeType.Key:
return name;
case EchartsFunnelLabelTypeType.Value:
return formattedValue;
case EchartsFunnelLabelTypeType.Percent:
return formattedPercent;
case EchartsFunnelLabelTypeType.KeyValue:
return `${name}: ${formattedValue}`;
case EchartsFunnelLabelTypeType.KeyValuePercent:
return `${name}: ${formattedValue} (${formattedPercent})`;
case EchartsFunnelLabelTypeType.KeyPercent:
return `${name}: ${formattedPercent}`;
case EchartsFunnelLabelTypeType.ValuePercent:
return `${formattedValue} (${formattedPercent})`;
default:
return name;
}
};

const defaultLabel = {
formatter,
Expand Down Expand Up @@ -266,13 +265,26 @@ export default function transformProps(
...getDefaultTooltip(refs),
show: !inContextMenu && showTooltipLabels,
trigger: 'item',
formatter: (params: any) =>
formatFunnelLabel({
formatter: (params: any) => {
const [name, formattedValue, formattedPercent] = parseParams({
params,
numberFormatter,
labelType: tooltipLabelType,
percentCalculationType,
}),
});
const row = [];
const enumName = EchartsFunnelLabelTypeType[tooltipLabelType];
const title = enumName.includes('Key') ? name : undefined;
if (enumName.includes('Value') || enumName.includes('Percent')) {
row.push(metricLabel);
}
if (enumName.includes('Value')) {
row.push(formattedValue);
}
if (enumName.includes('Percent')) {
row.push(formattedPercent);
}
return tooltipHtml([row], title);
},
},
legend: {
...getLegendProps(legendType, legendOrientation, showLegend, theme),
Expand Down
Loading

0 comments on commit 46365a2

Please sign in to comment.