changed var to const (#13061)

This commit is contained in:
Patrick O'Carroll 2018-08-29 14:26:50 +02:00 committed by Torkel Ödegaard
parent 9423e3e124
commit 5e0d0c5816
50 changed files with 298 additions and 299 deletions

View File

@ -1,4 +1,4 @@
import { Emitter } from './utils/emitter'; import { Emitter } from './utils/emitter';
var appEvents = new Emitter(); const appEvents = new Emitter();
export default appEvents; export default appEvents;

View File

@ -99,9 +99,9 @@ function link(scope, elem, attrs) {
if (scope.codeEditorFocus) { if (scope.codeEditorFocus) {
setTimeout(function() { setTimeout(function() {
textarea.focus(); textarea.focus();
var domEl = textarea[0]; const domEl = textarea[0];
if (domEl.setSelectionRange) { if (domEl.setSelectionRange) {
var pos = textarea.val().length * 2; const pos = textarea.val().length * 2;
domEl.setSelectionRange(pos, pos); domEl.setSelectionRange(pos, pos);
} }
}, 100); }, 100);

View File

@ -1,6 +1,6 @@
import coreModule from 'app/core/core_module'; import coreModule from 'app/core/core_module';
var template = ` const template = `
<select class="gf-form-input" ng-model="ctrl.model" ng-options="f.value as f.text for f in ctrl.options"></select> <select class="gf-form-input" ng-model="ctrl.model" ng-options="f.value as f.text for f in ctrl.options"></select>
`; `;

View File

@ -12,7 +12,7 @@ function escapeString(str: string): string {
* Determines if a value is an object * Determines if a value is an object
*/ */
export function isObject(value: any): boolean { export function isObject(value: any): boolean {
var type = typeof value; const type = typeof value;
return !!value && type === 'object'; return !!value && type === 'object';
} }
@ -55,7 +55,7 @@ export function getType(object: Object): string {
* Generates inline preview for a JavaScript object based on a value * Generates inline preview for a JavaScript object based on a value
*/ */
export function getValuePreview(object: Object, value: string): string { export function getValuePreview(object: Object, value: string): string {
var type = getType(object); const type = getType(object);
if (type === 'null' || type === 'undefined') { if (type === 'null' || type === 'undefined') {
return type; return type;

View File

@ -279,7 +279,7 @@ export class JsonExplorer {
const objectWrapperSpan = createElement('span'); const objectWrapperSpan = createElement('span');
// get constructor name and append it to wrapper span // get constructor name and append it to wrapper span
var constructorName = createElement('span', 'constructor-name', this.constructorName); const constructorName = createElement('span', 'constructor-name', this.constructorName);
objectWrapperSpan.appendChild(constructorName); objectWrapperSpan.appendChild(constructorName);
// if it's an array append the array specific elements like brackets and length // if it's an array append the array specific elements like brackets and length

View File

@ -11,7 +11,7 @@ coreModule.directive('jsonTree', [
rootName: '@', rootName: '@',
}, },
link: function(scope, elem) { link: function(scope, elem) {
var jsonExp = new JsonExplorer(scope.object, 3, { const jsonExp = new JsonExplorer(scope.object, 3, {
animateOpen: true, animateOpen: true,
}); });

View File

@ -1,7 +1,7 @@
import store from 'app/core/store'; import store from 'app/core/store';
import coreModule from 'app/core/core_module'; import coreModule from 'app/core/core_module';
var template = ` const template = `
<div class="layout-selector"> <div class="layout-selector">
<button ng-click="ctrl.listView()" ng-class="{active: ctrl.mode === 'list'}"> <button ng-click="ctrl.listView()" ng-class="{active: ctrl.mode === 'list'}">
<i class="fa fa-list"></i> <i class="fa fa-list"></i>
@ -51,7 +51,7 @@ export function layoutMode($rootScope) {
restrict: 'A', restrict: 'A',
scope: {}, scope: {},
link: function(scope, elem) { link: function(scope, elem) {
var layout = store.get('grafana.list.layout.mode') || 'grid'; const layout = store.get('grafana.list.layout.mode') || 'grid';
var className = 'card-list-layout-' + layout; var className = 'card-list-layout-' + layout;
elem.addClass(className); elem.addClass(className);

View File

@ -82,9 +82,9 @@ export class QueryPart {
} }
export function functionRenderer(part, innerExpr) { export function functionRenderer(part, innerExpr) {
var str = part.def.type + '('; const str = part.def.type + '(';
var parameters = _.map(part.params, (value, index) => { const parameters = _.map(part.params, (value, index) => {
var paramType = part.def.params[index]; const paramType = part.def.params[index];
if (paramType.type === 'time') { if (paramType.type === 'time') {
if (value === 'auto') { if (value === 'auto') {
value = '$__interval'; value = '$__interval';

View File

@ -2,7 +2,7 @@ import _ from 'lodash';
import $ from 'jquery'; import $ from 'jquery';
import coreModule from 'app/core/core_module'; import coreModule from 'app/core/core_module';
var template = ` const template = `
<div class="dropdown cascade-open"> <div class="dropdown cascade-open">
<a ng-click="showActionsMenu()" class="query-part-name pointer dropdown-toggle" data-toggle="dropdown">{{part.def.type}}</a> <a ng-click="showActionsMenu()" class="query-part-name pointer dropdown-toggle" data-toggle="dropdown">{{part.def.type}}</a>
<span>(</span><span class="query-part-parameters"></span><span>)</span> <span>(</span><span class="query-part-parameters"></span><span>)</span>
@ -15,7 +15,7 @@ var template = `
/** @ngInject */ /** @ngInject */
export function queryPartEditorDirective($compile, templateSrv) { export function queryPartEditorDirective($compile, templateSrv) {
var paramTemplate = '<input type="text" class="hide input-mini tight-form-func-param"></input>'; const paramTemplate = '<input type="text" class="hide input-mini tight-form-func-param"></input>';
return { return {
restrict: 'E', restrict: 'E',
@ -26,17 +26,17 @@ export function queryPartEditorDirective($compile, templateSrv) {
debounce: '@', debounce: '@',
}, },
link: function postLink($scope, elem) { link: function postLink($scope, elem) {
var part = $scope.part; const part = $scope.part;
var partDef = part.def; const partDef = part.def;
var $paramsContainer = elem.find('.query-part-parameters'); const $paramsContainer = elem.find('.query-part-parameters');
var debounceLookup = $scope.debounce; const debounceLookup = $scope.debounce;
$scope.partActions = []; $scope.partActions = [];
function clickFuncParam(paramIndex) { function clickFuncParam(paramIndex) {
/*jshint validthis:true */ /*jshint validthis:true */
var $link = $(this); const $link = $(this);
var $input = $link.next(); const $input = $link.next();
$input.val(part.params[paramIndex]); $input.val(part.params[paramIndex]);
$input.css('width', $link.width() + 16 + 'px'); $input.css('width', $link.width() + 16 + 'px');
@ -46,7 +46,7 @@ export function queryPartEditorDirective($compile, templateSrv) {
$input.focus(); $input.focus();
$input.select(); $input.select();
var typeahead = $input.data('typeahead'); const typeahead = $input.data('typeahead');
if (typeahead) { if (typeahead) {
$input.val(''); $input.val('');
typeahead.lookup(); typeahead.lookup();
@ -55,9 +55,9 @@ export function queryPartEditorDirective($compile, templateSrv) {
function inputBlur(paramIndex) { function inputBlur(paramIndex) {
/*jshint validthis:true */ /*jshint validthis:true */
var $input = $(this); const $input = $(this);
var $link = $input.prev(); const $link = $input.prev();
var newValue = $input.val(); const newValue = $input.val();
if (newValue !== '' || part.def.params[paramIndex].optional) { if (newValue !== '' || part.def.params[paramIndex].optional) {
$link.html(templateSrv.highlightVariablesAsHtml(newValue)); $link.html(templateSrv.highlightVariablesAsHtml(newValue));
@ -89,7 +89,7 @@ export function queryPartEditorDirective($compile, templateSrv) {
return; return;
} }
var typeaheadSource = function(query, callback) { const typeaheadSource = function(query, callback) {
if (param.options) { if (param.options) {
var options = param.options; var options = param.options;
if (param.type === 'int') { if (param.type === 'int') {
@ -102,7 +102,7 @@ export function queryPartEditorDirective($compile, templateSrv) {
$scope.$apply(function() { $scope.$apply(function() {
$scope.handleEvent({ $event: { name: 'get-param-options' } }).then(function(result) { $scope.handleEvent({ $event: { name: 'get-param-options' } }).then(function(result) {
var dynamicOptions = _.map(result, function(op) { const dynamicOptions = _.map(result, function(op) {
return op.value; return op.value;
}); });
callback(dynamicOptions); callback(dynamicOptions);
@ -124,10 +124,10 @@ export function queryPartEditorDirective($compile, templateSrv) {
}, },
}); });
var typeahead = $input.data('typeahead'); const typeahead = $input.data('typeahead');
typeahead.lookup = function() { typeahead.lookup = function() {
this.query = this.$element.val() || ''; this.query = this.$element.val() || '';
var items = this.source(this.query, $.proxy(this.process, this)); const items = this.source(this.query, $.proxy(this.process, this));
return items ? this.process(items) : items; return items ? this.process(items) : items;
}; };
@ -156,9 +156,9 @@ export function queryPartEditorDirective($compile, templateSrv) {
$('<span>, </span>').appendTo($paramsContainer); $('<span>, </span>').appendTo($paramsContainer);
} }
var paramValue = templateSrv.highlightVariablesAsHtml(part.params[index]); const paramValue = templateSrv.highlightVariablesAsHtml(part.params[index]);
var $paramLink = $('<a class="graphite-func-param-link pointer">' + paramValue + '</a>'); const $paramLink = $('<a class="graphite-func-param-link pointer">' + paramValue + '</a>');
var $input = $(paramTemplate); const $input = $(paramTemplate);
$paramLink.appendTo($paramsContainer); $paramLink.appendTo($paramsContainer);
$input.appendTo($paramsContainer); $input.appendTo($paramsContainer);

View File

@ -159,7 +159,7 @@ export class SearchCtrl {
searchDashboards() { searchDashboards() {
this.currentSearchId = this.currentSearchId + 1; this.currentSearchId = this.currentSearchId + 1;
var localSearchId = this.currentSearchId; const localSearchId = this.currentSearchId;
return this.searchSrv.search(this.query).then(results => { return this.searchSrv.search(this.query).then(results => {
if (localSearchId < this.currentSearchId) { if (localSearchId < this.currentSearchId) {
@ -172,7 +172,7 @@ export class SearchCtrl {
} }
queryHasNoFilters() { queryHasNoFilters() {
var query = this.query; const query = this.query;
return query.query === '' && query.starred === false && query.tag.length === 0; return query.query === '' && query.starred === false && query.tag.length === 0;
} }

View File

@ -74,8 +74,8 @@ export function sideMenuDirective() {
link: function(scope, elem) { link: function(scope, elem) {
// hack to hide dropdown menu // hack to hide dropdown menu
elem.on('click.dropdown', '.dropdown-menu a', function(evt) { elem.on('click.dropdown', '.dropdown-menu a', function(evt) {
var menu = $(evt.target).parents('.dropdown-menu'); const menu = $(evt.target).parents('.dropdown-menu');
var parent = menu.parent(); const parent = menu.parent();
menu.detach(); menu.detach();
setTimeout(function() { setTimeout(function() {

View File

@ -1,6 +1,6 @@
import coreModule from 'app/core/core_module'; import coreModule from 'app/core/core_module';
var template = ` const template = `
<label for="check-{{ctrl.id}}" class="gf-form-label {{ctrl.labelClass}} pointer" ng-show="ctrl.label"> <label for="check-{{ctrl.id}}" class="gf-form-label {{ctrl.labelClass}} pointer" ng-show="ctrl.label">
{{ctrl.label}} {{ctrl.label}}
<info-popover mode="right-normal" ng-if="ctrl.tooltip" position="top center"> <info-popover mode="right-normal" ng-if="ctrl.tooltip" position="top center">

View File

@ -14,9 +14,9 @@ coreModule.directive('giveFocus', function() {
} }
setTimeout(function() { setTimeout(function() {
element.focus(); element.focus();
var domEl = element[0]; const domEl = element[0];
if (domEl.setSelectionRange) { if (domEl.setSelectionRange) {
var pos = element.val().length * 2; const pos = element.val().length * 2;
domEl.setSelectionRange(pos, pos); domEl.setSelectionRange(pos, pos);
} }
}, 200); }, 200);

View File

@ -82,11 +82,11 @@ function editorOptBool($compile) {
return { return {
restrict: 'E', restrict: 'E',
link: function(scope, elem, attrs) { link: function(scope, elem, attrs) {
var ngchange = attrs.change ? ' ng-change="' + attrs.change + '"' : ''; const ngchange = attrs.change ? ' ng-change="' + attrs.change + '"' : '';
var tip = attrs.tip ? ' <tip>' + attrs.tip + '</tip>' : ''; const tip = attrs.tip ? ' <tip>' + attrs.tip + '</tip>' : '';
var showIf = attrs.showIf ? ' ng-show="' + attrs.showIf + '" ' : ''; const showIf = attrs.showIf ? ' ng-show="' + attrs.showIf + '" ' : '';
var template = const template =
'<div class="editor-option gf-form-checkbox text-center"' + '<div class="editor-option gf-form-checkbox text-center"' +
showIf + showIf +
'>' + '>' +
@ -119,11 +119,11 @@ function editorCheckbox($compile, $interpolate) {
return { return {
restrict: 'E', restrict: 'E',
link: function(scope, elem, attrs) { link: function(scope, elem, attrs) {
var text = $interpolate(attrs.text)(scope); const text = $interpolate(attrs.text)(scope);
var model = $interpolate(attrs.model)(scope); const model = $interpolate(attrs.model)(scope);
var ngchange = attrs.change ? ' ng-change="' + attrs.change + '"' : ''; const ngchange = attrs.change ? ' ng-change="' + attrs.change + '"' : '';
var tip = attrs.tip ? ' <tip>' + attrs.tip + '</tip>' : ''; const tip = attrs.tip ? ' <tip>' + attrs.tip + '</tip>' : '';
var label = '<label for="' + scope.$id + model + '" class="checkbox-label">' + text + tip + '</label>'; const label = '<label for="' + scope.$id + model + '" class="checkbox-label">' + text + tip + '</label>';
var template = var template =
'<input class="cr1" id="' + '<input class="cr1" id="' +
@ -152,8 +152,8 @@ function editorCheckbox($compile, $interpolate) {
/** @ngInject */ /** @ngInject */
function gfDropdown($parse, $compile, $timeout) { function gfDropdown($parse, $compile, $timeout) {
function buildTemplate(items, placement?) { function buildTemplate(items, placement?) {
var upclass = placement === 'top' ? 'dropup' : ''; const upclass = placement === 'top' ? 'dropup' : '';
var ul = ['<ul class="dropdown-menu ' + upclass + '" role="menu" aria-labelledby="drop1">', '</ul>']; const ul = ['<ul class="dropdown-menu ' + upclass + '" role="menu" aria-labelledby="drop1">', '</ul>'];
for (let index = 0; index < items.length; index++) { for (let index = 0; index < items.length; index++) {
const item = items[index]; const item = items[index];
@ -192,11 +192,11 @@ function gfDropdown($parse, $compile, $timeout) {
restrict: 'EA', restrict: 'EA',
scope: true, scope: true,
link: function postLink(scope, iElement, iAttrs) { link: function postLink(scope, iElement, iAttrs) {
var getter = $parse(iAttrs.gfDropdown), const getter = $parse(iAttrs.gfDropdown),
items = getter(scope); items = getter(scope);
$timeout(function() { $timeout(function() {
var placement = iElement.data('placement'); const placement = iElement.data('placement');
var dropdown = angular.element(buildTemplate(items, placement).join('')); const dropdown = angular.element(buildTemplate(items, placement).join(''));
dropdown.insertAfter(iElement); dropdown.insertAfter(iElement);
$compile(iElement.next('ul.dropdown-menu'))(scope); $compile(iElement.next('ul.dropdown-menu'))(scope);
}); });

View File

@ -47,7 +47,7 @@ function validTimeSpan() {
if (viewValue.indexOf('$') === 0 || viewValue.indexOf('+$') === 0) { if (viewValue.indexOf('$') === 0 || viewValue.indexOf('+$') === 0) {
return true; // allow template variable return true; // allow template variable
} }
var info = rangeUtil.describeTextRange(viewValue); const info = rangeUtil.describeTextRange(viewValue);
return info.invalid !== true; return info.invalid !== true;
}; };
}, },

View File

@ -3,7 +3,7 @@ import coreModule from '../core_module';
function getBlockNodes(nodes) { function getBlockNodes(nodes) {
var node = nodes[0]; var node = nodes[0];
var endNode = nodes[nodes.length - 1]; const endNode = nodes[nodes.length - 1];
var blockNodes; var blockNodes;
for (var i = 1; node !== endNode && (node = node.nextSibling); i++) { for (var i = 1; node !== endNode && (node = node.nextSibling); i++) {

View File

@ -47,7 +47,7 @@ function bootstrapTagsinput() {
scope.model = []; scope.model = [];
} }
var select = $('select', element); const select = $('select', element);
if (attrs.placeholder) { if (attrs.placeholder) {
select.attr('placeholder', attrs.placeholder); select.attr('placeholder', attrs.placeholder);
@ -76,7 +76,7 @@ function bootstrapTagsinput() {
scope.onTagsUpdated(); scope.onTagsUpdated();
} }
} }
var tagElement = select const tagElement = select
.next() .next()
.children('span') .children('span')
.filter(function() { .filter(function() {
@ -86,7 +86,7 @@ function bootstrapTagsinput() {
}); });
select.on('itemRemoved', function(event) { select.on('itemRemoved', function(event) {
var idx = scope.model.indexOf(event.item); const idx = scope.model.indexOf(event.item);
if (idx !== -1) { if (idx !== -1) {
scope.model.splice(idx, 1); scope.model.splice(idx, 1);
if (scope.onTagsUpdated) { if (scope.onTagsUpdated) {

View File

@ -2,10 +2,10 @@ import $ from 'jquery';
import angular from 'angular'; import angular from 'angular';
import _ from 'lodash'; import _ from 'lodash';
var $win = $(window); const $win = $(window);
$.fn.place_tt = (function() { $.fn.place_tt = (function() {
var defaults = { const defaults = {
offset: 5, offset: 5,
}; };
@ -13,9 +13,8 @@ $.fn.place_tt = (function() {
opts = $.extend(true, {}, defaults, opts); opts = $.extend(true, {}, defaults, opts);
return this.each(function() { return this.each(function() {
var $tooltip = $(this), const $tooltip = $(this);
width, let width, height;
height;
$tooltip.addClass('grafana-tooltip'); $tooltip.addClass('grafana-tooltip');
@ -30,7 +29,7 @@ $.fn.place_tt = (function() {
'$compile', '$compile',
'$rootScope', '$rootScope',
function($compile, $rootScope) { function($compile, $rootScope) {
var tmpScope = $rootScope.$new(true); const tmpScope = $rootScope.$new(true);
_.extend(tmpScope, opts.scopeData); _.extend(tmpScope, opts.scopeData);
$compile($tooltip)(tmpScope); $compile($tooltip)(tmpScope);

View File

@ -13,7 +13,7 @@ export class LiveSrv {
} }
getWebSocketUrl() { getWebSocketUrl() {
var l = window.location; const l = window.location;
return (l.protocol === 'https:' ? 'wss://' : 'ws://') + l.host + config.appSubUrl + '/ws'; return (l.protocol === 'https:' ? 'wss://' : 'ws://') + l.host + config.appSubUrl + '/ws';
} }
@ -66,7 +66,7 @@ export class LiveSrv {
return; return;
} }
var observer = this.observers[message.stream]; const observer = this.observers[message.stream];
if (!observer) { if (!observer) {
this.removeObserver(message.stream, null); this.removeObserver(message.stream, null);
return; return;
@ -128,5 +128,5 @@ export class LiveSrv {
} }
} }
var instance = new LiveSrv(); const instance = new LiveSrv();
export { instance as liveSrv }; export { instance as liveSrv };

View File

@ -39,7 +39,7 @@ export class NavModelSrv {
getNav(...args) { getNav(...args) {
var children = this.navItems; var children = this.navItems;
var nav = new NavModel(); const nav = new NavModel();
for (const id of args) { for (const id of args) {
// if its a number then it's the index to use for main // if its a number then it's the index to use for main
@ -69,7 +69,7 @@ export class NavModelSrv {
} }
getNotFoundNav() { getNotFoundNav() {
var node = { const node = {
text: 'Page not found', text: 'Page not found',
icon: 'fa fa-fw fa-warning', icon: 'fa fa-fw fa-warning',
subTitle: '404 Error', subTitle: '404 Error',

View File

@ -64,11 +64,11 @@ export class Profiler {
console.log('Dashboard::Performance Total Watchers: ' + this.getTotalWatcherCount()); console.log('Dashboard::Performance Total Watchers: ' + this.getTotalWatcherCount());
console.log('Dashboard::Performance Total ScopeCount: ' + this.scopeCount); console.log('Dashboard::Performance Total ScopeCount: ' + this.scopeCount);
var timeTaken = this.timings.lastPanelInitializedAt - this.timings.dashboardLoadStart; const timeTaken = this.timings.lastPanelInitializedAt - this.timings.dashboardLoadStart;
console.log('Dashboard::Performance All panels initialized in ' + timeTaken + ' ms'); console.log('Dashboard::Performance All panels initialized in ' + timeTaken + ' ms');
// measure digest performance // measure digest performance
var rootDigestStart = window.performance.now(); const rootDigestStart = window.performance.now();
for (var i = 0; i < 30; i++) { for (var i = 0; i < 30; i++) {
this.$rootScope.$apply(); this.$rootScope.$apply();
} }
@ -80,9 +80,9 @@ export class Profiler {
getTotalWatcherCount() { getTotalWatcherCount() {
var count = 0; var count = 0;
var scopes = 0; var scopes = 0;
var root = $(document.getElementsByTagName('body')); const root = $(document.getElementsByTagName('body'));
var f = function(element) { const f = function(element) {
if (element.data().hasOwnProperty('$scope')) { if (element.data().hasOwnProperty('$scope')) {
scopes++; scopes++;
angular.forEach(element.data().$scope.$$watchers, function() { angular.forEach(element.data().$scope.$$watchers, function() {
@ -126,5 +126,5 @@ export class Profiler {
} }
} }
var profiler = new Profiler(); const profiler = new Profiler();
export { profiler }; export { profiler };

View File

@ -59,7 +59,7 @@ export class ContextSrv {
} }
} }
var contextSrv = new ContextSrv(); const contextSrv = new ContextSrv();
export { contextSrv }; export { contextSrv };
coreModule.factory('contextSrv', function() { coreModule.factory('contextSrv', function() {

View File

@ -6,7 +6,7 @@ export class ImpressionSrv {
constructor() {} constructor() {}
addDashboardImpression(dashboardId) { addDashboardImpression(dashboardId) {
var impressionsKey = this.impressionKey(config); const impressionsKey = this.impressionKey(config);
var impressions = []; var impressions = [];
if (store.exists(impressionsKey)) { if (store.exists(impressionsKey)) {
impressions = JSON.parse(store.get(impressionsKey)); impressions = JSON.parse(store.get(impressionsKey));

View File

@ -52,9 +52,9 @@ function applied(fn, scope) {
if (fn.wrappedInApply) { if (fn.wrappedInApply) {
return fn; return fn;
} }
var wrapped: any = function() { const wrapped: any = function() {
var args = arguments; const args = arguments;
var phase = scope.$root.$$phase; const phase = scope.$root.$$phase;
if (phase === '$apply' || phase === '$digest') { if (phase === '$apply' || phase === '$digest') {
return fn.apply(null, args); return fn.apply(null, args);
} else { } else {
@ -81,8 +81,8 @@ function applied(fn, scope) {
*/ */
function applyFunctions(obj, scope, propsConfig?) { function applyFunctions(obj, scope, propsConfig?) {
return Object.keys(obj || {}).reduce(function(prev, key) { return Object.keys(obj || {}).reduce(function(prev, key) {
var value = obj[key]; const value = obj[key];
var config = (propsConfig || {})[key] || {}; const config = (propsConfig || {})[key] || {};
/** /**
* wrap functions in a function that ensures they are scope.$applied * wrap functions in a function that ensures they are scope.$applied
* ensures that when function is called from a React component * ensures that when function is called from a React component
@ -103,14 +103,14 @@ function applyFunctions(obj, scope, propsConfig?) {
* If watchDepth attribute is NOT reference or collection, watchDepth defaults to deep watching by value * If watchDepth attribute is NOT reference or collection, watchDepth defaults to deep watching by value
*/ */
function watchProps(watchDepth, scope, watchExpressions, listener) { function watchProps(watchDepth, scope, watchExpressions, listener) {
var supportsWatchCollection = angular.isFunction(scope.$watchCollection); const supportsWatchCollection = angular.isFunction(scope.$watchCollection);
var supportsWatchGroup = angular.isFunction(scope.$watchGroup); const supportsWatchGroup = angular.isFunction(scope.$watchGroup);
var watchGroupExpressions = []; const watchGroupExpressions = [];
watchExpressions.forEach(function(expr) { watchExpressions.forEach(function(expr) {
var actualExpr = getPropExpression(expr); const actualExpr = getPropExpression(expr);
var exprWatchDepth = getPropWatchDepth(watchDepth, expr); const exprWatchDepth = getPropWatchDepth(watchDepth, expr);
if (exprWatchDepth === 'collection' && supportsWatchCollection) { if (exprWatchDepth === 'collection' && supportsWatchCollection) {
scope.$watchCollection(actualExpr, listener); scope.$watchCollection(actualExpr, listener);
@ -156,7 +156,7 @@ function getPropExpression(prop) {
// find the normalized attribute knowing that React props accept any type of capitalization // find the normalized attribute knowing that React props accept any type of capitalization
function findAttribute(attrs, propName) { function findAttribute(attrs, propName) {
var index = Object.keys(attrs).filter(function(attr) { const index = Object.keys(attrs).filter(function(attr) {
return attr.toLowerCase() === propName.toLowerCase(); return attr.toLowerCase() === propName.toLowerCase();
})[0]; })[0];
return attrs[index]; return attrs[index];
@ -164,7 +164,7 @@ function findAttribute(attrs, propName) {
// get watch depth of prop (string or array) // get watch depth of prop (string or array)
function getPropWatchDepth(defaultWatch, prop) { function getPropWatchDepth(defaultWatch, prop) {
var customWatchDepth = Array.isArray(prop) && angular.isObject(prop[1]) && prop[1].watchDepth; const customWatchDepth = Array.isArray(prop) && angular.isObject(prop[1]) && prop[1].watchDepth;
return customWatchDepth || defaultWatch; return customWatchDepth || defaultWatch;
} }
@ -186,16 +186,16 @@ function getPropWatchDepth(defaultWatch, prop) {
// } // }
// })); // }));
// //
var reactComponent = function($injector) { const reactComponent = function($injector) {
return { return {
restrict: 'E', restrict: 'E',
replace: true, replace: true,
link: function(scope, elem, attrs) { link: function(scope, elem, attrs) {
var reactComponent = getReactComponent(attrs.name, $injector); const reactComponent = getReactComponent(attrs.name, $injector);
var renderMyComponent = function() { const renderMyComponent = function() {
var scopeProps = scope.$eval(attrs.props); const scopeProps = scope.$eval(attrs.props);
var props = applyFunctions(scopeProps, scope); const props = applyFunctions(scopeProps, scope);
renderComponent(reactComponent, props, scope, elem); renderComponent(reactComponent, props, scope, elem);
}; };
@ -243,24 +243,24 @@ var reactComponent = function($injector) {
// //
// <hello name="name"/> // <hello name="name"/>
// //
var reactDirective = function($injector) { const reactDirective = function($injector) {
return function(reactComponentName, props, conf, injectableProps) { return function(reactComponentName, props, conf, injectableProps) {
var directive = { const directive = {
restrict: 'E', restrict: 'E',
replace: true, replace: true,
link: function(scope, elem, attrs) { link: function(scope, elem, attrs) {
var reactComponent = getReactComponent(reactComponentName, $injector); const reactComponent = getReactComponent(reactComponentName, $injector);
// if props is not defined, fall back to use the React component's propTypes if present // if props is not defined, fall back to use the React component's propTypes if present
props = props || Object.keys(reactComponent.propTypes || {}); props = props || Object.keys(reactComponent.propTypes || {});
// for each of the properties, get their scope value and set it to scope.props // for each of the properties, get their scope value and set it to scope.props
var renderMyComponent = function() { const renderMyComponent = function() {
var scopeProps = {}, var scopeProps = {};
config = {}; const config = {};
props.forEach(function(prop) { props.forEach(function(prop) {
var propName = getPropName(prop); const propName = getPropName(prop);
scopeProps[propName] = scope.$eval(findAttribute(attrs, propName)); scopeProps[propName] = scope.$eval(findAttribute(attrs, propName));
config[propName] = getPropConfig(prop); config[propName] = getPropConfig(prop);
}); });
@ -272,7 +272,7 @@ var reactDirective = function($injector) {
// watch each property name and trigger an update whenever something changes, // watch each property name and trigger an update whenever something changes,
// to update scope.props with new values // to update scope.props with new values
var propExpressions = props.map(function(prop) { const propExpressions = props.map(function(prop) {
return Array.isArray(prop) ? [attrs[getPropName(prop)], getPropConfig(prop)] : attrs[prop]; return Array.isArray(prop) ? [attrs[getPropName(prop)], getPropConfig(prop)] : attrs[prop];
}); });

View File

@ -31,7 +31,7 @@ export class SearchSrv {
} }
private queryForRecentDashboards() { private queryForRecentDashboards() {
var dashIds = _.take(impressionSrv.getDashboardOpened(), 5); const dashIds = _.take(impressionSrv.getDashboardOpened(), 5);
if (dashIds.length === 0) { if (dashIds.length === 0) {
return Promise.resolve([]); return Promise.resolve([]);
} }

View File

@ -1,7 +1,7 @@
import _ from 'lodash'; import _ from 'lodash';
import moment from 'moment'; import moment from 'moment';
var units = ['y', 'M', 'w', 'd', 'h', 'm', 's']; const units = ['y', 'M', 'w', 'd', 'h', 'm', 's'];
export function parse(text, roundUp?, timezone?) { export function parse(text, roundUp?, timezone?) {
if (!text) { if (!text) {
@ -47,7 +47,7 @@ export function parse(text, roundUp?, timezone?) {
} }
export function isValid(text) { export function isValid(text) {
var date = parse(text); const date = parse(text);
if (!date) { if (!date) {
return false; return false;
} }
@ -60,12 +60,12 @@ export function isValid(text) {
} }
export function parseDateMath(mathString, time, roundUp?) { export function parseDateMath(mathString, time, roundUp?) {
var dateTime = time; const dateTime = time;
var i = 0; var i = 0;
var len = mathString.length; const len = mathString.length;
while (i < len) { while (i < len) {
var c = mathString.charAt(i++); const c = mathString.charAt(i++);
var type; var type;
var num; var num;
var unit; var unit;
@ -85,7 +85,7 @@ export function parseDateMath(mathString, time, roundUp?) {
} else if (mathString.length === 2) { } else if (mathString.length === 2) {
num = mathString.charAt(i); num = mathString.charAt(i);
} else { } else {
var numFrom = i; const numFrom = i;
while (!isNaN(mathString.charAt(i))) { while (!isNaN(mathString.charAt(i))) {
i++; i++;
if (i > 10) { if (i > 10) {

View File

@ -15,7 +15,7 @@ export class Emitter {
this.emitter.on(name, handler); this.emitter.on(name, handler);
if (scope) { if (scope) {
var unbind = scope.$on('$destroy', () => { const unbind = scope.$on('$destroy', () => {
this.emitter.off(name, handler); this.emitter.off(name, handler);
unbind(); unbind();
}); });

View File

@ -1,5 +1,5 @@
export function assignModelProperties(target, source, defaults, removeDefaults?) { export function assignModelProperties(target, source, defaults, removeDefaults?) {
for (var key in defaults) { for (const key in defaults) {
if (!defaults.hasOwnProperty(key)) { if (!defaults.hasOwnProperty(key)) {
continue; continue;
} }

View File

@ -2,10 +2,10 @@
function outlineFixer() { function outlineFixer() {
const d: any = document; const d: any = document;
var style_element = d.createElement('STYLE'); const style_element = d.createElement('STYLE');
var dom_events = 'addEventListener' in d; const dom_events = 'addEventListener' in d;
var add_event_listener = function(type, callback) { const add_event_listener = function(type, callback) {
// Basic cross-browser event handling // Basic cross-browser event handling
if (dom_events) { if (dom_events) {
d.addEventListener(type, callback); d.addEventListener(type, callback);
@ -14,7 +14,7 @@ function outlineFixer() {
} }
}; };
var set_css = function(css_text) { const set_css = function(css_text) {
// Handle setting of <style> element contents in IE8 // Handle setting of <style> element contents in IE8
!!style_element.styleSheet ? (style_element.styleSheet.cssText = css_text) : (style_element.innerHTML = css_text); !!style_element.styleSheet ? (style_element.styleSheet.cssText = css_text) : (style_element.innerHTML = css_text);
}; };

View File

@ -6,7 +6,7 @@ export default function sortByKeys(input) {
} }
if (_.isPlainObject(input)) { if (_.isPlainObject(input)) {
var sortedObject = {}; const sortedObject = {};
for (const key of _.keys(input).sort()) { for (const key of _.keys(input).sort()) {
sortedObject[key] = sortByKeys(input[key]); sortedObject[key] = sortByKeys(input[key]);
} }

View File

@ -11,9 +11,9 @@ export function tickStep(start: number, stop: number, count: number): number {
e5 = Math.sqrt(10), e5 = Math.sqrt(10),
e2 = Math.sqrt(2); e2 = Math.sqrt(2);
let step0 = Math.abs(stop - start) / Math.max(0, count), const step0 = Math.abs(stop - start) / Math.max(0, count);
step1 = Math.pow(10, Math.floor(Math.log(step0) / Math.LN10)), let step1 = Math.pow(10, Math.floor(Math.log(step0) / Math.LN10));
error = step0 / step1; const error = step0 / step1;
if (error >= e10) { if (error >= e10) {
step1 *= 10; step1 *= 10;
@ -39,13 +39,13 @@ export function getScaledDecimals(decimals, tick_size) {
* @param tickDecimals Tick decimal precision * @param tickDecimals Tick decimal precision
*/ */
export function getFlotTickSize(min: number, max: number, noTicks: number, tickDecimals: number) { export function getFlotTickSize(min: number, max: number, noTicks: number, tickDecimals: number) {
var delta = (max - min) / noTicks, const delta = (max - min) / noTicks;
dec = -Math.floor(Math.log(delta) / Math.LN10), let dec = -Math.floor(Math.log(delta) / Math.LN10);
maxDec = tickDecimals; const maxDec = tickDecimals;
var magn = Math.pow(10, -dec), const magn = Math.pow(10, -dec);
norm = delta / magn, // norm is between 1.0 and 10.0 const norm = delta / magn; // norm is between 1.0 and 10.0
size; let size;
if (norm < 1.5) { if (norm < 1.5) {
size = 1; size = 1;
@ -81,8 +81,8 @@ export function getFlotRange(panelMin, panelMax, datamin, datamax) {
if (delta === 0.0) { if (delta === 0.0) {
// Grafana fix: wide Y min and max using increased wideFactor // Grafana fix: wide Y min and max using increased wideFactor
// when all series values are the same // when all series values are the same
var wideFactor = 0.25; const wideFactor = 0.25;
var widen = Math.abs(max === 0 ? 1 : max * wideFactor); const widen = Math.abs(max === 0 ? 1 : max * wideFactor);
if (panelMin === null) { if (panelMin === null) {
min -= widen; min -= widen;
@ -94,7 +94,7 @@ export function getFlotRange(panelMin, panelMax, datamin, datamax) {
} }
} else { } else {
// consider autoscaling // consider autoscaling
var margin = autoscaleMargin; const margin = autoscaleMargin;
if (margin != null) { if (margin != null) {
if (panelMin == null) { if (panelMin == null) {
min -= delta * margin; min -= delta * margin;

View File

@ -1,7 +1,7 @@
import _ from 'lodash'; import _ from 'lodash';
import { QueryPartDef, QueryPart } from 'app/core/components/query_part/query_part'; import { QueryPartDef, QueryPart } from 'app/core/components/query_part/query_part';
var alertQueryDef = new QueryPartDef({ const alertQueryDef = new QueryPartDef({
type: 'query', type: 'query',
params: [ params: [
{ name: 'queryRefId', type: 'string', dynamicLookup: true }, { name: 'queryRefId', type: 'string', dynamicLookup: true },
@ -15,9 +15,9 @@ var alertQueryDef = new QueryPartDef({
defaultParams: ['#A', '15m', 'now', 'avg'], defaultParams: ['#A', '15m', 'now', 'avg'],
}); });
var conditionTypes = [{ text: 'Query', value: 'query' }]; const conditionTypes = [{ text: 'Query', value: 'query' }];
var alertStateSortScore = { const alertStateSortScore = {
alerting: 1, alerting: 1,
no_data: 2, no_data: 2,
pending: 3, pending: 3,
@ -25,7 +25,7 @@ var alertStateSortScore = {
paused: 5, paused: 5,
}; };
var evalFunctions = [ const evalFunctions = [
{ text: 'IS ABOVE', value: 'gt' }, { text: 'IS ABOVE', value: 'gt' },
{ text: 'IS BELOW', value: 'lt' }, { text: 'IS BELOW', value: 'lt' },
{ text: 'IS OUTSIDE RANGE', value: 'outside_range' }, { text: 'IS OUTSIDE RANGE', value: 'outside_range' },
@ -33,9 +33,9 @@ var evalFunctions = [
{ text: 'HAS NO VALUE', value: 'no_value' }, { text: 'HAS NO VALUE', value: 'no_value' },
]; ];
var evalOperators = [{ text: 'OR', value: 'or' }, { text: 'AND', value: 'and' }]; const evalOperators = [{ text: 'OR', value: 'or' }, { text: 'AND', value: 'and' }];
var reducerTypes = [ const reducerTypes = [
{ text: 'avg()', value: 'avg' }, { text: 'avg()', value: 'avg' },
{ text: 'min()', value: 'min' }, { text: 'min()', value: 'min' },
{ text: 'max()', value: 'max' }, { text: 'max()', value: 'max' },
@ -48,17 +48,17 @@ var reducerTypes = [
{ text: 'count_non_null()', value: 'count_non_null' }, { text: 'count_non_null()', value: 'count_non_null' },
]; ];
var noDataModes = [ const noDataModes = [
{ text: 'Alerting', value: 'alerting' }, { text: 'Alerting', value: 'alerting' },
{ text: 'No Data', value: 'no_data' }, { text: 'No Data', value: 'no_data' },
{ text: 'Keep Last State', value: 'keep_state' }, { text: 'Keep Last State', value: 'keep_state' },
{ text: 'Ok', value: 'ok' }, { text: 'Ok', value: 'ok' },
]; ];
var executionErrorModes = [{ text: 'Alerting', value: 'alerting' }, { text: 'Keep Last State', value: 'keep_state' }]; const executionErrorModes = [{ text: 'Alerting', value: 'alerting' }, { text: 'Keep Last State', value: 'keep_state' }];
function createReducerPart(model) { function createReducerPart(model) {
var def = new QueryPartDef({ type: model.type, defaultParams: [] }); const def = new QueryPartDef({ type: model.type, defaultParams: [] });
return new QueryPart(model, def); return new QueryPart(model, def);
} }

View File

@ -50,7 +50,7 @@ export class AlertTabCtrl {
this.addNotificationSegment = this.uiSegmentSrv.newPlusButton(); this.addNotificationSegment = this.uiSegmentSrv.newPlusButton();
// subscribe to graph threshold handle changes // subscribe to graph threshold handle changes
var thresholdChangedEventHandler = this.graphThresholdChanged.bind(this); const thresholdChangedEventHandler = this.graphThresholdChanged.bind(this);
this.panelCtrl.events.on('threshold-changed', thresholdChangedEventHandler); this.panelCtrl.events.on('threshold-changed', thresholdChangedEventHandler);
// set panel alert edit mode // set panel alert edit mode
@ -129,7 +129,7 @@ export class AlertTabCtrl {
} }
notificationAdded() { notificationAdded() {
var model = _.find(this.notifications, { const model = _.find(this.notifications, {
name: this.addNotificationSegment.value, name: this.addNotificationSegment.value,
}); });
if (!model) { if (!model) {
@ -154,7 +154,7 @@ export class AlertTabCtrl {
} }
initModel() { initModel() {
var alert = (this.alert = this.panel.alert); const alert = (this.alert = this.panel.alert);
if (!alert) { if (!alert) {
return; return;
} }
@ -170,7 +170,7 @@ export class AlertTabCtrl {
alert.handler = alert.handler || 1; alert.handler = alert.handler || 1;
alert.notifications = alert.notifications || []; alert.notifications = alert.notifications || [];
var defaultName = this.panel.title + ' alert'; const defaultName = this.panel.title + ' alert';
alert.name = alert.name || defaultName; alert.name = alert.name || defaultName;
this.conditionModels = _.reduce( this.conditionModels = _.reduce(
@ -185,7 +185,7 @@ export class AlertTabCtrl {
ThresholdMapper.alertToGraphThresholds(this.panel); ThresholdMapper.alertToGraphThresholds(this.panel);
for (const addedNotification of alert.notifications) { for (const addedNotification of alert.notifications) {
var model = _.find(this.notifications, { id: addedNotification.id }); const model = _.find(this.notifications, { id: addedNotification.id });
if (model && model.isDefault === false) { if (model && model.isDefault === false) {
model.iconClass = this.getNotificationIcon(model.type); model.iconClass = this.getNotificationIcon(model.type);
this.alertNotifications.push(model); this.alertNotifications.push(model);
@ -205,7 +205,7 @@ export class AlertTabCtrl {
} }
graphThresholdChanged(evt) { graphThresholdChanged(evt) {
for (var condition of this.alert.conditions) { for (const condition of this.alert.conditions) {
if (condition.type === 'query') { if (condition.type === 'query') {
condition.evaluator.params[evt.handleIndex] = evt.threshold.value; condition.evaluator.params[evt.handleIndex] = evt.threshold.value;
this.evaluatorParamsChanged(); this.evaluatorParamsChanged();
@ -232,12 +232,12 @@ export class AlertTabCtrl {
let firstTarget; let firstTarget;
let foundTarget = null; let foundTarget = null;
for (var condition of this.alert.conditions) { for (const condition of this.alert.conditions) {
if (condition.type !== 'query') { if (condition.type !== 'query') {
continue; continue;
} }
for (var target of this.panel.targets) { for (const target of this.panel.targets) {
if (!firstTarget) { if (!firstTarget) {
firstTarget = target; firstTarget = target;
} }
@ -256,7 +256,7 @@ export class AlertTabCtrl {
} }
} }
var datasourceName = foundTarget.datasource || this.panel.datasource; const datasourceName = foundTarget.datasource || this.panel.datasource;
this.datasourceSrv.get(datasourceName).then(ds => { this.datasourceSrv.get(datasourceName).then(ds => {
if (!ds.meta.alerting) { if (!ds.meta.alerting) {
this.error = 'The datasource does not support alerting queries'; this.error = 'The datasource does not support alerting queries';
@ -270,7 +270,7 @@ export class AlertTabCtrl {
} }
buildConditionModel(source) { buildConditionModel(source) {
var cm: any = { source: source, type: source.type }; const cm: any = { source: source, type: source.type };
cm.queryPart = new QueryPart(source.query, alertDef.alertQueryDef); cm.queryPart = new QueryPart(source.query, alertDef.alertQueryDef);
cm.reducerPart = alertDef.createReducerPart(source.reducer); cm.reducerPart = alertDef.createReducerPart(source.reducer);
@ -292,7 +292,7 @@ export class AlertTabCtrl {
this.validateModel(); this.validateModel();
} }
case 'get-param-options': { case 'get-param-options': {
var result = this.panel.targets.map(target => { const result = this.panel.targets.map(target => {
return this.uiSegmentSrv.newSegment({ value: target.refId }); return this.uiSegmentSrv.newSegment({ value: target.refId });
}); });
@ -309,8 +309,8 @@ export class AlertTabCtrl {
break; break;
} }
case 'get-part-actions': { case 'get-part-actions': {
var result = []; const result = [];
for (var type of alertDef.reducerTypes) { for (const type of alertDef.reducerTypes) {
if (type.value !== conditionModel.source.reducer.type) { if (type.value !== conditionModel.source.reducer.type) {
result.push(type); result.push(type);
} }
@ -321,7 +321,7 @@ export class AlertTabCtrl {
} }
addCondition(type) { addCondition(type) {
var condition = this.buildDefaultCondition(); const condition = this.buildDefaultCondition();
// add to persited model // add to persited model
this.alert.conditions.push(condition); this.alert.conditions.push(condition);
// add to view model // add to view model
@ -406,7 +406,7 @@ export class AlertTabCtrl {
this.testing = true; this.testing = true;
this.testResult = false; this.testResult = false;
var payload = { const payload = {
dashboard: this.dashboardSrv.getCurrent().getSaveModelClone(), dashboard: this.dashboardSrv.getCurrent().getSaveModelClone(),
panelId: this.panelCtrl.panel.id, panelId: this.panelCtrl.panel.id,
}; };

View File

@ -6,8 +6,8 @@ export class ThresholdMapper {
continue; continue;
} }
var evaluator = condition.evaluator; const evaluator = condition.evaluator;
var thresholds = (panel.thresholds = []); const thresholds = (panel.thresholds = []);
switch (evaluator.type) { switch (evaluator.type) {
case 'gt': { case 'gt': {
@ -51,13 +51,13 @@ export class ThresholdMapper {
break; break;
} }
for (var t of panel.thresholds) { for (const t of panel.thresholds) {
t.fill = true; t.fill = true;
t.line = true; t.line = true;
t.colorMode = 'critical'; t.colorMode = 'critical';
} }
var updated = true; const updated = true;
return updated; return updated;
} }
} }

View File

@ -19,8 +19,8 @@ export class DashboardMigrator {
updateSchema(old) { updateSchema(old) {
var i, j, k, n; var i, j, k, n;
var oldVersion = this.dashboard.schemaVersion; const oldVersion = this.dashboard.schemaVersion;
var panelUpgrades = []; const panelUpgrades = [];
this.dashboard.schemaVersion = 16; this.dashboard.schemaVersion = 16;
if (oldVersion === this.dashboard.schemaVersion) { if (oldVersion === this.dashboard.schemaVersion) {
@ -108,7 +108,7 @@ export class DashboardMigrator {
if (oldVersion < 6) { if (oldVersion < 6) {
// move pulldowns to new schema // move pulldowns to new schema
var annotations = _.find(old.pulldowns, { type: 'annotations' }); const annotations = _.find(old.pulldowns, { type: 'annotations' });
if (annotations) { if (annotations) {
this.dashboard.annotations = { this.dashboard.annotations = {
@ -118,7 +118,7 @@ export class DashboardMigrator {
// update template variables // update template variables
for (i = 0; i < this.dashboard.templating.list.length; i++) { for (i = 0; i < this.dashboard.templating.list.length; i++) {
var variable = this.dashboard.templating.list[i]; const variable = this.dashboard.templating.list[i];
if (variable.datasource === void 0) { if (variable.datasource === void 0) {
variable.datasource = null; variable.datasource = null;
} }
@ -162,7 +162,7 @@ export class DashboardMigrator {
delete target.fill; delete target.fill;
} else { } else {
target.select = _.map(target.fields, function(field) { target.select = _.map(target.fields, function(field) {
var parts = []; const parts = [];
parts.push({ type: 'field', params: [field.name] }); parts.push({ type: 'field', params: [field.name] });
parts.push({ type: field.func, params: [] }); parts.push({ type: field.func, params: [] });
if (field.mathExpr) { if (field.mathExpr) {
@ -204,7 +204,7 @@ export class DashboardMigrator {
} }
if (panel.thresholds) { if (panel.thresholds) {
var k = panel.thresholds.split(','); const k = panel.thresholds.split(',');
if (k.length >= 3) { if (k.length >= 3) {
k.shift(); k.shift();
@ -224,7 +224,7 @@ export class DashboardMigrator {
_.each(panel.styles, function(style) { _.each(panel.styles, function(style) {
if (style.thresholds && style.thresholds.length >= 3) { if (style.thresholds && style.thresholds.length >= 3) {
var k = style.thresholds; const k = style.thresholds;
k.shift(); k.shift();
style.thresholds = k; style.thresholds = k;
} }
@ -309,7 +309,7 @@ export class DashboardMigrator {
} }
panel.thresholds = []; panel.thresholds = [];
var t1: any = {}, const t1: any = {},
t2: any = {}; t2: any = {};
if (panel.grid.threshold1 !== null) { if (panel.grid.threshold1 !== null) {

View File

@ -145,7 +145,7 @@ export class DashboardModel {
// make clone // make clone
var copy: any = {}; var copy: any = {};
for (var property in this) { for (const property in this) {
if (DashboardModel.nonPersistedProperties[property] || !this.hasOwnProperty(property)) { if (DashboardModel.nonPersistedProperties[property] || !this.hasOwnProperty(property)) {
continue; continue;
} }
@ -542,7 +542,7 @@ export class DashboardModel {
} }
removePanel(panel: PanelModel) { removePanel(panel: PanelModel) {
var index = _.indexOf(this.panels, panel); const index = _.indexOf(this.panels, panel);
this.panels.splice(index, 1); this.panels.splice(index, 1);
this.events.emit('panel-removed', panel); this.events.emit('panel-removed', panel);
} }
@ -559,7 +559,7 @@ export class DashboardModel {
expandRows() { expandRows() {
for (let i = 0; i < this.panels.length; i++) { for (let i = 0; i < this.panels.length; i++) {
var panel = this.panels[i]; const panel = this.panels[i];
if (panel.type !== 'row') { if (panel.type !== 'row') {
continue; continue;
@ -573,7 +573,7 @@ export class DashboardModel {
collapseRows() { collapseRows() {
for (let i = 0; i < this.panels.length; i++) { for (let i = 0; i < this.panels.length; i++) {
var panel = this.panels[i]; const panel = this.panels[i];
if (panel.type !== 'row') { if (panel.type !== 'row') {
continue; continue;
@ -595,12 +595,12 @@ export class DashboardModel {
return true; return true;
} }
var visibleVars = _.filter(this.templating.list, variable => variable.hide !== 2); const visibleVars = _.filter(this.templating.list, variable => variable.hide !== 2);
if (visibleVars.length > 0) { if (visibleVars.length > 0) {
return true; return true;
} }
var visibleAnnotations = _.filter(this.annotations.list, annotation => annotation.hide !== true); const visibleAnnotations = _.filter(this.annotations.list, annotation => annotation.hide !== true);
if (visibleAnnotations.length > 0) { if (visibleAnnotations.length > 0) {
return true; return true;
} }
@ -773,7 +773,7 @@ export class DashboardModel {
} }
getNextQueryLetter(panel) { getNextQueryLetter(panel) {
var letters = 'ABCDEFGHIJKLMNOPQRSTUVWXYZ'; const letters = 'ABCDEFGHIJKLMNOPQRSTUVWXYZ';
return _.find(letters, function(refId) { return _.find(letters, function(refId) {
return _.every(panel.targets, function(other) { return _.every(panel.targets, function(other) {

View File

@ -41,7 +41,7 @@ export class PanelModel {
this.events = new Emitter(); this.events = new Emitter();
// copy properties from persisted model // copy properties from persisted model
for (var property in model) { for (const property in model) {
this[property] = model[property]; this[property] = model[property];
} }
@ -52,7 +52,7 @@ export class PanelModel {
getSaveModel() { getSaveModel() {
const model: any = {}; const model: any = {};
for (var property in this) { for (const property in this) {
if (notPersistedProperties[property] || !this.hasOwnProperty(property)) { if (notPersistedProperties[property] || !this.hasOwnProperty(property)) {
continue; continue;
} }

View File

@ -164,7 +164,7 @@ class MetricsPanelCtrl extends PanelCtrl {
intervalOverride = this.datasource.interval; intervalOverride = this.datasource.interval;
} }
var res = kbn.calculateInterval(this.range, this.resolution, intervalOverride); const res = kbn.calculateInterval(this.range, this.resolution, intervalOverride);
this.interval = res.interval; this.interval = res.interval;
this.intervalMs = res.intervalMs; this.intervalMs = res.intervalMs;
} }
@ -174,15 +174,15 @@ class MetricsPanelCtrl extends PanelCtrl {
// check panel time overrrides // check panel time overrrides
if (this.panel.timeFrom) { if (this.panel.timeFrom) {
var timeFromInterpolated = this.templateSrv.replace(this.panel.timeFrom, this.panel.scopedVars); const timeFromInterpolated = this.templateSrv.replace(this.panel.timeFrom, this.panel.scopedVars);
var timeFromInfo = rangeUtil.describeTextRange(timeFromInterpolated); const timeFromInfo = rangeUtil.describeTextRange(timeFromInterpolated);
if (timeFromInfo.invalid) { if (timeFromInfo.invalid) {
this.timeInfo = 'invalid time override'; this.timeInfo = 'invalid time override';
return; return;
} }
if (_.isString(this.range.raw.from)) { if (_.isString(this.range.raw.from)) {
var timeFromDate = dateMath.parse(timeFromInfo.from); const timeFromDate = dateMath.parse(timeFromInfo.from);
this.timeInfo = timeFromInfo.display; this.timeInfo = timeFromInfo.display;
this.range.from = timeFromDate; this.range.from = timeFromDate;
this.range.to = dateMath.parse(timeFromInfo.to); this.range.to = dateMath.parse(timeFromInfo.to);
@ -192,14 +192,14 @@ class MetricsPanelCtrl extends PanelCtrl {
} }
if (this.panel.timeShift) { if (this.panel.timeShift) {
var timeShiftInterpolated = this.templateSrv.replace(this.panel.timeShift, this.panel.scopedVars); const timeShiftInterpolated = this.templateSrv.replace(this.panel.timeShift, this.panel.scopedVars);
var timeShiftInfo = rangeUtil.describeTextRange(timeShiftInterpolated); const timeShiftInfo = rangeUtil.describeTextRange(timeShiftInterpolated);
if (timeShiftInfo.invalid) { if (timeShiftInfo.invalid) {
this.timeInfo = 'invalid timeshift'; this.timeInfo = 'invalid timeshift';
return; return;
} }
var timeShift = '-' + timeShiftInterpolated; const timeShift = '-' + timeShiftInterpolated;
this.timeInfo += ' timeshift ' + timeShift; this.timeInfo += ' timeshift ' + timeShift;
this.range.from = dateMath.parseDateMath(timeShift, this.range.from, false); this.range.from = dateMath.parseDateMath(timeShift, this.range.from, false);
this.range.to = dateMath.parseDateMath(timeShift, this.range.to, true); this.range.to = dateMath.parseDateMath(timeShift, this.range.to, true);
@ -220,12 +220,12 @@ class MetricsPanelCtrl extends PanelCtrl {
// make shallow copy of scoped vars, // make shallow copy of scoped vars,
// and add built in variables interval and interval_ms // and add built in variables interval and interval_ms
var scopedVars = Object.assign({}, this.panel.scopedVars, { const scopedVars = Object.assign({}, this.panel.scopedVars, {
__interval: { text: this.interval, value: this.interval }, __interval: { text: this.interval, value: this.interval },
__interval_ms: { text: this.intervalMs, value: this.intervalMs }, __interval_ms: { text: this.intervalMs, value: this.intervalMs },
}); });
var metricsQuery = { const metricsQuery = {
timezone: this.dashboard.getTimezone(), timezone: this.dashboard.getTimezone(),
panelId: this.panel.id, panelId: this.panel.id,
dashboardId: this.dashboard.id, dashboardId: this.dashboard.id,
@ -343,14 +343,14 @@ class MetricsPanelCtrl extends PanelCtrl {
} }
removeQuery(target) { removeQuery(target) {
var index = _.indexOf(this.panel.targets, target); const index = _.indexOf(this.panel.targets, target);
this.panel.targets.splice(index, 1); this.panel.targets.splice(index, 1);
this.nextRefId = this.dashboard.getNextQueryLetter(this.panel); this.nextRefId = this.dashboard.getNextQueryLetter(this.panel);
this.refresh(); this.refresh();
} }
moveQuery(target, direction) { moveQuery(target, direction) {
var index = _.indexOf(this.panel.targets, target); const index = _.indexOf(this.panel.targets, target);
_.move(this.panel.targets, index, index + direction); _.move(this.panel.targets, index, index + direction);
} }
} }

View File

@ -92,7 +92,7 @@ export class MetricsTabCtrl {
this.helpOpen = !this.helpOpen; this.helpOpen = !this.helpOpen;
this.backendSrv.get(`/api/plugins/${this.datasourceInstance.meta.id}/markdown/query_help`).then(res => { this.backendSrv.get(`/api/plugins/${this.datasourceInstance.meta.id}/markdown/query_help`).then(res => {
var md = new Remarkable(); const md = new Remarkable();
this.helpHtml = this.$sce.trustAsHtml(md.render(res)); this.helpHtml = this.$sce.trustAsHtml(md.render(res));
}); });
} }

View File

@ -43,7 +43,7 @@ export class PanelCtrl {
this.events = this.panel.events; this.events = this.panel.events;
this.timing = {}; this.timing = {};
var plugin = config.panels[this.panel.type]; const plugin = config.panels[this.panel.type];
if (plugin) { if (plugin) {
this.pluginId = plugin.id; this.pluginId = plugin.id;
this.pluginName = plugin.name; this.pluginName = plugin.name;
@ -105,7 +105,7 @@ export class PanelCtrl {
this.editModeInitiated = true; this.editModeInitiated = true;
this.events.emit('init-edit-mode', null); this.events.emit('init-edit-mode', null);
var urlTab = (this.$injector.get('$routeParams').tab || '').toLowerCase(); const urlTab = (this.$injector.get('$routeParams').tab || '').toLowerCase();
if (urlTab) { if (urlTab) {
this.editorTabs.forEach((tab, i) => { this.editorTabs.forEach((tab, i) => {
if (tab.title.toLowerCase() === urlTab) { if (tab.title.toLowerCase() === urlTab) {
@ -117,13 +117,13 @@ export class PanelCtrl {
changeTab(newIndex) { changeTab(newIndex) {
this.editorTabIndex = newIndex; this.editorTabIndex = newIndex;
var route = this.$injector.get('$route'); const route = this.$injector.get('$route');
route.current.params.tab = this.editorTabs[newIndex].title.toLowerCase(); route.current.params.tab = this.editorTabs[newIndex].title.toLowerCase();
route.updateParams(); route.updateParams();
} }
addEditorTab(title, directiveFn, index?) { addEditorTab(title, directiveFn, index?) {
var editorTab = { title, directiveFn }; const editorTab = { title, directiveFn };
if (_.isString(directiveFn)) { if (_.isString(directiveFn)) {
editorTab.directiveFn = function() { editorTab.directiveFn = function() {
@ -225,9 +225,9 @@ export class PanelCtrl {
calculatePanelHeight() { calculatePanelHeight() {
if (this.fullscreen) { if (this.fullscreen) {
var docHeight = $(window).height(); const docHeight = $(window).height();
var editHeight = Math.floor(docHeight * 0.4); const editHeight = Math.floor(docHeight * 0.4);
var fullscreenHeight = Math.floor(docHeight * 0.8); const fullscreenHeight = Math.floor(docHeight * 0.8);
this.containerHeight = this.editMode ? editHeight : fullscreenHeight; this.containerHeight = this.editMode ? editHeight : fullscreenHeight;
} else { } else {
this.containerHeight = this.panel.gridPos.h * GRID_CELL_HEIGHT + (this.panel.gridPos.h - 1) * GRID_CELL_VMARGIN; this.containerHeight = this.panel.gridPos.h * GRID_CELL_HEIGHT + (this.panel.gridPos.h - 1) * GRID_CELL_VMARGIN;
@ -293,7 +293,7 @@ export class PanelCtrl {
} }
sharePanel() { sharePanel() {
var shareScope = this.$scope.$new(); const shareScope = this.$scope.$new();
shareScope.panel = this.panel; shareScope.panel = this.panel;
shareScope.dashboard = this.dashboard; shareScope.dashboard = this.dashboard;
@ -323,10 +323,10 @@ export class PanelCtrl {
markdown = this.error || this.panel.description; markdown = this.error || this.panel.description;
} }
var linkSrv = this.$injector.get('linkSrv'); const linkSrv = this.$injector.get('linkSrv');
var sanitize = this.$injector.get('$sanitize'); const sanitize = this.$injector.get('$sanitize');
var templateSrv = this.$injector.get('templateSrv'); const templateSrv = this.$injector.get('templateSrv');
var interpolatedMarkdown = templateSrv.replace(markdown, this.panel.scopedVars); const interpolatedMarkdown = templateSrv.replace(markdown, this.panel.scopedVars);
var html = '<div class="markdown-html">'; var html = '<div class="markdown-html">';
html += new Remarkable().render(interpolatedMarkdown); html += new Remarkable().render(interpolatedMarkdown);
@ -334,7 +334,7 @@ export class PanelCtrl {
if (this.panel.links && this.panel.links.length > 0) { if (this.panel.links && this.panel.links.length > 0) {
html += '<ul>'; html += '<ul>';
for (const link of this.panel.links) { for (const link of this.panel.links) {
var info = linkSrv.getPanelLinkAnchorInfo(link, this.panel.scopedVars); const info = linkSrv.getPanelLinkAnchorInfo(link, this.panel.scopedVars);
html += html +=
'<li><a class="panel-menu-link" href="' + '<li><a class="panel-menu-link" href="' +
info.href + info.href +
@ -352,7 +352,7 @@ export class PanelCtrl {
} }
openInspector() { openInspector() {
var modalScope = this.$scope.$new(); const modalScope = this.$scope.$new();
modalScope.panel = this.panel; modalScope.panel = this.panel;
modalScope.dashboard = this.dashboard; modalScope.dashboard = this.dashboard;
modalScope.panelInfoHtml = this.getInfoContent({ mode: 'inspector' }); modalScope.panelInfoHtml = this.getInfoContent({ mode: 'inspector' });

View File

@ -22,7 +22,7 @@ export function containsVariable(...args: any[]) {
} }
variableName = kbn.regexEscape(variableName); variableName = kbn.regexEscape(variableName);
var findVarRegex = new RegExp('\\$(' + variableName + ')(?:\\W|$)|\\[\\[(' + variableName + ')\\]\\]', 'g'); const findVarRegex = new RegExp('\\$(' + variableName + ')(?:\\W|$)|\\[\\[(' + variableName + ')\\]\\]', 'g');
var match = findVarRegex.exec(str); const match = findVarRegex.exec(str);
return match !== null; return match !== null;
} }

View File

@ -20,7 +20,7 @@ export class CloudWatchQueryParameterCtrl {
/** @ngInject */ /** @ngInject */
constructor($scope, templateSrv, uiSegmentSrv, datasourceSrv, $q) { constructor($scope, templateSrv, uiSegmentSrv, datasourceSrv, $q) {
$scope.init = function() { $scope.init = function() {
var target = $scope.target; const target = $scope.target;
target.namespace = target.namespace || ''; target.namespace = target.namespace || '';
target.metricName = target.metricName || ''; target.metricName = target.metricName || '';
target.statistics = target.statistics || ['Average']; target.statistics = target.statistics || ['Average'];
@ -106,8 +106,8 @@ export class CloudWatchQueryParameterCtrl {
}; };
$scope.ensurePlusButton = function(segments) { $scope.ensurePlusButton = function(segments) {
var count = segments.length; const count = segments.length;
var lastSegment = segments[Math.max(count - 1, 0)]; const lastSegment = segments[Math.max(count - 1, 0)];
if (!lastSegment || lastSegment.type !== 'plus-button') { if (!lastSegment || lastSegment.type !== 'plus-button') {
segments.push(uiSegmentSrv.newPlusButton()); segments.push(uiSegmentSrv.newPlusButton());
@ -119,13 +119,13 @@ export class CloudWatchQueryParameterCtrl {
return $q.when([]); return $q.when([]);
} }
var target = $scope.target; const target = $scope.target;
var query = $q.when([]); var query = $q.when([]);
if (segment.type === 'key' || segment.type === 'plus-button') { if (segment.type === 'key' || segment.type === 'plus-button') {
query = $scope.datasource.getDimensionKeys($scope.target.namespace, $scope.target.region); query = $scope.datasource.getDimensionKeys($scope.target.namespace, $scope.target.region);
} else if (segment.type === 'value') { } else if (segment.type === 'value') {
var dimensionKey = $scope.dimSegments[$index - 2].value; const dimensionKey = $scope.dimSegments[$index - 2].value;
query = $scope.datasource.getDimensionValues( query = $scope.datasource.getDimensionValues(
target.region, target.region,
target.namespace, target.namespace,
@ -161,12 +161,12 @@ export class CloudWatchQueryParameterCtrl {
}; };
$scope.syncDimSegmentsWithModel = function() { $scope.syncDimSegmentsWithModel = function() {
var dims = {}; const dims = {};
var length = $scope.dimSegments.length; const length = $scope.dimSegments.length;
for (var i = 0; i < length - 2; i += 3) { for (var i = 0; i < length - 2; i += 3) {
var keySegment = $scope.dimSegments[i]; const keySegment = $scope.dimSegments[i];
var valueSegment = $scope.dimSegments[i + 2]; const valueSegment = $scope.dimSegments[i + 2];
if (!valueSegment.fake) { if (!valueSegment.fake) {
dims[keySegment.value] = valueSegment.value; dims[keySegment.value] = valueSegment.value;
} }
@ -212,7 +212,7 @@ export class CloudWatchQueryParameterCtrl {
$scope.transformToSegments = function(addTemplateVars) { $scope.transformToSegments = function(addTemplateVars) {
return function(results) { return function(results) {
var segments = _.map(results, function(segment) { const segments = _.map(results, function(segment) {
return uiSegmentSrv.newSegment({ return uiSegmentSrv.newSegment({
value: segment.text, value: segment.text,
expandable: segment.expandable, expandable: segment.expandable,

View File

@ -16,16 +16,16 @@ export function graphiteAddFunc($compile) {
return { return {
link: function($scope, elem) { link: function($scope, elem) {
var ctrl = $scope.ctrl; const ctrl = $scope.ctrl;
var $input = $(inputTemplate); const $input = $(inputTemplate);
var $button = $(buttonTemplate); const $button = $(buttonTemplate);
$input.appendTo(elem); $input.appendTo(elem);
$button.appendTo(elem); $button.appendTo(elem);
ctrl.datasource.getFuncDefs().then(function(funcDefs) { ctrl.datasource.getFuncDefs().then(function(funcDefs) {
var allFunctions = _.map(funcDefs, 'name').sort(); const allFunctions = _.map(funcDefs, 'name').sort();
$scope.functionMenu = createFunctionDropDownMenu(funcDefs); $scope.functionMenu = createFunctionDropDownMenu(funcDefs);
@ -82,7 +82,7 @@ export function graphiteAddFunc($compile) {
}); });
var drop; var drop;
var cleanUpDrop = function() { const cleanUpDrop = function() {
if (drop) { if (drop) {
drop.destroy(); drop.destroy();
drop = null; drop = null;
@ -106,7 +106,7 @@ export function graphiteAddFunc($compile) {
shortDesc = shortDesc.substring(0, 497) + '...'; shortDesc = shortDesc.substring(0, 497) + '...';
} }
var contentElement = document.createElement('div'); const contentElement = document.createElement('div');
contentElement.innerHTML = '<h4>' + funcDef.name + '</h4>' + rst2html(shortDesc); contentElement.innerHTML = '<h4>' + funcDef.name + '</h4>' + rst2html(shortDesc);
drop = new Drop({ drop = new Drop({
@ -133,7 +133,7 @@ export function graphiteAddFunc($compile) {
angular.module('grafana.directives').directive('graphiteAddFunc', graphiteAddFunc); angular.module('grafana.directives').directive('graphiteAddFunc', graphiteAddFunc);
function createFunctionDropDownMenu(funcDefs) { function createFunctionDropDownMenu(funcDefs) {
var categories = {}; const categories = {};
_.forEach(funcDefs, function(funcDef) { _.forEach(funcDefs, function(funcDef) {
if (!funcDef.category) { if (!funcDef.category) {

View File

@ -20,10 +20,10 @@ export function graphiteFuncEditor($compile, templateSrv, popoverSrv) {
return { return {
restrict: 'A', restrict: 'A',
link: function postLink($scope, elem) { link: function postLink($scope, elem) {
var $funcLink = $(funcSpanTemplate); const $funcLink = $(funcSpanTemplate);
var $funcControls = $(funcControlsTemplate); const $funcControls = $(funcControlsTemplate);
var ctrl = $scope.ctrl; const ctrl = $scope.ctrl;
var func = $scope.func; const func = $scope.func;
var scheduledRelink = false; var scheduledRelink = false;
var paramCountAtLink = 0; var paramCountAtLink = 0;
var cancelBlur = null; var cancelBlur = null;
@ -31,9 +31,9 @@ export function graphiteFuncEditor($compile, templateSrv, popoverSrv) {
function clickFuncParam(paramIndex) { function clickFuncParam(paramIndex) {
/*jshint validthis:true */ /*jshint validthis:true */
var $link = $(this); const $link = $(this);
var $comma = $link.prev('.comma'); const $comma = $link.prev('.comma');
var $input = $link.next(); const $input = $link.next();
$input.val(func.params[paramIndex]); $input.val(func.params[paramIndex]);
@ -43,7 +43,7 @@ export function graphiteFuncEditor($compile, templateSrv, popoverSrv) {
$input.focus(); $input.focus();
$input.select(); $input.select();
var typeahead = $input.data('typeahead'); const typeahead = $input.data('typeahead');
if (typeahead) { if (typeahead) {
$input.val(''); $input.val('');
typeahead.lookup(); typeahead.lookup();
@ -76,14 +76,14 @@ export function graphiteFuncEditor($compile, templateSrv, popoverSrv) {
function switchToLink(inputElem, paramIndex) { function switchToLink(inputElem, paramIndex) {
/*jshint validthis:true */ /*jshint validthis:true */
var $input = $(inputElem); const $input = $(inputElem);
clearTimeout(cancelBlur); clearTimeout(cancelBlur);
cancelBlur = null; cancelBlur = null;
var $link = $input.prev(); const $link = $input.prev();
var $comma = $link.prev('.comma'); const $comma = $link.prev('.comma');
var newValue = $input.val(); const newValue = $input.val();
// remove optional empty params // remove optional empty params
if (newValue !== '' || paramDef(paramIndex).optional) { if (newValue !== '' || paramDef(paramIndex).optional) {
@ -110,7 +110,7 @@ export function graphiteFuncEditor($compile, templateSrv, popoverSrv) {
// this = input element // this = input element
function inputBlur(paramIndex) { function inputBlur(paramIndex) {
/*jshint validthis:true */ /*jshint validthis:true */
var inputElem = this; const inputElem = this;
// happens long before the click event on the typeahead options // happens long before the click event on the typeahead options
// need to have long delay because the blur // need to have long delay because the blur
cancelBlur = setTimeout(function() { cancelBlur = setTimeout(function() {
@ -151,7 +151,7 @@ export function graphiteFuncEditor($compile, templateSrv, popoverSrv) {
}, },
}); });
var typeahead = $input.data('typeahead'); const typeahead = $input.data('typeahead');
typeahead.lookup = function() { typeahead.lookup = function() {
this.query = this.$element.val() || ''; this.query = this.$element.val() || '';
return this.process(this.source); return this.process(this.source);
@ -159,7 +159,7 @@ export function graphiteFuncEditor($compile, templateSrv, popoverSrv) {
} }
function toggleFuncControls() { function toggleFuncControls() {
var targetDiv = elem.closest('.tight-form'); const targetDiv = elem.closest('.tight-form');
if (elem.hasClass('show-function-controls')) { if (elem.hasClass('show-function-controls')) {
elem.removeClass('show-function-controls'); elem.removeClass('show-function-controls');
@ -178,8 +178,8 @@ export function graphiteFuncEditor($compile, templateSrv, popoverSrv) {
$funcControls.appendTo(elem); $funcControls.appendTo(elem);
$funcLink.appendTo(elem); $funcLink.appendTo(elem);
var defParams = _.clone(func.def.params); const defParams = _.clone(func.def.params);
var lastParam = _.last(func.def.params); const lastParam = _.last(func.def.params);
while (func.params.length >= defParams.length && lastParam && lastParam.multiple) { while (func.params.length >= defParams.length && lastParam && lastParam.multiple) {
defParams.push(_.assign({}, lastParam, { optional: true })); defParams.push(_.assign({}, lastParam, { optional: true }));
@ -192,7 +192,7 @@ export function graphiteFuncEditor($compile, templateSrv, popoverSrv) {
var paramValue = templateSrv.highlightVariablesAsHtml(func.params[index]); var paramValue = templateSrv.highlightVariablesAsHtml(func.params[index]);
var last = index >= func.params.length - 1 && param.optional && !paramValue; const last = index >= func.params.length - 1 && param.optional && !paramValue;
if (last && param.multiple) { if (last && param.multiple) {
paramValue = '+'; paramValue = '+';
} }
@ -201,14 +201,14 @@ export function graphiteFuncEditor($compile, templateSrv, popoverSrv) {
$('<span class="comma' + (last ? ' query-part__last' : '') + '">, </span>').appendTo(elem); $('<span class="comma' + (last ? ' query-part__last' : '') + '">, </span>').appendTo(elem);
} }
var $paramLink = $( const $paramLink = $(
'<a ng-click="" class="graphite-func-param-link' + '<a ng-click="" class="graphite-func-param-link' +
(last ? ' query-part__last' : '') + (last ? ' query-part__last' : '') +
'">' + '">' +
(paramValue || '&nbsp;') + (paramValue || '&nbsp;') +
'</a>' '</a>'
); );
var $input = $(paramTemplate); const $input = $(paramTemplate);
$input.attr('placeholder', param.name); $input.attr('placeholder', param.name);
paramCountAtLink++; paramCountAtLink++;
@ -251,7 +251,7 @@ export function graphiteFuncEditor($compile, templateSrv, popoverSrv) {
function registerFuncControlsActions() { function registerFuncControlsActions() {
$funcControls.click(function(e) { $funcControls.click(function(e) {
var $target = $(e.target); const $target = $(e.target);
if ($target.hasClass('fa-remove')) { if ($target.hasClass('fa-remove')) {
toggleFuncControls(); toggleFuncControls();
$scope.$apply(function() { $scope.$apply(function() {
@ -277,7 +277,7 @@ export function graphiteFuncEditor($compile, templateSrv, popoverSrv) {
} }
if ($target.hasClass('fa-question-circle')) { if ($target.hasClass('fa-question-circle')) {
var funcDef = ctrl.datasource.getFuncDef(func.def.name); const funcDef = ctrl.datasource.getFuncDef(func.def.name);
if (funcDef && funcDef.description) { if (funcDef && funcDef.description) {
popoverSrv.show({ popoverSrv.show({
element: e.target, element: e.target,

View File

@ -1,7 +1,7 @@
import _ from 'lodash'; import _ from 'lodash';
import { isVersionGtOrEq } from 'app/core/utils/version'; import { isVersionGtOrEq } from 'app/core/utils/version';
var index = {}; const index = {};
function addFuncDef(funcDef) { function addFuncDef(funcDef) {
funcDef.params = funcDef.params || []; funcDef.params = funcDef.params || [];
@ -13,7 +13,7 @@ function addFuncDef(funcDef) {
} }
} }
var optionalSeriesRefArgs = [{ name: 'other', type: 'value_or_series', optional: true, multiple: true }]; const optionalSeriesRefArgs = [{ name: 'other', type: 'value_or_series', optional: true, multiple: true }];
addFuncDef({ addFuncDef({
name: 'scaleToSeconds', name: 'scaleToSeconds',
@ -962,9 +962,9 @@ export class FuncInstance {
} }
render(metricExp) { render(metricExp) {
var str = this.def.name + '('; const str = this.def.name + '(';
var parameters = _.map( const parameters = _.map(
this.params, this.params,
function(value, index) { function(value, index) {
var paramType; var paramType;
@ -1063,7 +1063,7 @@ function getFuncDef(name, idx?) {
} }
function getFuncDefs(graphiteVersion, idx?) { function getFuncDefs(graphiteVersion, idx?) {
var funcs = {}; const funcs = {};
_.forEach(idx || index, function(funcDef) { _.forEach(idx || index, function(funcDef) {
if (isVersionRelatedFunction(funcDef, graphiteVersion)) { if (isVersionRelatedFunction(funcDef, graphiteVersion)) {
funcs[funcDef.name] = _.assign({}, funcDef, { funcs[funcDef.name] = _.assign({}, funcDef, {
@ -1078,7 +1078,7 @@ function getFuncDefs(graphiteVersion, idx?) {
// parse response from graphite /functions endpoint into internal format // parse response from graphite /functions endpoint into internal format
function parseFuncDefs(rawDefs) { function parseFuncDefs(rawDefs) {
var funcDefs = {}; const funcDefs = {};
_.forEach(rawDefs || {}, (funcDef, funcName) => { _.forEach(rawDefs || {}, (funcDef, funcName) => {
// skip graphite graph functions // skip graphite graph functions
@ -1095,7 +1095,7 @@ function parseFuncDefs(rawDefs) {
.replace(/.. code-block *:: *none/g, '.. code-block::'); .replace(/.. code-block *:: *none/g, '.. code-block::');
} }
var func = { const func = {
name: funcDef.name, name: funcDef.name,
description: description, description: description,
category: funcDef.group, category: funcDef.group,
@ -1120,7 +1120,7 @@ function parseFuncDefs(rawDefs) {
} }
_.forEach(funcDef.params, rawParam => { _.forEach(funcDef.params, rawParam => {
var param = { const param = {
name: rawParam.name, name: rawParam.name,
type: 'string', type: 'string',
optional: !rawParam.required, optional: !rawParam.required,

View File

@ -33,8 +33,8 @@ export default class GraphiteQuery {
return; return;
} }
var parser = new Parser(this.target.target); const parser = new Parser(this.target.target);
var astNode = parser.getAst(); const astNode = parser.getAst();
if (astNode === null) { if (astNode === null) {
this.checkOtherSegmentsIndex = 0; this.checkOtherSegmentsIndex = 0;
return; return;
@ -69,7 +69,7 @@ export default class GraphiteQuery {
} }
getSegmentPathUpTo(index) { getSegmentPathUpTo(index) {
var arr = this.segments.slice(0, index); const arr = this.segments.slice(0, index);
return _.reduce( return _.reduce(
arr, arr,
@ -87,7 +87,7 @@ export default class GraphiteQuery {
switch (astNode.type) { switch (astNode.type) {
case 'function': case 'function':
var innerFunc = this.datasource.createFuncInstance(astNode.name, { const innerFunc = this.datasource.createFuncInstance(astNode.name, {
withDefaultParams: false, withDefaultParams: false,
}); });
_.each(astNode.params, param => { _.each(astNode.params, param => {
@ -133,7 +133,7 @@ export default class GraphiteQuery {
} }
moveAliasFuncLast() { moveAliasFuncLast() {
var aliasFunc = _.find(this.functions, function(func) { const aliasFunc = _.find(this.functions, function(func) {
return func.def.name.startsWith('alias'); return func.def.name.startsWith('alias');
}); });
@ -157,7 +157,7 @@ export default class GraphiteQuery {
updateModelTarget(targets) { updateModelTarget(targets) {
// render query // render query
if (!this.target.textEditor) { if (!this.target.textEditor) {
var metricPath = this.getSegmentPathUpTo(this.segments.length).replace(/\.select metric$/, ''); const metricPath = this.getSegmentPathUpTo(this.segments.length).replace(/\.select metric$/, '');
this.target.target = _.reduce(this.functions, wrapFunction, metricPath); this.target.target = _.reduce(this.functions, wrapFunction, metricPath);
} }
@ -173,12 +173,12 @@ export default class GraphiteQuery {
updateRenderedTarget(target, targets) { updateRenderedTarget(target, targets) {
// render nested query // render nested query
var targetsByRefId = _.keyBy(targets, 'refId'); const targetsByRefId = _.keyBy(targets, 'refId');
// no references to self // no references to self
delete targetsByRefId[target.refId]; delete targetsByRefId[target.refId];
var nestedSeriesRefRegex = /\#([A-Z])/g; const nestedSeriesRefRegex = /\#([A-Z])/g;
var targetWithNestedQueries = target.target; var targetWithNestedQueries = target.target;
// Use ref count to track circular references // Use ref count to track circular references
@ -200,8 +200,8 @@ export default class GraphiteQuery {
// Keep interpolating until there are no query references // Keep interpolating until there are no query references
// The reason for the loop is that the referenced query might contain another reference to another query // The reason for the loop is that the referenced query might contain another reference to another query
while (targetWithNestedQueries.match(nestedSeriesRefRegex)) { while (targetWithNestedQueries.match(nestedSeriesRefRegex)) {
var updated = targetWithNestedQueries.replace(nestedSeriesRefRegex, (match, g1) => { const updated = targetWithNestedQueries.replace(nestedSeriesRefRegex, (match, g1) => {
var t = targetsByRefId[g1]; const t = targetsByRefId[g1];
if (!t) { if (!t) {
return match; return match;
} }

View File

@ -9,7 +9,7 @@ import _ from 'lodash';
// http://www.fileformat.info/info/unicode/category/Lo/list.htm // http://www.fileformat.info/info/unicode/category/Lo/list.htm
// http://www.fileformat.info/info/unicode/category/Nl/list.htm // http://www.fileformat.info/info/unicode/category/Nl/list.htm
var unicodeLetterTable = [ const unicodeLetterTable = [
170, 170,
170, 170,
181, 181,
@ -898,7 +898,7 @@ var unicodeLetterTable = [
195101, 195101,
]; ];
var identifierStartTable = []; const identifierStartTable = [];
for (var i = 0; i < 128; i++) { for (var i = 0; i < 128; i++) {
identifierStartTable[i] = identifierStartTable[i] =
@ -920,7 +920,7 @@ for (var i = 0; i < 128; i++) {
(i >= 97 && i <= 122); // a-z (i >= 97 && i <= 122); // a-z
} }
var identifierPartTable = identifierStartTable; const identifierPartTable = identifierStartTable;
export function Lexer(expression) { export function Lexer(expression) {
this.input = expression; this.input = expression;
@ -940,7 +940,7 @@ Lexer.prototype = {
}, },
tokenize: function() { tokenize: function() {
var list = []; const list = [];
var token; var token;
while ((token = this.next())) { while ((token = this.next())) {
list.push(token); list.push(token);
@ -1037,7 +1037,7 @@ Lexer.prototype = {
return /^[0-9a-fA-F]$/.test(str); return /^[0-9a-fA-F]$/.test(str);
} }
var readUnicodeEscapeSequence = _.bind(function() { const readUnicodeEscapeSequence = _.bind(function() {
/*jshint validthis:true */ /*jshint validthis:true */
index += 1; index += 1;
@ -1045,10 +1045,10 @@ Lexer.prototype = {
return null; return null;
} }
var ch1 = this.peek(index + 1); const ch1 = this.peek(index + 1);
var ch2 = this.peek(index + 2); const ch2 = this.peek(index + 2);
var ch3 = this.peek(index + 3); const ch3 = this.peek(index + 3);
var ch4 = this.peek(index + 4); const ch4 = this.peek(index + 4);
var code; var code;
if (isHexDigit(ch1) && isHexDigit(ch2) && isHexDigit(ch3) && isHexDigit(ch4)) { if (isHexDigit(ch1) && isHexDigit(ch2) && isHexDigit(ch3) && isHexDigit(ch4)) {
@ -1065,10 +1065,10 @@ Lexer.prototype = {
return null; return null;
}, this); }, this);
var getIdentifierStart = _.bind(function() { const getIdentifierStart = _.bind(function() {
/*jshint validthis:true */ /*jshint validthis:true */
var chr = this.peek(index); const chr = this.peek(index);
var code = chr.charCodeAt(0); const code = chr.charCodeAt(0);
if (chr === '*') { if (chr === '*') {
index += 1; index += 1;
@ -1096,10 +1096,10 @@ Lexer.prototype = {
return null; return null;
}, this); }, this);
var getIdentifierPart = _.bind(function() { const getIdentifierPart = _.bind(function() {
/*jshint validthis:true */ /*jshint validthis:true */
var chr = this.peek(index); const chr = this.peek(index);
var code = chr.charCodeAt(0); const code = chr.charCodeAt(0);
if (code === 92) { if (code === 92) {
return readUnicodeEscapeSequence(); return readUnicodeEscapeSequence();
@ -1170,7 +1170,7 @@ Lexer.prototype = {
scanNumericLiteral: function(): any { scanNumericLiteral: function(): any {
var index = 0; var index = 0;
var value = ''; var value = '';
var length = this.input.length; const length = this.input.length;
var char = this.peek(index); var char = this.peek(index);
var bad; var bad;
@ -1385,7 +1385,7 @@ Lexer.prototype = {
}, },
scanPunctuator: function() { scanPunctuator: function() {
var ch1 = this.peek(); const ch1 = this.peek();
if (this.isPunctuator(ch1)) { if (this.isPunctuator(ch1)) {
return { return {
@ -1411,7 +1411,7 @@ Lexer.prototype = {
*/ */
scanStringLiteral: function() { scanStringLiteral: function() {
/*jshint loopfunc:true */ /*jshint loopfunc:true */
var quote = this.peek(); const quote = this.peek();
// String must start with a quote. // String must start with a quote.
if (quote !== '"' && quote !== "'") { if (quote !== '"' && quote !== "'") {
@ -1434,8 +1434,8 @@ Lexer.prototype = {
}; };
} }
var char = this.peek(); const char = this.peek();
var jump = 1; // A length of a jump, after we're done const jump = 1; // A length of a jump, after we're done
// parsing this character. // parsing this character.
value += char; value += char;

View File

@ -54,14 +54,14 @@ Parser.prototype = {
}, },
metricSegment: function() { metricSegment: function() {
var curly = this.curlyBraceSegment(); const curly = this.curlyBraceSegment();
if (curly) { if (curly) {
return curly; return curly;
} }
if (this.match('identifier') || this.match('number')) { if (this.match('identifier') || this.match('number')) {
// hack to handle float numbers in metric segments // hack to handle float numbers in metric segments
var parts = this.consumeToken().value.split('.'); const parts = this.consumeToken().value.split('.');
if (parts.length === 2) { if (parts.length === 2) {
this.tokens.splice(this.index, 0, { type: '.' }); this.tokens.splice(this.index, 0, { type: '.' });
this.tokens.splice(this.index + 1, 0, { this.tokens.splice(this.index + 1, 0, {
@ -86,7 +86,7 @@ Parser.prototype = {
this.errorMark('Expected identifier after templateStart'); this.errorMark('Expected identifier after templateStart');
} }
var node = { const node = {
type: 'template', type: 'template',
value: this.consumeToken().value, value: this.consumeToken().value,
}; };
@ -104,7 +104,7 @@ Parser.prototype = {
return null; return null;
} }
var node = { const node = {
type: 'metric', type: 'metric',
segments: [], segments: [],
}; };
@ -114,7 +114,7 @@ Parser.prototype = {
while (this.match('.')) { while (this.match('.')) {
this.consumeToken(); this.consumeToken();
var segment = this.metricSegment(); const segment = this.metricSegment();
if (!segment) { if (!segment) {
this.errorMark('Expected metric identifier'); this.errorMark('Expected metric identifier');
} }
@ -130,7 +130,7 @@ Parser.prototype = {
return null; return null;
} }
var node: any = { const node: any = {
type: 'function', type: 'function',
name: this.consumeToken().value, name: this.consumeToken().value,
}; };
@ -165,7 +165,7 @@ Parser.prototype = {
return []; return [];
} }
var param = const param =
this.functionCall() || this.functionCall() ||
this.numericLiteral() || this.numericLiteral() ||
this.seriesRefExpression() || this.seriesRefExpression() ||
@ -186,12 +186,12 @@ Parser.prototype = {
return null; return null;
} }
var value = this.tokens[this.index].value; const value = this.tokens[this.index].value;
if (!value.match(/\#[A-Z]/)) { if (!value.match(/\#[A-Z]/)) {
return null; return null;
} }
var token = this.consumeToken(); const token = this.consumeToken();
return { return {
type: 'series-ref', type: 'series-ref',
@ -215,7 +215,7 @@ Parser.prototype = {
return null; return null;
} }
var token = this.consumeToken(); const token = this.consumeToken();
if (token.isUnclosed) { if (token.isUnclosed) {
throw { message: 'Unclosed string parameter', pos: token.pos }; throw { message: 'Unclosed string parameter', pos: token.pos };
} }
@ -227,8 +227,8 @@ Parser.prototype = {
}, },
errorMark: function(text) { errorMark: function(text) {
var currentToken = this.tokens[this.index]; const currentToken = this.tokens[this.index];
var type = currentToken ? currentToken.type : 'end of string'; const type = currentToken ? currentToken.type : 'end of string';
throw { throw {
message: text + ' instead found ' + type, message: text + ' instead found ' + type,
pos: currentToken ? currentToken.pos : this.lexer.char, pos: currentToken ? currentToken.pos : this.lexer.char,
@ -242,7 +242,7 @@ Parser.prototype = {
}, },
matchToken: function(type, index) { matchToken: function(type, index) {
var token = this.tokens[this.index + index]; const token = this.tokens[this.index + index];
return (token === undefined && type === '') || (token && token.type === type); return (token === undefined && type === '') || (token && token.type === type);
}, },

View File

@ -72,7 +72,7 @@ export class GraphiteQueryCtrl extends QueryCtrl {
return; return;
} }
var path = this.queryModel.getSegmentPathUpTo(fromIndex + 1); const path = this.queryModel.getSegmentPathUpTo(fromIndex + 1);
if (path === '') { if (path === '') {
return Promise.resolve(); return Promise.resolve();
} }
@ -110,7 +110,7 @@ export class GraphiteQueryCtrl extends QueryCtrl {
if (index > 0) { if (index > 0) {
query = this.queryModel.getSegmentPathUpTo(index) + '.' + query; query = this.queryModel.getSegmentPathUpTo(index) + '.' + query;
} }
var options = { const options = {
range: this.panelCtrl.range, range: this.panelCtrl.range,
requestId: 'get-alt-segments', requestId: 'get-alt-segments',
}; };
@ -118,7 +118,7 @@ export class GraphiteQueryCtrl extends QueryCtrl {
return this.datasource return this.datasource
.metricFindQuery(query, options) .metricFindQuery(query, options)
.then(segments => { .then(segments => {
var altSegments = _.map(segments, segment => { const altSegments = _.map(segments, segment => {
return this.uiSegmentSrv.newSegment({ return this.uiSegmentSrv.newSegment({
value: segment.text, value: segment.text,
expandable: segment.expandable, expandable: segment.expandable,
@ -238,7 +238,7 @@ export class GraphiteQueryCtrl extends QueryCtrl {
return; return;
} }
var oldTarget = this.queryModel.target.target; const oldTarget = this.queryModel.target.target;
this.updateModelTarget(); this.updateModelTarget();
if (this.queryModel.target !== oldTarget && !this.paused) { if (this.queryModel.target !== oldTarget && !this.paused) {
@ -247,7 +247,7 @@ export class GraphiteQueryCtrl extends QueryCtrl {
} }
addFunction(funcDef) { addFunction(funcDef) {
var newFunc = this.datasource.createFuncInstance(funcDef, { const newFunc = this.datasource.createFuncInstance(funcDef, {
withDefaultParams: true, withDefaultParams: true,
}); });
newFunc.added = true; newFunc.added = true;

View File

@ -6,15 +6,15 @@ class MixedDatasource {
constructor(private $q, private datasourceSrv) {} constructor(private $q, private datasourceSrv) {}
query(options) { query(options) {
var sets = _.groupBy(options.targets, 'datasource'); const sets = _.groupBy(options.targets, 'datasource');
var promises = _.map(sets, targets => { const promises = _.map(sets, targets => {
var dsName = targets[0].datasource; const dsName = targets[0].datasource;
if (dsName === '-- Mixed --') { if (dsName === '-- Mixed --') {
return this.$q([]); return this.$q([]);
} }
return this.datasourceSrv.get(dsName).then(function(ds) { return this.datasourceSrv.get(dsName).then(function(ds) {
var opt = angular.copy(options); const opt = angular.copy(options);
opt.targets = targets; opt.targets = targets;
return ds.query(opt); return ds.query(opt);
}); });