[js linting] use airbnb eslint settings (#796)

* add airbnb eslint settings and lint all the code

* fix linting erros
This commit is contained in:
Alanna Scott
2016-07-27 16:57:05 -07:00
committed by GitHub
parent f43e5f18d5
commit 1101de5ae4
20 changed files with 1006 additions and 1132 deletions

View File

@@ -1,11 +1,10 @@
var $ = require('jquery');
var jQuery = $;
var d3 = require('d3');
var Mustache = require('mustache');
var utils = require('./utils');
import $ from 'jquery';
const d3 = require('d3');
const Mustache = require('mustache');
const utils = require('./utils');
// vis sources
var sourceMap = {
/* eslint camel-case: 0 */
const sourceMap = {
area: 'nvd3_vis.js',
bar: 'nvd3_vis.js',
bubble: 'nvd3_vis.js',
@@ -34,185 +33,247 @@ var sourceMap = {
horizon: 'horizon.js',
mapbox: 'mapbox.jsx',
};
var color = function () {
const color = function () {
// Color related utility functions go in this object
var bnbColors = [
//rausch hackb kazan babu lima beach barol
'#ff5a5f', '#7b0051', '#007A87', '#00d1c1', '#8ce071', '#ffb400', '#b4a76c',
'#ff8083', '#cc0086', '#00a1b3', '#00ffeb', '#bbedab', '#ffd266', '#cbc29a',
'#ff3339', '#ff1ab1', '#005c66', '#00b3a5', '#55d12e', '#b37e00', '#988b4e',
const bnbColors = [
'#ff5a5f', // rausch
'#7b0051', // hackb
'#007A87', // kazan
'#00d1c1', // babu
'#8ce071', // lima
'#ffb400', // beach
'#b4a76c', // barol
'#ff8083',
'#cc0086',
'#00a1b3',
'#00ffeb',
'#bbedab',
'#ffd266',
'#cbc29a',
'#ff3339',
'#ff1ab1',
'#005c66',
'#00b3a5',
'#55d12e',
'#b37e00',
'#988b4e',
];
var spectrums = {
blue_white_yellow: ['#00d1c1', 'white', '#ffb400'],
fire: ['white', 'yellow', 'red', 'black'],
white_black: ['white', 'black'],
black_white: ['black', 'white'],
const spectrums = {
blue_white_yellow: [
'#00d1c1',
'white',
'#ffb400',
],
fire: [
'white',
'yellow',
'red',
'black',
],
white_black: [
'white',
'black',
],
black_white: [
'black',
'white',
],
};
var colorBnb = function () {
const colorBnb = function () {
// Color factory
var seen = {};
const seen = {};
return function (s) {
if (!s) { return; }
s = String(s);
// next line is for caravel series that should have the same color
s = s.replace('---', '');
if (seen[s] === undefined) {
seen[s] = Object.keys(seen).length;
if (!s) {
return;
}
return this.bnbColors[seen[s] % this.bnbColors.length];
let stringifyS = String(s);
// next line is for caravel series that should have the same color
stringifyS = stringifyS.replace('---', '');
if (seen[stringifyS] === undefined) {
seen[stringifyS] = Object.keys(seen).length;
}
/* eslint consistent-return: 0 */
return this.bnbColors[seen[stringifyS] % this.bnbColors.length];
};
};
var colorScalerFactory = function (colors, data, accessor) {
const colorScalerFactory = function (colors, data, accessor) {
// Returns a linear scaler our of an array of color
if (!Array.isArray(colors)) {
/* eslint no-param-reassign: 0 */
colors = spectrums[colors];
}
var ext = [0, 1];
let ext = [
0,
1,
];
if (data !== undefined) {
ext = d3.extent(data, accessor);
}
var points = [];
var chunkSize = (ext[1] - ext[0]) / colors.length;
$.each(colors, function (i, c) {
const points = [];
const chunkSize = (ext[1] - ext[0]) / colors.length;
$.each(colors, function (i) {
points.push(i * chunkSize);
});
return d3.scale.linear().domain(points).range(colors);
};
return {
bnbColors: bnbColors,
bnbColors,
category21: colorBnb(),
colorScalerFactory: colorScalerFactory,
colorScalerFactory,
};
};
var px = (function () {
var visualizations = {};
var slice;
/* eslint wrap-iife: 0*/
const px = function () {
const visualizations = {};
let slice;
function getParam(name) {
name = name.replace(/[\[]/, "\\[").replace(/[\]]/, "\\]");
var regex = new RegExp("[\\?&]" + name + "=([^&#]*)"),
results = regex.exec(location.search);
return results === null ? "" : decodeURIComponent(results[1].replace(/\+/g, " "));
name = name.replace(/[\[]/, '\\[').replace(/[\]]/, '\\]');
const regex = new RegExp('[\\?&]' + name + '=([^&#]*)');
const results = regex.exec(location.search);
return results === null ? '' : decodeURIComponent(results[1].replace(/\+/g, ' '));
}
function UTC(dttm) {
return new Date(dttm.getUTCFullYear(), dttm.getUTCMonth(), dttm.getUTCDate(), dttm.getUTCHours(), dttm.getUTCMinutes(), dttm.getUTCSeconds());
return new Date(
dttm.getUTCFullYear(),
dttm.getUTCMonth(),
dttm.getUTCDate(),
dttm.getUTCHours(),
dttm.getUTCMinutes(),
dttm.getUTCSeconds()
);
}
var tickMultiFormat = d3.time.format.multi([
[".%L", function (d) {
return d.getMilliseconds();
}], // If there are millisections, show only them
[":%S", function (d) {
return d.getSeconds();
}], // If there are seconds, show only them
["%a %b %d, %I:%M %p", function (d) {
return d.getMinutes() !== 0;
}], // If there are non-zero minutes, show Date, Hour:Minute [AM/PM]
["%a %b %d, %I %p", function (d) {
return d.getHours() !== 0;
}], // If there are hours that are multiples of 3, show date and AM/PM
["%a %b %d", function (d) {
return d.getDate() !== 1;
}], // If not the first of the month, do "month day, year."
["%B %Y", function (d) {
return d.getMonth() !== 0 && d.getDate() === 1;
}], // If the first of the month, do "month day, year."
["%Y", function (d) {
return true;
}], // fall back on month, year
const tickMultiFormat = d3.time.format.multi([
[
'.%L',
function (d) {
return d.getMilliseconds();
},
],
// If there are millisections, show only them
[
':%S',
function (d) {
return d.getSeconds();
},
],
// If there are seconds, show only them
[
'%a %b %d, %I:%M %p',
function (d) {
return d.getMinutes() !== 0;
},
],
// If there are non-zero minutes, show Date, Hour:Minute [AM/PM]
[
'%a %b %d, %I %p',
function (d) {
return d.getHours() !== 0;
},
],
// If there are hours that are multiples of 3, show date and AM/PM
[
'%a %b %d',
function (d) {
return d.getDate() !== 1;
},
],
// If not the first of the month, do "month day, year."
[
'%B %Y',
function (d) {
return d.getMonth() !== 0 && d.getDate() === 1;
},
],
// If the first of the month, do "month day, year."
[
'%Y',
function () {
return true;
},
], // fall back on month, year
]);
function formatDate(dttm) {
var d = UTC(new Date(dttm));
//d = new Date(d.getTime() - 1 * 60 * 60 * 1000);
const d = UTC(new Date(dttm));
// d = new Date(d.getTime() - 1 * 60 * 60 * 1000);
return tickMultiFormat(d);
}
function timeFormatFactory(d3timeFormat) {
var f = d3.time.format(d3timeFormat);
const f = d3.time.format(d3timeFormat);
return function (dttm) {
var d = UTC(new Date(dttm));
const d = UTC(new Date(dttm));
return f(d);
};
}
function initFavStars() {
var baseUrl = '/caravel/favstar/';
// Init star behavihor for favorite
function show() {
if ($(this).hasClass('selected')) {
$(this).html('<i class="fa fa-star"></i>');
} else {
$(this).html('<i class="fa fa-star-o"></i>');
}
const baseUrl = '/caravel/favstar/';
// Init star behavihor for favorite
function show() {
if ($(this).hasClass('selected')) {
$(this).html('<i class="fa fa-star"></i>');
} else {
$(this).html('<i class="fa fa-star-o"></i>');
}
$('.favstar')
.attr('title', 'Click to favorite/unfavorite')
.each(show)
.each(function () {
var url = baseUrl + $(this).attr("class_name");
var star = this;
url += '/' + $(this).attr("obj_id") + '/';
$.getJSON(url + 'count/', function (data) {
if (data.count > 0) {
$(star)
.addClass('selected')
.each(show);
}
});
})
.click(function () {
$(this).toggleClass('selected');
var url = baseUrl + $(this).attr("class_name");
url += '/' + $(this).attr("obj_id") + '/';
if ($(this).hasClass('selected')) {
url += 'select/';
} else {
url += 'unselect/';
}
$('.favstar')
.attr('title', 'Click to favorite/unfavorite')
.each(show)
.each(function () {
let url = baseUrl + $(this).attr('class_name');
const star = this;
url += '/' + $(this).attr('obj_id') + '/';
$.getJSON(url + 'count/', function (data) {
if (data.count > 0) {
$(star).addClass('selected').each(show);
}
$.get(url);
$(this).each(show);
})
.tooltip();
});
})
.click(function () {
$(this).toggleClass('selected');
let url = baseUrl + $(this).attr('class_name');
url += '/' + $(this).attr('obj_id') + '/';
if ($(this).hasClass('selected')) {
url += 'select/';
} else {
url += 'unselect/';
}
$.get(url);
$(this).each(show);
})
.tooltip();
}
var Slice = function (data, dashboard) {
var timer;
var token = $('#' + data.token);
var container_id = data.token + '_con';
var selector = '#' + container_id;
var container = $(selector);
var slice_id = data.slice_id;
var dttm = 0;
var stopwatch = function () {
const Slice = function (data, dashboard) {
let timer;
const token = $('#' + data.token);
const containerId = data.token + '_con';
const selector = '#' + containerId;
const container = $(selector);
const sliceId = data.sliceId;
let dttm = 0;
const stopwatch = function () {
dttm += 10;
var num = dttm / 1000;
$('#timer').text(num.toFixed(2) + " sec");
const num = dttm / 1000;
$('#timer').text(num.toFixed(2) + ' sec');
};
var qrystr = '';
var always = function (data) {
//Private f, runs after done and error
let qrystr = '';
const always = function () {
// Private f, runs after done and error
clearInterval(timer);
$('#timer').removeClass('btn-warning');
};
slice = {
data: data,
container: container,
container_id: container_id,
selector: selector,
querystring: function (params) {
data,
container,
containerId,
selector,
querystring(params) {
params = params || {};
var parser = document.createElement('a');
const parser = document.createElement('a');
parser.href = data.json_endpoint;
if (dashboard !== undefined) {
var flts = params.extraFilters === false ?
'' : encodeURIComponent(JSON.stringify(dashboard.filters));
qrystr = parser.search + "&extra_filters=" + flts;
const flts =
params.extraFilters === false ? '' :
encodeURIComponent(JSON.stringify(dashboard.filters));
qrystr = parser.search + '&extra_filters=' + flts;
} else if ($('#query').length === 0) {
qrystr = parser.search;
} else {
@@ -220,69 +281,66 @@ var px = (function () {
}
return qrystr;
},
getWidgetHeader: function () {
return this.container.parents("div.widget").find(".chart-header");
getWidgetHeader() {
return this.container.parents('div.widget').find('.chart-header');
},
render_template: function (s) {
var context = {
render_template(s) {
const context = {
width: this.width,
height: this.height,
};
return Mustache.render(s, context);
},
jsonEndpoint: function (params) {
jsonEndpoint(params) {
params = params || {};
var parser = document.createElement('a');
const parser = document.createElement('a');
parser.href = data.json_endpoint;
var endpoint = parser.pathname + this.querystring({
extraFilters: params.extraFilters,
});
endpoint += "&json=true";
endpoint += "&force=" + this.force;
let endpoint = parser.pathname + this.querystring({ extraFilters: params.extraFilters });
endpoint += '&json=true';
endpoint += '&force=' + this.force;
return endpoint;
},
d3format: function (col, number) {
d3format(col, number) {
// uses the utils memoized d3format function and formats based on
// column level defined preferences
var format = this.data.column_formats[col];
const format = this.data.column_formats[col];
return utils.d3format(format, number);
},
done: function (data) {
/* eslint no-shadow: 0 */
done(data) {
clearInterval(timer);
token.find("img.loading").hide();
token.find('img.loading').hide();
container.show();
var cachedSelector = null;
let cachedSelector = null;
if (dashboard === undefined) {
cachedSelector = $('#is_cached');
if (data !== undefined && data.is_cached) {
cachedSelector
.attr('title', 'Served from data cached at ' + data.cached_dttm + '. Click to force-refresh')
.attr('title',
'Served from data cached at ' + data.cached_dttm + '. Click to force-refresh')
.show()
.tooltip('fixTitle');
} else {
cachedSelector.hide();
}
} else {
var refresh = this.getWidgetHeader().find('.refresh');
const refresh = this.getWidgetHeader().find('.refresh');
if (data !== undefined && data.is_cached) {
refresh
.addClass('danger')
.attr(
'title',
'Served from data cached at ' + data.cached_dttm + '. Click to force-refresh')
.tooltip('fixTitle');
.addClass('danger')
.attr('title',
'Served from data cached at ' + data.cached_dttm +
'. Click to force-refresh')
.tooltip('fixTitle');
} else {
refresh
.removeClass('danger')
.attr(
'title',
'Click to force-refresh')
.tooltip('fixTitle');
.removeClass('danger')
.attr('title', 'Click to force-refresh')
.tooltip('fixTitle');
}
}
if (data !== undefined) {
$("#query_container").html(data.query);
$('#query_container').html(data.query);
}
$('#timer').removeClass('btn-warning');
$('#timer').addClass('btn-success');
@@ -297,26 +355,26 @@ var px = (function () {
$('.query-and-save button').removeAttr('disabled');
always(data);
},
getErrorMsg: function (xhr) {
if (xhr.statusText === "timeout") {
return "The request timed out";
getErrorMsg(xhr) {
if (xhr.statusText === 'timeout') {
return 'The request timed out';
}
var msg = "";
let msg = '';
if (!xhr.responseText) {
var status = xhr.status;
msg += "An unknown error occurred. (Status: " + status + ")";
const status = xhr.status;
msg += 'An unknown error occurred. (Status: ' + status + ')';
if (status === 0) {
// This may happen when the worker in gunicorn times out
msg += " Maybe the request timed out?";
msg += ' Maybe the request timed out?';
}
}
return msg;
},
error: function (msg, xhr) {
token.find("img.loading").hide();
var err = msg ? ('<div class="alert alert-danger">' + msg + '</div>') : "";
error(msg, xhr) {
token.find('img.loading').hide();
let err = msg ? '<div class="alert alert-danger">' + msg + '</div>' : '';
if (xhr) {
var extendedMsg = this.getErrorMsg(xhr);
const extendedMsg = this.getErrorMsg(xhr);
if (extendedMsg) {
err += '<div class="alert alert-danger">' + extendedMsg + '</div>';
}
@@ -329,35 +387,35 @@ var px = (function () {
$('.query-and-save button').removeAttr('disabled');
always(data);
},
width: function () {
width() {
return token.width();
},
height: function () {
var others = 0;
var widget = container.parents('.widget');
var slice_description = widget.find('.slice_description');
if (slice_description.is(":visible")) {
others += widget.find('.slice_description').height() + 25;
height() {
let others = 0;
const widget = container.parents('.widget');
const sliceDescription = widget.find('.sliceDescription');
if (sliceDescription.is(':visible')) {
others += widget.find('.sliceDescription').height() + 25;
}
others += widget.find('.chart-header').height();
return widget.height() - others - 10;
},
bindResizeToWindowResize: function () {
var resizeTimer;
var slice = this;
$(window).on('resize', function (e) {
bindResizeToWindowResize() {
let resizeTimer;
const slice = this;
$(window).on('resize', function () {
clearTimeout(resizeTimer);
resizeTimer = setTimeout(function () {
slice.resize();
}, 500);
});
},
render: function (force) {
render(force) {
if (force === undefined) {
force = false;
}
this.force = force;
token.find("img.loading").show();
token.find('img.loading').show();
container.css('height', this.height());
dttm = 0;
timer = setInterval(stopwatch, 10);
@@ -365,67 +423,65 @@ var px = (function () {
$('#timer').addClass('btn-warning');
this.viz.render();
},
resize: function () {
token.find("img.loading").show();
resize() {
token.find('img.loading').show();
container.css('height', this.height());
this.viz.render();
this.viz.resize();
},
addFilter: function (col, vals) {
addFilter(col, vals) {
if (dashboard !== undefined) {
dashboard.addFilter(slice_id, col, vals);
dashboard.addFilter(sliceId, col, vals);
}
},
setFilter: function (col, vals) {
setFilter(col, vals) {
if (dashboard !== undefined) {
dashboard.setFilter(slice_id, col, vals);
dashboard.setFilter(sliceId, col, vals);
}
},
getFilters: function (col, vals) {
getFilters() {
if (dashboard !== undefined) {
return dashboard.filters[slice_id];
return dashboard.filters[sliceId];
}
return false;
},
clearFilter() {
if (dashboard !== undefined) {
dashboard.clearFilter(sliceId);
}
},
clearFilter: function () {
removeFilter(col, vals) {
if (dashboard !== undefined) {
delete dashboard.clearFilter(slice_id);
}
},
removeFilter: function (col, vals) {
if (dashboard !== undefined) {
delete dashboard.removeFilter(slice_id, col, vals);
dashboard.removeFilter(sliceId, col, vals);
}
},
};
var visType = data.form_data.viz_type;
const visType = data.form_data.viz_type;
px.registerViz(visType);
slice.viz = visualizations[data.form_data.viz_type](slice);
return slice;
};
function registerViz(name) {
var visSource = sourceMap[name];
const visSource = sourceMap[name];
if (visSource) {
var visFactory = require('../../visualizations/' + visSource);
/* eslint global-require: 0 */
const visFactory = require('../../visualizations/' + visSource);
if (typeof visFactory === 'function') {
visualizations[name] = visFactory;
}
} else {
throw new Error("require(" + name + ") failed.");
throw new Error('require(' + name + ') failed.');
}
}
// Export public functions
return {
registerViz: registerViz,
Slice: Slice,
formatDate: formatDate,
timeFormatFactory: timeFormatFactory,
color: color(),
getParam: getParam,
initFavStars: initFavStars,
formatDate,
getParam,
initFavStars,
registerViz,
Slice,
timeFormatFactory,
};
})();
}();
module.exports = px;

View File

@@ -1,56 +1,51 @@
var $ = require('jquery');
var d3 = require('d3');
const $ = require('jquery');
const d3 = require('d3');
/*
Utility function that takes a d3 svg:text selection and a max width, and splits the
text's text across multiple tspan lines such that any given line does not exceed max width
If text does not span multiple lines AND adjustedY is passed, will set the text to the passed val
If text does not span multiple lines AND adjustedY is passed,
will set the text to the passed val
*/
function wrapSvgText(text, width, adjustedY) {
var lineHeight = 1; // ems
const lineHeight = 1;
// ems
text.each(function () {
var text = d3.select(this),
words = text.text().split(/\s+/),
word,
line = [],
lineNumber = 0,
x = text.attr("x"),
y = text.attr("y"),
dy = parseFloat(text.attr("dy")),
tspan = text.text(null)
.append("tspan")
.attr("x", x)
.attr("y", y)
.attr("dy", dy + "em");
const d3Text = d3.select(this);
const words = d3Text.text().split(/\s+/);
let word;
let line = [];
let lineNumber = 0;
const x = d3Text.attr('x');
const y = d3Text.attr('y');
const dy = parseFloat(d3Text.attr('dy'));
let tspan =
d3Text.text(null).append('tspan').attr('x', x)
.attr('y', y)
.attr('dy', dy + 'em');
var didWrap = false;
for (var i = 0; i < words.length; i++) {
let didWrap = false;
for (let i = 0; i < words.length; i++) {
word = words[i];
line.push(word);
tspan.text(line.join(" "));
tspan.text(line.join(' '));
if (tspan.node().getComputedTextLength() > width) {
line.pop(); // remove word that pushes over the limit
tspan.text(line.join(" "));
line.pop();
// remove word that pushes over the limit
tspan.text(line.join(' '));
line = [word];
tspan = text.append("tspan")
.attr("x", x)
.attr("y", y)
.attr("dy", ++lineNumber * lineHeight + dy + "em")
.text(word);
tspan =
d3Text.append('tspan').attr('x', x).attr('y', y)
.attr('dy', ++lineNumber * lineHeight + dy + 'em')
.text(word);
didWrap = true;
}
}
if (!didWrap && typeof adjustedY !== "undefined") {
tspan.attr("y", adjustedY);
if (!didWrap && typeof adjustedY !== 'undefined') {
tspan.attr('y', adjustedY);
}
});
}
/**
* Sets the body and title content of a modal, and shows it. Assumes HTML for modal exists and that
* it handles closing (i.e., works with bootstrap)
@@ -65,47 +60,41 @@ function wrapSvgText(text, width, adjustedY) {
* }
*/
function showModal(options) {
options.modalSelector = options.modalSelector || ".misc-modal";
options.titleSelector = options.titleSelector || ".misc-modal .modal-title";
options.bodySelector = options.bodySelector || ".misc-modal .modal-body";
$(options.titleSelector).html(options.title || "");
$(options.bodySelector).html(options.body || "");
$(options.modalSelector).modal("show");
/* eslint no-param-reassign: 0 */
options.modalSelector = options.modalSelector || '.misc-modal';
options.titleSelector = options.titleSelector || '.misc-modal .modal-title';
options.bodySelector = options.bodySelector || '.misc-modal .modal-body';
$(options.titleSelector).html(options.title || '');
$(options.bodySelector).html(options.body || '');
$(options.modalSelector).modal('show');
}
var showApiMessage = function (resp) {
var template = '<div class="alert"> ' +
'<button type="button" class="close" ' +
'data-dismiss="alert">×</button> </div>';
var severity = resp.severity || 'info';
$(template)
.addClass('alert-' + severity)
.append(resp.message)
.appendTo($('#alert-container'));
const showApiMessage = function (resp) {
const template =
'<div class="alert"> ' +
'<button type="button" class="close" ' +
'data-dismiss="alert">\xD7</button> </div>';
const severity = resp.severity || 'info';
$(template).addClass('alert-' + severity)
.append(resp.message)
.appendTo($('#alert-container'));
};
var toggleCheckbox = function (apiUrlPrefix, selector) {
var apiUrl = apiUrlPrefix + $(selector)[0].checked;
$.get(apiUrl).fail(function (xhr, textStatus, errorThrown) {
var resp = xhr.responseJSON;
const toggleCheckbox = function (apiUrlPrefix, selector) {
const apiUrl = apiUrlPrefix + $(selector)[0].checked;
$.get(apiUrl).fail(function (xhr) {
const resp = xhr.responseJSON;
if (resp && resp.message) {
showApiMessage(resp);
}
});
};
/**
* Fix the height of the table body of a DataTable with scrollY set
*/
var fixDataTableBodyHeight = function ($tableDom, height) {
var headHeight = $tableDom.find('.dataTables_scrollHead').height();
$tableDom.find('.dataTables_scrollBody')
.css('max-height', height - headHeight);
const fixDataTableBodyHeight = function ($tableDom, height) {
const headHeight = $tableDom.find('.dataTables_scrollHead').height();
$tableDom.find('.dataTables_scrollBody').css('max-height', height - headHeight);
};
var formatters = {};
const formatters = {};
function d3format(format, number) {
// Formats a number and memoizes formatters to be reused
format = format || '.3s';
@@ -114,11 +103,10 @@ function d3format(format, number) {
}
return formatters[format](number);
}
module.exports = {
wrapSvgText: wrapSvgText,
showModal: showModal,
toggleCheckbox: toggleCheckbox,
fixDataTableBodyHeight: fixDataTableBodyHeight,
d3format: d3format,
d3format,
fixDataTableBodyHeight,
showModal,
toggleCheckbox,
wrapSvgText,
};