forked from apache/superset
-
Notifications
You must be signed in to change notification settings - Fork 5
/
utils.js
247 lines (217 loc) · 7.64 KB
/
utils.js
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
import d3 from 'd3';
import d3tip from 'd3-tip';
import dompurify from 'dompurify';
import { getNumberFormatter } from '@superset-ui/number-format';
import { smartDateFormatter } from '@superset-ui/time-format';
const MAX_LABEL_LENGTH = 24;
// Regexp for the label added to time shifted series
// (1 hour offset, 2 days offset, etc.)
const TIME_SHIFT_PATTERN = /\d+ \w+ offset/;
export function cleanColorInput(value) {
// for superset series that should have the same color
return String(value).trim()
.split(', ')
.filter(k => !TIME_SHIFT_PATTERN.test(k))
.join(', ');
}
/**
* If format is smart_date, format date
* Otherwise, format number with the given format name
* @param {*} format
*/
export function getTimeOrNumberFormatter(format) {
return (format === 'smart_date')
? smartDateFormatter
: getNumberFormatter(format);
}
export function drawBarValues(svg, data, stacked, axisFormat) {
const format = getNumberFormatter(axisFormat);
const countSeriesDisplayed = data.length;
const totalStackedValues = stacked && data.length !== 0 ?
data[0].values.map(function (bar, iBar) {
const bars = data.map(series => series.values[iBar]);
return d3.sum(bars, d => d.y);
}) : [];
const groupLabels = svg.select('g.nv-barsWrap').append('g');
svg.selectAll('g.nv-group')
.filter((d, i) => !stacked || i === countSeriesDisplayed - 1)
.selectAll('rect')
.each(function (d, index) {
const rectObj = d3.select(this);
if (rectObj.attr('class').includes('positive')) {
const transformAttr = rectObj.attr('transform');
const yPos = parseFloat(rectObj.attr('y'));
const xPos = parseFloat(rectObj.attr('x'));
const rectWidth = parseFloat(rectObj.attr('width'));
const textEls = groupLabels.append('text')
.attr('y', yPos - 5)
.text(format(stacked ? totalStackedValues[index] : d.y))
.attr('transform', transformAttr)
.attr('class', 'bar-chart-label');
const labelWidth = textEls.node().getBBox().width;
textEls.attr('x', xPos + rectWidth / 2 - labelWidth / 2); // fine tune
}
});
}
// Formats the series key to account for a possible NULL value
function getFormattedKey(seriesKey, shouldDompurify) {
if (seriesKey === '<NULL>') {
return '<' + seriesKey.slice(1, -1) + '>';
}
return shouldDompurify ? dompurify.sanitize(seriesKey) : seriesKey;
}
// Custom sorted tooltip
// use a verbose formatter for times
export function generateRichLineTooltipContent(d, timeFormatter, valueFormatter) {
let tooltip = '';
tooltip += "<table><thead><tr><td colspan='3'>"
+ `<strong class='x-value'>${timeFormatter(d.value)}</strong>`
+ '</td></tr></thead><tbody>';
d.series.sort((a, b) => a.value >= b.value ? -1 : 1);
d.series.forEach((series) => {
const key = getFormattedKey(series.key, true);
tooltip += (
`<tr class="${series.highlight ? 'emph' : ''}">` +
`<td class='legend-color-guide' style="opacity: ${series.highlight ? '1' : '0.75'};"">` +
'<div ' +
`style="border: 2px solid ${series.highlight ? 'black' : 'transparent'}; background-color: ${series.color};"` +
'></div>' +
'</td>' +
`<td>${key}</td>` +
`<td>${valueFormatter(series.value)}</td>` +
'</tr>'
);
});
tooltip += '</tbody></table>';
return tooltip;
}
export function generateMultiLineTooltipContent(d, xFormatter, yFormatters) {
const tooltipTitle = xFormatter(d.value);
let tooltip = '';
tooltip += "<table><thead><tr><td colspan='3'>"
+ `<strong class='x-value'>${tooltipTitle}</strong>`
+ '</td></tr></thead><tbody>';
d.series.forEach((series, i) => {
const yFormatter = yFormatters[i];
const key = getFormattedKey(series.key, false);
tooltip += "<tr><td class='legend-color-guide'>"
+ `<div style="background-color: ${series.color};"></div></td>`
+ `<td class='key'>${key}</td>`
+ `<td class='value'>${yFormatter(series.value)}</td></tr>`;
});
tooltip += '</tbody></table>';
return tooltip;
}
function getLabel(stringOrObjectWithLabel) {
return stringOrObjectWithLabel.label || stringOrObjectWithLabel;
}
function createHTMLRow(col1, col2) {
return `<tr><td>${col1}</td><td>${col2}</td></tr>`;
}
export function generateBubbleTooltipContent({
point,
entity,
xField,
yField,
sizeField,
xFormatter,
yFormatter,
sizeFormatter,
}) {
let s = '<table>';
s += (
`<tr><td style="color: ${point.color};">` +
`<strong>${point[entity]}</strong> (${point.group})` +
'</td></tr>'
);
s += createHTMLRow(getLabel(xField), xFormatter(point.x));
s += createHTMLRow(getLabel(yField), yFormatter(point.y));
s += createHTMLRow(getLabel(sizeField), sizeFormatter(point.size));
s += '</table>';
return s;
}
export function hideTooltips() {
const target = document.querySelector('.nvtooltip');
if (target) {
target.style.opacity = 0;
}
}
export function wrapTooltip(chart, maxWidth) {
const tooltipLayer = chart.useInteractiveGuideline && chart.useInteractiveGuideline() ?
chart.interactiveLayer : chart;
const tooltipGeneratorFunc = tooltipLayer.tooltip.contentGenerator();
tooltipLayer.tooltip.contentGenerator((d) => {
let tooltip = `<div style="max-width: ${maxWidth * 0.5}px">`;
tooltip += tooltipGeneratorFunc(d);
tooltip += '</div>';
return tooltip;
});
}
export function tipFactory(layer) {
return d3tip()
.attr('class', 'd3-tip')
.direction('n')
.offset([-5, 0])
.html((d) => {
if (!d) {
return '';
}
const title = d[layer.titleColumn] && d[layer.titleColumn].length ?
d[layer.titleColumn] + ' - ' + layer.name :
layer.name;
const body = Array.isArray(layer.descriptionColumns) ?
layer.descriptionColumns.map(c => d[c]) : Object.values(d);
return '<div><strong>' + title + '</strong></div><br/>' +
'<div>' + body.join(', ') + '</div>';
});
}
export function getMaxLabelSize(svg, axisClass) {
// axis class = .nv-y2 // second y axis on dual line chart
// axis class = .nv-x // x axis on time series line chart
const tickTexts = svg.selectAll(`.${axisClass} g.tick text`);
if (tickTexts.length > 0) {
const lengths = tickTexts[0].map(text => text.getComputedTextLength());
return Math.ceil(Math.max(0, ...lengths));
}
return 0;
}
export function formatLabel(input, verboseMap = {}) {
// The input for label may be a string or an array of string
// When using the time shift feature, the label contains a '---' in the array
const verboseLookup = s => verboseMap[s] || s;
return (Array.isArray(input) && input.length)
? input.map(l => TIME_SHIFT_PATTERN.test(l) ? l : verboseLookup(l))
.join(', ')
: verboseLookup(input);
}
const MIN_BAR_WIDTH = 15;
export function computeBarChartWidth(data, stacked, maxWidth) {
const barCount = stacked
? d3.max(data, d => d.values.length)
: d3.sum(data, d => d.values.length);
const barWidth = barCount * MIN_BAR_WIDTH;
return Math.max(barWidth, maxWidth);
}
export function tryNumify(s) {
// Attempts casting to Number, returns string when failing
const n = Number(s);
return Number.isNaN(n) ? s : n;
}
export function stringifyTimeRange(extent) {
if (extent.some(d => d.toISOString === undefined)) {
return null;
}
return extent.map(d => d.toISOString()
.slice(0, -1))
.join(' : ');
}
export function setAxisShowMaxMin(axis, showminmax) {
if (axis && axis.showMaxMin && showminmax !== undefined) {
axis.showMaxMin(showminmax);
}
}
export function truncateLabel(text) {
return text.length > MAX_LABEL_LENGTH
? text.substr(0, MAX_LABEL_LENGTH - 1) + '…'
: text;
}