Tidy up .js files based on static analysis from jshint

This commit is contained in:
Sam Starling 2015-11-11 20:04:37 +01:00
parent 307d9fad46
commit 1901875595
3 changed files with 93 additions and 94 deletions

View File

@ -1,7 +1,7 @@
function init() { function init() {
$(".alert_header").click(function() { $(".alert_header").click(function() {
var expanderIcon = $(this).find("i.icon-chevron-down"); var expanderIcon = $(this).find("i.icon-chevron-down");
if (expanderIcon.length != 0) { if (expanderIcon.length !== 0) {
expanderIcon.removeClass("icon-chevron-down").addClass("icon-chevron-up"); expanderIcon.removeClass("icon-chevron-down").addClass("icon-chevron-up");
} else { } else {
var collapserIcon = $(this).find("i.icon-chevron-up"); var collapserIcon = $(this).find("i.icon-chevron-up");

View File

@ -37,10 +37,10 @@ Prometheus.Graph.prototype.initialize = function() {
self.id = Prometheus.Graph.numGraphs++; self.id = Prometheus.Graph.numGraphs++;
// Set default options. // Set default options.
self.options["id"] = self.id; self.options.id = self.id;
self.options["range_input"] = self.options["range_input"] || "1h"; self.options.range_input = self.options.range_input || "1h";
if (self.options["tab"] === undefined) { if (self.options.tab === undefined) {
self.options["tab"] = 1; self.options.tab = 1;
} }
// Draw graph controls and container from Handlebars template. // Draw graph controls and container from Handlebars template.
@ -79,10 +79,10 @@ Prometheus.Graph.prototype.initialize = function() {
self.graphTab = graphWrapper.find(".graph_container"); self.graphTab = graphWrapper.find(".graph_container");
self.tabs = graphWrapper.find("a[data-toggle='tab']"); self.tabs = graphWrapper.find("a[data-toggle='tab']");
self.tabs.eq(self.options["tab"]).tab("show"); self.tabs.eq(self.options.tab).tab("show");
self.tabs.on("shown.bs.tab", function(e) { self.tabs.on("shown.bs.tab", function(e) {
var target = $(e.target); var target = $(e.target);
self.options["tab"] = target.parent().index(); self.options.tab = target.parent().index();
storeGraphOptionsInURL(); storeGraphOptionsInURL();
if ($("#" + target.attr("aria-controls")).hasClass("reload")) { if ($("#" + target.attr("aria-controls")).hasClass("reload")) {
self.submitQuery(); self.submitQuery();
@ -102,11 +102,11 @@ Prometheus.Graph.prototype.initialize = function() {
language: 'en', language: 'en',
pickSeconds: false, pickSeconds: false,
}); });
if (self.options["end_input"]) { if (self.options.end_input) {
self.endDate.data('datetimepicker').setValue(self.options["end_input"]); self.endDate.data('datetimepicker').setValue(self.options.end_input);
} }
self.endDate.change(function() { self.submitQuery() }); self.endDate.change(function() { self.submitQuery(); });
self.refreshInterval.change(function() { self.updateRefresh() }); self.refreshInterval.change(function() { self.updateRefresh(); });
self.isStacked = function() { self.isStacked = function() {
return self.stacked.val() === '1'; return self.stacked.val() === '1';
@ -237,7 +237,7 @@ Prometheus.Graph.prototype.populateAutocompleteMetrics = function() {
dataType: "json", dataType: "json",
success: function(json, textStatus) { success: function(json, textStatus) {
if (json.status !== "success") { if (json.status !== "success") {
self.showError("Error loading available metrics!") self.showError("Error loading available metrics!");
return; return;
} }
@ -302,20 +302,20 @@ Prometheus.Graph.prototype.getOptions = function() {
]; ];
self.queryForm.find("input").each(function(index, element) { self.queryForm.find("input").each(function(index, element) {
var name = element.name; var name = element.name;
if ($.inArray(name, optionInputs) >= 0) { if ($.inArray(name, optionInputs) >= 0) {
options[name] = element.value; options[name] = element.value;
} }
}); });
options["expr"] = self.expr.val(); options.expr = self.expr.val();
options["tab"] = self.options["tab"]; options.tab = self.options.tab;
return options; return options;
}; };
Prometheus.Graph.prototype.parseDuration = function(rangeText) { Prometheus.Graph.prototype.parseDuration = function(rangeText) {
var rangeRE = new RegExp("^([0-9]+)([ywdhms]+)$"); var rangeRE = new RegExp("^([0-9]+)([ywdhms]+)$");
var matches = rangeText.match(rangeRE); var matches = rangeText.match(rangeRE);
if (!matches) { return }; if (!matches) { return; }
if (matches.length != 3) { if (matches.length != 3) {
return 60; return 60;
} }
@ -365,7 +365,7 @@ Prometheus.Graph.prototype.getOrSetEndDate = function() {
var date = self.getEndDate(); var date = self.getEndDate();
self.setEndDate(date); self.setEndDate(date);
return date; return date;
} };
Prometheus.Graph.prototype.setEndDate = function(date) { Prometheus.Graph.prototype.setEndDate = function(date) {
var self = this; var self = this;
@ -374,13 +374,13 @@ Prometheus.Graph.prototype.setEndDate = function(date) {
Prometheus.Graph.prototype.increaseEnd = function() { Prometheus.Graph.prototype.increaseEnd = function() {
var self = this; var self = this;
self.setEndDate(new Date(self.getOrSetEndDate() + self.parseDuration(self.rangeInput.val()) * 1000/2 )) // increase by 1/2 range & convert ms in s self.setEndDate(new Date(self.getOrSetEndDate() + self.parseDuration(self.rangeInput.val()) * 1000/2 )); // increase by 1/2 range & convert ms in s
self.submitQuery(); self.submitQuery();
}; };
Prometheus.Graph.prototype.decreaseEnd = function() { Prometheus.Graph.prototype.decreaseEnd = function() {
var self = this; var self = this;
self.setEndDate(new Date(self.getOrSetEndDate() - self.parseDuration(self.rangeInput.val()) * 1000/2 )) self.setEndDate(new Date(self.getOrSetEndDate() - self.parseDuration(self.rangeInput.val()) * 1000/2 ));
self.submitQuery(); self.submitQuery();
}; };
@ -407,14 +407,14 @@ Prometheus.Graph.prototype.submitQuery = function() {
var params = { var params = {
"query": self.expr.val() "query": self.expr.val()
}; };
if (self.options["tab"] === 0) { if (self.options.tab === 0) {
params['start'] = endDate - rangeSeconds; params.start = endDate - rangeSeconds;
params['end'] = endDate; params.end = endDate;
params['step'] = resolution; params.step = resolution;
url = PATH_PREFIX + "/api/v1/query_range"; url = PATH_PREFIX + "/api/v1/query_range";
success = function(json, textStatus) { self.handleGraphResponse(json, textStatus); }; success = function(json, textStatus) { self.handleGraphResponse(json, textStatus); };
} else { } else {
params['time'] = startTime / 1000; params.time = startTime / 1000;
url = PATH_PREFIX + "/api/v1/query"; url = PATH_PREFIX + "/api/v1/query";
success = function(json, textStatus) { self.handleConsoleResponse(json, textStatus); }; success = function(json, textStatus) { self.handleConsoleResponse(json, textStatus); };
} }
@ -454,13 +454,13 @@ Prometheus.Graph.prototype.showError = function(msg) {
var self = this; var self = this;
self.error.text(msg); self.error.text(msg);
self.error.show(); self.error.show();
} };
Prometheus.Graph.prototype.clearError = function(msg) { Prometheus.Graph.prototype.clearError = function(msg) {
var self = this; var self = this;
self.error.text(''); self.error.text('');
self.error.hide(); self.error.hide();
} };
Prometheus.Graph.prototype.updateRefresh = function() { Prometheus.Graph.prototype.updateRefresh = function() {
var self = this; var self = this;
@ -470,30 +470,30 @@ Prometheus.Graph.prototype.updateRefresh = function() {
} }
interval = self.parseDuration(self.refreshInterval.val()); interval = self.parseDuration(self.refreshInterval.val());
if (!interval) { return }; if (!interval) { return; }
self.timeoutID = window.setTimeout(function() { self.timeoutID = window.setTimeout(function() {
self.submitQuery(); self.submitQuery();
self.updateRefresh(); self.updateRefresh();
}, interval * SECOND); }, interval * SECOND);
} };
Prometheus.Graph.prototype.renderLabels = function(labels) { Prometheus.Graph.prototype.renderLabels = function(labels) {
var labelStrings = []; var labelStrings = [];
for (label in labels) { for (var label in labels) {
if (label != "__name__") { if (label != "__name__") {
labelStrings.push("<strong>" + label + "</strong>: " + escapeHTML(labels[label])); labelStrings.push("<strong>" + label + "</strong>: " + escapeHTML(labels[label]));
} }
} }
return labels = "<div class=\"labels\">" + labelStrings.join("<br>") + "</div>"; return labels = "<div class=\"labels\">" + labelStrings.join("<br>") + "</div>";
} };
Prometheus.Graph.prototype.metricToTsName = function(labels) { Prometheus.Graph.prototype.metricToTsName = function(labels) {
var tsName = (labels["__name__"] || '') + "{"; var tsName = (labels.__name__ || '') + "{";
var labelStrings = []; var labelStrings = [];
for (label in labels) { for (var label in labels) {
if (label != "__name__") { if (label != "__name__") {
labelStrings.push(label + "=\"" + labels[label] + "\""); labelStrings.push(label + "=\"" + labels[label] + "\"");
} }
} }
tsName += labelStrings.join(",") + "}"; tsName += labelStrings.join(",") + "}";
@ -505,7 +505,7 @@ Prometheus.Graph.prototype.parseValue = function(value) {
if (isNaN(val)) { if (isNaN(val)) {
// "+Inf", "-Inf", "+Inf" will be parsed into NaN by parseFloat(). The // "+Inf", "-Inf", "+Inf" will be parsed into NaN by parseFloat(). The
// can't be graphed, so show them as gaps (null). // can't be graphed, so show them as gaps (null).
return null return null;
} }
return val; return val;
}; };
@ -534,7 +534,7 @@ Prometheus.Graph.prototype.transformData = function(json) {
return { return {
x: value[0], x: value[0],
y: self.parseValue(value[1]) y: self.parseValue(value[1])
} };
}), }),
color: palette.color() color: palette.color()
}; };
@ -545,7 +545,7 @@ Prometheus.Graph.prototype.transformData = function(json) {
Prometheus.Graph.prototype.updateGraph = function() { Prometheus.Graph.prototype.updateGraph = function() {
var self = this; var self = this;
if (self.data.length == 0) { return; } if (self.data.length === 0) { return; }
// Remove any traces of an existing graph. // Remove any traces of an existing graph.
self.legend.empty(); self.legend.empty();
@ -599,7 +599,7 @@ Prometheus.Graph.prototype.updateGraph = function() {
graph: self.rickshawGraph, graph: self.rickshawGraph,
formatter: function(series, x, y) { formatter: function(series, x, y) {
var swatch = '<span class="detail_swatch" style="background-color: ' + series.color + '"></span>'; var swatch = '<span class="detail_swatch" style="background-color: ' + series.color + '"></span>';
var content = swatch + (series.labels["__name__"] || 'value') + ": <strong>" + y + '</strong><br>'; var content = swatch + (series.labels.__name__ || 'value') + ": <strong>" + y + '</strong><br>';
return content + self.renderLabels(series.labels); return content + self.renderLabels(series.labels);
} }
}); });
@ -624,28 +624,28 @@ Prometheus.Graph.prototype.updateGraph = function() {
Prometheus.Graph.prototype.resizeGraph = function() { Prometheus.Graph.prototype.resizeGraph = function() {
var self = this; var self = this;
if (self.rickshawGraph != null) { if (self.rickshawGraph !== null) {
self.rickshawGraph.configure({ self.rickshawGraph.configure({
width: Math.max(self.graph.innerWidth() - 80, 200), width: Math.max(self.graph.innerWidth() - 80, 200),
}); });
self.rickshawGraph.render(); self.rickshawGraph.render();
} }
} };
Prometheus.Graph.prototype.handleGraphResponse = function(json, textStatus) { Prometheus.Graph.prototype.handleGraphResponse = function(json, textStatus) {
var self = this var self = this;
// Rickshaw mutates passed series data for stacked graphs, so we need to save // Rickshaw mutates passed series data for stacked graphs, so we need to save
// the original AJAX response in order to re-transform it into series data // the original AJAX response in order to re-transform it into series data
// when the user disables the stacking. // when the user disables the stacking.
self.graphJSON = json; self.graphJSON = json;
self.data = self.transformData(json); self.data = self.transformData(json);
if (self.data.length == 0) { if (self.data.length === 0) {
self.showError("No datapoints found."); self.showError("No datapoints found.");
return; return;
} }
self.graphTab.removeClass("reload"); self.graphTab.removeClass("reload");
self.updateGraph(); self.updateGraph();
} };
Prometheus.Graph.prototype.handleConsoleResponse = function(data, textStatus) { Prometheus.Graph.prototype.handleConsoleResponse = function(data, textStatus) {
var self = this; var self = this;
@ -679,7 +679,7 @@ Prometheus.Graph.prototype.handleConsoleResponse = function(data, textStatus) {
for (var j = 0; j < v.values.length; j++) { for (var j = 0; j < v.values.length; j++) {
valueText += v.values[j][1] + " @" + v.values[j][0] + "<br/>"; valueText += v.values[j][1] + " @" + v.values[j][0] + "<br/>";
} }
tBody.append("<tr><td>" + escapeHTML(tsName) + "</td><td>" + valueText + "</td></tr>") tBody.append("<tr><td>" + escapeHTML(tsName) + "</td><td>" + valueText + "</td></tr>");
} }
break; break;
case "scalar": case "scalar":
@ -692,7 +692,7 @@ Prometheus.Graph.prototype.handleConsoleResponse = function(data, textStatus) {
self.showError("Unsupported value type!"); self.showError("Unsupported value type!");
break; break;
} }
} };
function parseGraphOptionsFromURL() { function parseGraphOptionsFromURL() {
var hashOptions = window.location.hash.slice(1); var hashOptions = window.location.hash.slice(1);
@ -750,7 +750,7 @@ function init() {
success: function(data) { success: function(data) {
graphTemplate = Handlebars.compile(data); graphTemplate = Handlebars.compile(data);
var options = parseGraphOptionsFromURL(); var options = parseGraphOptionsFromURL();
if (options.length == 0) { if (options.length === 0) {
options.push({}); options.push({});
} }
for (var i = 0; i < options.length; i++) { for (var i = 0; i < options.length; i++) {
@ -758,7 +758,7 @@ function init() {
} }
$("#add_graph").click(function() { addGraph({}); }); $("#add_graph").click(function() { addGraph({}); });
} }
}) });
} }
$(init); $(init);

View File

@ -17,7 +17,7 @@ PromConsole._stripTrailingZero = function(x) {
return x.replace(/\.?0*$/, ''); return x.replace(/\.?0*$/, '');
} }
return x; return x;
} };
// Humanize a number. // Humanize a number.
PromConsole.NumberFormatter.humanize = function(x) { PromConsole.NumberFormatter.humanize = function(x) {
@ -30,7 +30,7 @@ PromConsole.NumberFormatter.humanize = function(x) {
return x.toExponential(3) + prefix; return x.toExponential(3) + prefix;
} }
return PromConsole._stripTrailingZero(x.toFixed(3)) + prefix; return PromConsole._stripTrailingZero(x.toFixed(3)) + prefix;
} };
// Humanize a number, don't use milli/micro/etc. prefixes. // Humanize a number, don't use milli/micro/etc. prefixes.
PromConsole.NumberFormatter.humanizeNoSmallPrefix = function(x) { PromConsole.NumberFormatter.humanizeNoSmallPrefix = function(x) {
@ -43,7 +43,7 @@ PromConsole.NumberFormatter.humanizeNoSmallPrefix = function(x) {
x = ret[0]; x = ret[0];
var prefix = ret[1]; var prefix = ret[1];
return PromConsole._stripTrailingZero(x.toFixed(3)) + prefix; return PromConsole._stripTrailingZero(x.toFixed(3)) + prefix;
} };
// Humanize a number with 1024 as the base, rather than 1000. // Humanize a number with 1024 as the base, rather than 1000.
PromConsole.NumberFormatter.humanize1024 = function(x) { PromConsole.NumberFormatter.humanize1024 = function(x) {
@ -56,7 +56,7 @@ PromConsole.NumberFormatter.humanize1024 = function(x) {
return x.toExponential(3) + prefix; return x.toExponential(3) + prefix;
} }
return PromConsole._stripTrailingZero(x.toFixed(3)) + prefix; return PromConsole._stripTrailingZero(x.toFixed(3)) + prefix;
} };
// Humanize a number, returning an exact representation. // Humanize a number, returning an exact representation.
PromConsole.NumberFormatter.humanizeExact = function(x) { PromConsole.NumberFormatter.humanizeExact = function(x) {
@ -64,11 +64,11 @@ PromConsole.NumberFormatter.humanizeExact = function(x) {
x, PromConsole.NumberFormatter.prefixesBig, x, PromConsole.NumberFormatter.prefixesBig,
PromConsole.NumberFormatter.prefixesSmall, 1000); PromConsole.NumberFormatter.prefixesSmall, 1000);
return ret[0] + ret[1]; return ret[0] + ret[1];
} };
PromConsole.NumberFormatter._humanize = function(x, prefixesBig, prefixesSmall, factor) { PromConsole.NumberFormatter._humanize = function(x, prefixesBig, prefixesSmall, factor) {
var prefix = "" var prefix = "";
if (x == 0) { if (x === 0) {
/* Do nothing. */ /* Do nothing. */
} else if (Math.abs(x) >= 1) { } else if (Math.abs(x) >= 1) {
for (var i=0; i < prefixesBig.length && Math.abs(x) >= factor; ++i) { for (var i=0; i < prefixesBig.length && Math.abs(x) >= factor; ++i) {
@ -113,7 +113,7 @@ PromConsole.TimeControl = function() {
this.endElement.value = PromConsole.TimeControl.prototype.getHumanDate( this.endElement.value = PromConsole.TimeControl.prototype.getHumanDate(
new Date(PromConsole.TimeControl._initialValues.endTime * 1000)); new Date(PromConsole.TimeControl._initialValues.endTime * 1000));
} }
} };
PromConsole.TimeControl.timeFactors = { PromConsole.TimeControl.timeFactors = {
"y": 60 * 60 * 24 * 365, "y": 60 * 60 * 24 * 365,
@ -134,11 +134,11 @@ PromConsole.TimeControl.prototype._setHash = function() {
var endTime = this.getEndDate() / 1000; var endTime = this.getEndDate() / 1000;
window.location.hash = "#pctc" + encodeURIComponent(JSON.stringify( window.location.hash = "#pctc" + encodeURIComponent(JSON.stringify(
{duration: duration, endTime: endTime})); {duration: duration, endTime: endTime}));
} };
PromConsole.TimeControl._initialValues = function() { PromConsole.TimeControl._initialValues = function() {
var hash = window.location.hash; var hash = window.location.hash;
if (hash.indexOf('#pctc') == 0) { if (hash.indexOf('#pctc') === 0) {
return JSON.parse(decodeURIComponent(hash.substring(5))); return JSON.parse(decodeURIComponent(hash.substring(5)));
} }
return {duration: 3600, endTime: new Date().getTime() / 1000, endTimeNow: true}; return {duration: 3600, endTime: new Date().getTime() / 1000, endTimeNow: true};
@ -158,9 +158,9 @@ PromConsole.TimeControl.prototype.getHumanDuration = function(duration) {
for (var key in PromConsole.TimeControl.timeFactors) { for (var key in PromConsole.TimeControl.timeFactors) {
units.push([PromConsole.TimeControl.timeFactors[key], key]); units.push([PromConsole.TimeControl.timeFactors[key], key]);
} }
units.sort(function(a, b) { return b[0] - a[0] }); units.sort(function(a, b) { return b[0] - a[0]; });
for (var i = 0; i < units.length; ++i) { for (var i = 0; i < units.length; ++i) {
if (duration % units[i][0] == 0) { if (duration % units[i][0] === 0) {
return (duration / units[i][0]) + units[i][1]; return (duration / units[i][0]) + units[i][1];
} }
} }
@ -195,7 +195,7 @@ PromConsole.TimeControl.prototype.setDuration = function(duration) {
}; };
PromConsole.TimeControl.prototype.getEndDate = function() { PromConsole.TimeControl.prototype.getEndDate = function() {
if (this.endElement.value == '') { if (this.endElement.value === '') {
return null; return null;
} }
return new Date(this.endElement.value).getTime(); return new Date(this.endElement.value).getTime();
@ -209,14 +209,14 @@ PromConsole.TimeControl.prototype.getOrSetEndDate = function() {
date = new Date(); date = new Date();
this.setEndDate(date); this.setEndDate(date);
return date; return date;
} };
PromConsole.TimeControl.prototype.getHumanDate = function(date) { PromConsole.TimeControl.prototype.getHumanDate = function(date) {
var hours = date.getHours() < 10 ? '0' + date.getHours() : date.getHours(); var hours = date.getHours() < 10 ? '0' + date.getHours() : date.getHours();
var minutes = date.getMinutes() < 10 ? '0' + date.getMinutes() : date.getMinutes(); var minutes = date.getMinutes() < 10 ? '0' + date.getMinutes() : date.getMinutes();
return date.getFullYear() + "-" + (date.getMonth()+1) + "-" + date.getDate() + " " + return date.getFullYear() + "-" + (date.getMonth()+1) + "-" + date.getDate() + " " +
hours + ":" + minutes; hours + ":" + minutes;
} };
PromConsole.TimeControl.prototype.setEndDate = function(date) { PromConsole.TimeControl.prototype.setEndDate = function(date) {
this.setRefresh("Off"); this.setRefresh("Off");
@ -224,7 +224,6 @@ PromConsole.TimeControl.prototype.setEndDate = function(date) {
this._setHash(); this._setHash();
}; };
PromConsole.TimeControl.prototype.increaseEnd = function() { PromConsole.TimeControl.prototype.increaseEnd = function() {
// Increase duration 25% range & convert ms to s. // Increase duration 25% range & convert ms to s.
this.setEndDate(new Date(this.getOrSetEndDate() + this.parseDuration(this.durationElement.value) * 1000/4 )); this.setEndDate(new Date(this.getOrSetEndDate() + this.parseDuration(this.durationElement.value) * 1000/4 ));
@ -240,7 +239,7 @@ PromConsole.TimeControl.prototype.refresh = function() {
this.endElement.value = ''; this.endElement.value = '';
this._setHash(); this._setHash();
this.dispatch(); this.dispatch();
} };
PromConsole.TimeControl.prototype.dispatch = function() { PromConsole.TimeControl.prototype.dispatch = function() {
var durationSeconds = this.parseDuration(this.durationElement.value); var durationSeconds = this.parseDuration(this.durationElement.value);
@ -264,7 +263,7 @@ PromConsole.TimeControl.prototype.setRefresh = function(duration) {
this._refreshInterval = null; this._refreshInterval = null;
} }
if (duration != "Off") { if (duration != "Off") {
if (this.endElement.value != '') { if (this.endElement.value !== '') {
this.refresh(); this.refresh();
} }
var durationSeconds = this.parseDuration(duration); var durationSeconds = this.parseDuration(duration);
@ -273,8 +272,6 @@ PromConsole.TimeControl.prototype.setRefresh = function(duration) {
this.refreshValueElement.textContent = duration; this.refreshValueElement.textContent = duration;
}; };
// List of all graphs, used by time controls. // List of all graphs, used by time controls.
PromConsole._graph_registry = []; PromConsole._graph_registry = [];
@ -320,7 +317,7 @@ PromConsole.Graph = function(params) {
if (typeof params.name == "string" || typeof params.name == "function") { if (typeof params.name == "string" || typeof params.name == "function") {
var name = []; var name = [];
for (var i = 0; i < params.expr.length; i++) { for (var i = 0; i < params.expr.length; i++) {
name.push(params.name) name.push(params.name);
} }
params.name = name; params.name = name;
} }
@ -380,10 +377,9 @@ PromConsole.Graph = function(params) {
if(this.rendered_data !== null) { if(this.rendered_data !== null) {
this._render(this.rendered_data); this._render(this.rendered_data);
} }
}.bind(this)) }.bind(this));
this.dispatch(); this.dispatch();
}; };
PromConsole.Graph.prototype._parseValue = function(value) { PromConsole.Graph.prototype._parseValue = function(value) {
@ -391,10 +387,10 @@ PromConsole.Graph.prototype._parseValue = function(value) {
if (isNaN(val)) { if (isNaN(val)) {
// "+Inf", "-Inf", "+Inf" will be parsed into NaN by parseFloat(). The // "+Inf", "-Inf", "+Inf" will be parsed into NaN by parseFloat(). The
// can't be graphed, so show them as gaps (null). // can't be graphed, so show them as gaps (null).
return null return null;
} }
return val; return val;
} };
PromConsole.Graph.prototype._escapeHTML = function(string) { PromConsole.Graph.prototype._escapeHTML = function(string) {
var entityMap = { var entityMap = {
@ -409,7 +405,7 @@ PromConsole.Graph.prototype._escapeHTML = function(string) {
return string.replace(/[&<>"'\/]/g, function (s) { return string.replace(/[&<>"'\/]/g, function (s) {
return entityMap[s]; return entityMap[s];
}); });
} };
PromConsole.Graph.prototype._render = function(data) { PromConsole.Graph.prototype._render = function(data) {
var self = this; var self = this;
@ -443,7 +439,7 @@ PromConsole.Graph.prototype._render = function(data) {
for (var e = 0; e < data.length; e++) { for (var e = 0; e < data.length; e++) {
for (var i = 0; i < data[e].value.length; i++) { for (var i = 0; i < data[e].value.length; i++) {
series[seriesLen++] = { series[seriesLen++] = {
data: data[e].value[i].values.map(function(s) {return {x: s[0], y: self._parseValue(s[1])} }), data: data[e].value[i].values.map(function(s) { return {x: s[0], y: self._parseValue(s[1])}; }),
color: palette.color(), color: palette.color(),
name: self._escapeHTML(nameFuncs[e](data[e].value[i].metric)), name: self._escapeHTML(nameFuncs[e](data[e].value[i].metric)),
}; };
@ -473,8 +469,8 @@ PromConsole.Graph.prototype._render = function(data) {
onRender: function() { onRender: function() {
var xLabel = this.element.getElementsByClassName("x_label")[0]; var xLabel = this.element.getElementsByClassName("x_label")[0];
var item = this.element.getElementsByClassName("item")[0]; var item = this.element.getElementsByClassName("item")[0];
if (xLabel.offsetWidth + xLabel.offsetLeft + this.element.offsetLeft > graph.element.offsetWidth if (xLabel.offsetWidth + xLabel.offsetLeft + this.element.offsetLeft > graph.element.offsetWidth ||
|| item.offsetWidth + item.offsetLeft + this.element.offsetLeft > graph.element.offsetWidth) { item.offsetWidth + item.offsetLeft + this.element.offsetLeft > graph.element.offsetWidth) {
xLabel.classList.add("prom_graph_hover_flipped"); xLabel.classList.add("prom_graph_hover_flipped");
item.classList.add("prom_graph_hover_flipped"); item.classList.add("prom_graph_hover_flipped");
} else { } else {
@ -482,7 +478,9 @@ PromConsole.Graph.prototype._render = function(data) {
item.classList.remove("prom_graph_hover_flipped"); item.classList.remove("prom_graph_hover_flipped");
} }
}, },
yFormatter: function(y) {return this.params.yHoverFormatter(y) + this.params.yUnits}.bind(this) yFormatter: function(y) {
return this.params.yHoverFormatter(y) + this.params.yUnits;
}.bind(this)
}); });
var yAxis = new Rickshaw.Graph.Axis.Y({ var yAxis = new Rickshaw.Graph.Axis.Y({
graph: graph, graph: graph,
@ -507,9 +505,9 @@ PromConsole.Graph.prototype._clearGraph = function() {
while (this.legendDiv.lastChild) { while (this.legendDiv.lastChild) {
this.legendDiv.removeChild(this.legendDiv.lastChild); this.legendDiv.removeChild(this.legendDiv.lastChild);
} }
} };
PromConsole.Graph.prototype._xhrs = [] PromConsole.Graph.prototype._xhrs = [];
PromConsole.Graph.prototype.dispatch = function() { PromConsole.Graph.prototype.dispatch = function() {
for (var j = 0; j < this._xhrs.length; j++) { for (var j = 0; j < this._xhrs.length; j++) {
@ -520,9 +518,9 @@ PromConsole.Graph.prototype.dispatch = function() {
var pending_requests = this.params.expr.length; var pending_requests = this.params.expr.length;
for (var i = 0; i < this.params.expr.length; ++i) { for (var i = 0; i < this.params.expr.length; ++i) {
var endTime = this.params.endTime; var endTime = this.params.endTime;
var url = PATH_PREFIX + "/api/query_range?expr=" + encodeURIComponent(this.params.expr[i]) var url = PATH_PREFIX + "/api/query_range?expr=" + encodeURIComponent(this.params.expr[i]) +
+ "&step=" + this.params.duration / this.graphTd.offsetWidth "&step=" + this.params.duration / this.graphTd.offsetWidth +
+ "&range=" + this.params.duration + "&end=" + endTime; "&range=" + this.params.duration + "&end=" + endTime;
var xhr = new XMLHttpRequest(); var xhr = new XMLHttpRequest();
xhr.open('get', url, true); xhr.open('get', url, true);
xhr.responseType = 'json'; xhr.responseType = 'json';
@ -538,20 +536,20 @@ PromConsole.Graph.prototype.dispatch = function() {
for (var j = 0; j < pending_requests; j++) { for (var j = 0; j < pending_requests; j++) {
this._xhrs[j].abort(); this._xhrs[j].abort();
} }
}.bind(this, xhr, i) }.bind(this, xhr, i);
xhr.onload = function(xhr, i) { xhr.onload = function(xhr, i) {
if (pending_requests == 0) { if (pending_requests === 0) {
// Got an error before this success. // Got an error before this success.
return; return;
} }
var data = xhr.response; var data = xhr.response;
pending_requests -= 1; pending_requests -= 1;
all_data[i] = data; all_data[i] = data;
if (pending_requests == 0) { if (pending_requests === 0) {
this._xhrs = []; this._xhrs = [];
this._render(all_data); this._render(all_data);
} }
}.bind(this, xhr, i) }.bind(this, xhr, i);
xhr.send(); xhr.send();
this._xhrs[i] = xhr; this._xhrs[i] = xhr;
} }
@ -568,13 +566,13 @@ PromConsole._interpolateName = function(name, metric) {
var re = /(.*?)\[\[\s*(\w+)+\s*\]\](.*?)/g; var re = /(.*?)\[\[\s*(\w+)+\s*\]\](.*?)/g;
var result = ''; var result = '';
while (match = re.exec(name)) { while (match = re.exec(name)) {
result = result + match[1] + metric[match[2]] + match[3] result = result + match[1] + metric[match[2]] + match[3];
} }
if (!result) { if (!result) {
return name; return name;
} }
return result; return result;
} };
// Given the data returned by the API, return an appropriate function // Given the data returned by the API, return an appropriate function
// to return plot names. // to return plot names.
@ -589,7 +587,8 @@ PromConsole._chooseNameFunction = function(data) {
name += label + "='" + metric[label] + "',"; name += label + "='" + metric[label] + "',";
} }
return name + "}"; return name + "}";
} };
// If only one label varies, use that value. // If only one label varies, use that value.
var labelValues = {}; var labelValues = {};
for (var e = 0; e < data.length; e++) { for (var e = 0; e < data.length; e++) {
@ -602,6 +601,7 @@ PromConsole._chooseNameFunction = function(data) {
} }
} }
} }
var multiValueLabels = []; var multiValueLabels = [];
for (var label in labelValues) { for (var label in labelValues) {
if (Object.keys(labelValues[label]).length > 1) { if (Object.keys(labelValues[label]).length > 1) {
@ -611,11 +611,10 @@ PromConsole._chooseNameFunction = function(data) {
if (multiValueLabels.length == 1) { if (multiValueLabels.length == 1) {
nameFunc = function(metric) { nameFunc = function(metric) {
return metric[multiValueLabels[0]]; return metric[multiValueLabels[0]];
} };
} }
return nameFunc; return nameFunc;
} };
// Given a list of expressions, produce the /graph url for them. // Given a list of expressions, produce the /graph url for them.
PromConsole._graphsToSlashGraphURL = function(exprs) { PromConsole._graphsToSlashGraphURL = function(exprs) {