diff --git a/public/app/containers/AlertRuleList/AlertRuleList.test.tsx b/public/app/containers/AlertRuleList/AlertRuleList.test.tsx index eac18a6c69d..f88ff4522d4 100644 --- a/public/app/containers/AlertRuleList/AlertRuleList.test.tsx +++ b/public/app/containers/AlertRuleList/AlertRuleList.test.tsx @@ -46,7 +46,7 @@ describe('AlertRuleList', () => { it('should render 1 rule', () => { page.update(); - let ruleNode = page.find('.alert-rule-item'); + const ruleNode = page.find('.alert-rule-item'); expect(toJson(ruleNode)).toMatchSnapshot(); }); diff --git a/public/app/containers/AlertRuleList/AlertRuleList.tsx b/public/app/containers/AlertRuleList/AlertRuleList.tsx index 3c2da77c2a7..668136dee6f 100644 --- a/public/app/containers/AlertRuleList/AlertRuleList.tsx +++ b/public/app/containers/AlertRuleList/AlertRuleList.tsx @@ -132,13 +132,13 @@ export class AlertRuleItem extends React.Component { render() { const { rule } = this.props; - let stateClass = classNames({ + const stateClass = classNames({ fa: true, 'fa-play': rule.isPaused, 'fa-pause': !rule.isPaused, }); - let ruleUrl = `${rule.url}?panelId=${rule.panelId}&fullscreen=true&edit=true&tab=alert`; + const ruleUrl = `${rule.url}?panelId=${rule.panelId}&fullscreen=true&edit=true&tab=alert`; return (
  • diff --git a/public/app/containers/Explore/Table.tsx b/public/app/containers/Explore/Table.tsx index e5adde2d008..cbb3ab11f4e 100644 --- a/public/app/containers/Explore/Table.tsx +++ b/public/app/containers/Explore/Table.tsx @@ -40,7 +40,7 @@ function Cell(props: SFCCellProps) { export default class Table extends PureComponent { render() { const { className = '', data, loading, onClickCell } = this.props; - let tableModel = data || EMPTY_TABLE; + const tableModel = data || EMPTY_TABLE; if (!loading && data && data.rows.length === 0) { return ( diff --git a/public/app/containers/Explore/utils/prometheus.ts b/public/app/containers/Explore/utils/prometheus.ts index f5ccb848f2f..19129976282 100644 --- a/public/app/containers/Explore/utils/prometheus.ts +++ b/public/app/containers/Explore/utils/prometheus.ts @@ -65,7 +65,7 @@ export function parseSelector(query: string, cursorOffset = 1): { labelKeys: any // Extract clean labels to form clean selector, incomplete labels are dropped const selector = query.slice(prefixOpen, suffixClose); - let labels = {}; + const labels = {}; selector.replace(labelRegexp, match => { const delimiterIndex = match.indexOf('='); const key = match.slice(0, delimiterIndex); diff --git a/public/app/containers/Teams/TeamList.tsx b/public/app/containers/Teams/TeamList.tsx index 2d037eed642..d0feee75184 100644 --- a/public/app/containers/Teams/TeamList.tsx +++ b/public/app/containers/Teams/TeamList.tsx @@ -36,7 +36,7 @@ export class TeamList extends React.Component { }; renderTeamMember(team: Team): JSX.Element { - let teamUrl = `org/teams/edit/${team.id}`; + const teamUrl = `org/teams/edit/${team.id}`; return ( diff --git a/public/app/core/components/Permissions/AddPermissions.test.tsx b/public/app/core/components/Permissions/AddPermissions.test.tsx index 513a22ddea4..c6d1ab381b8 100644 --- a/public/app/core/components/Permissions/AddPermissions.test.tsx +++ b/public/app/core/components/Permissions/AddPermissions.test.tsx @@ -22,7 +22,7 @@ describe('AddPermissions', () => { let wrapper; let store; let instance; - let backendSrv: any = getBackendSrv(); + const backendSrv: any = getBackendSrv(); beforeAll(() => { store = RootStore.create({}, { backendSrv: backendSrv }); diff --git a/public/app/core/components/TagFilter/TagFilter.tsx b/public/app/core/components/TagFilter/TagFilter.tsx index 84f3e1819cd..a879f544da0 100644 --- a/public/app/core/components/TagFilter/TagFilter.tsx +++ b/public/app/core/components/TagFilter/TagFilter.tsx @@ -43,7 +43,7 @@ export class TagFilter extends React.Component { } render() { - let selectOptions = { + const selectOptions = { loadOptions: this.searchTags, onChange: this.onChange, value: this.props.tags, diff --git a/public/app/core/components/code_editor/code_editor.ts b/public/app/core/components/code_editor/code_editor.ts index 886ae2a6407..66aec778d73 100644 --- a/public/app/core/components/code_editor/code_editor.ts +++ b/public/app/core/components/code_editor/code_editor.ts @@ -53,23 +53,23 @@ const DEFAULT_TAB_SIZE = 2; const DEFAULT_BEHAVIOURS = true; const DEFAULT_SNIPPETS = true; -let editorTemplate = `
    `; +const editorTemplate = `
    `; function link(scope, elem, attrs) { // Options - let langMode = attrs.mode || DEFAULT_MODE; - let maxLines = attrs.maxLines || DEFAULT_MAX_LINES; - let showGutter = attrs.showGutter !== undefined; - let tabSize = attrs.tabSize || DEFAULT_TAB_SIZE; - let behavioursEnabled = attrs.behavioursEnabled ? attrs.behavioursEnabled === 'true' : DEFAULT_BEHAVIOURS; - let snippetsEnabled = attrs.snippetsEnabled ? attrs.snippetsEnabled === 'true' : DEFAULT_SNIPPETS; + const langMode = attrs.mode || DEFAULT_MODE; + const maxLines = attrs.maxLines || DEFAULT_MAX_LINES; + const showGutter = attrs.showGutter !== undefined; + const tabSize = attrs.tabSize || DEFAULT_TAB_SIZE; + const behavioursEnabled = attrs.behavioursEnabled ? attrs.behavioursEnabled === 'true' : DEFAULT_BEHAVIOURS; + const snippetsEnabled = attrs.snippetsEnabled ? attrs.snippetsEnabled === 'true' : DEFAULT_SNIPPETS; // Initialize editor - let aceElem = elem.get(0); - let codeEditor = ace.edit(aceElem); - let editorSession = codeEditor.getSession(); + const aceElem = elem.get(0); + const codeEditor = ace.edit(aceElem); + const editorSession = codeEditor.getSession(); - let editorOptions = { + const editorOptions = { maxLines: maxLines, showGutter: showGutter, tabSize: tabSize, @@ -93,7 +93,7 @@ function link(scope, elem, attrs) { // Add classes elem.addClass('gf-code-editor'); - let textarea = elem.find('textarea'); + const textarea = elem.find('textarea'); textarea.addClass('gf-form-input'); if (scope.codeEditorFocus) { @@ -110,14 +110,14 @@ function link(scope, elem, attrs) { // Event handlers editorSession.on('change', e => { scope.$apply(() => { - let newValue = codeEditor.getValue(); + const newValue = codeEditor.getValue(); scope.content = newValue; }); }); // Sync with outer scope - update editor content if model has been changed from outside of directive. scope.$watch('content', (newValue, oldValue) => { - let editorValue = codeEditor.getValue(); + const editorValue = codeEditor.getValue(); if (newValue !== editorValue && newValue !== oldValue) { scope.$$postDigest(function() { setEditorContent(newValue); @@ -157,7 +157,7 @@ function link(scope, elem, attrs) { anyEditor.completers.push(scope.getCompleter()); } - let aceModeName = `ace/mode/${lang}`; + const aceModeName = `ace/mode/${lang}`; editorSession.setMode(aceModeName); } diff --git a/public/app/core/components/colorpicker/ColorPicker.tsx b/public/app/core/components/colorpicker/ColorPicker.tsx index c492d3829ca..6e5083b6d6b 100644 --- a/public/app/core/components/colorpicker/ColorPicker.tsx +++ b/public/app/core/components/colorpicker/ColorPicker.tsx @@ -29,10 +29,10 @@ export class ColorPicker extends React.Component { openColorPicker() { const dropContent = ; - let dropContentElem = document.createElement('div'); + const dropContentElem = document.createElement('div'); ReactDOM.render(dropContent, dropContentElem); - let drop = new Drop({ + const drop = new Drop({ target: this.pickerElem[0], content: dropContentElem, position: 'top center', diff --git a/public/app/core/components/colorpicker/ColorPickerPopover.tsx b/public/app/core/components/colorpicker/ColorPickerPopover.tsx index ac7dd6a2738..c42bcfa1d06 100644 --- a/public/app/core/components/colorpicker/ColorPickerPopover.tsx +++ b/public/app/core/components/colorpicker/ColorPickerPopover.tsx @@ -28,7 +28,7 @@ export class ColorPickerPopover extends React.Component { } setColor(color) { - let newColor = tinycolor(color); + const newColor = tinycolor(color); if (newColor.isValid()) { this.setState({ color: newColor.toString(), @@ -43,20 +43,20 @@ export class ColorPickerPopover extends React.Component { } spectrumColorSelected(color) { - let rgbColor = color.toRgbString(); + const rgbColor = color.toRgbString(); this.setColor(rgbColor); } onColorStringChange(e) { - let colorString = e.target.value; + const colorString = e.target.value; this.setState({ colorString: colorString, }); - let newColor = tinycolor(colorString); + const newColor = tinycolor(colorString); if (newColor.isValid()) { // Update only color state - let newColorString = newColor.toString(); + const newColorString = newColor.toString(); this.setState({ color: newColorString, }); @@ -65,7 +65,7 @@ export class ColorPickerPopover extends React.Component { } onColorStringBlur(e) { - let colorString = e.target.value; + const colorString = e.target.value; this.setColor(colorString); } @@ -73,7 +73,7 @@ export class ColorPickerPopover extends React.Component { this.pickerNavElem.find('li:first').addClass('active'); this.pickerNavElem.on('show', e => { // use href attr (#name => name) - let tab = e.target.hash.slice(1); + const tab = e.target.hash.slice(1); this.setState({ tab: tab, }); diff --git a/public/app/core/components/colorpicker/SpectrumPicker.tsx b/public/app/core/components/colorpicker/SpectrumPicker.tsx index e8a30e8c460..15a76068e9b 100644 --- a/public/app/core/components/colorpicker/SpectrumPicker.tsx +++ b/public/app/core/components/colorpicker/SpectrumPicker.tsx @@ -29,7 +29,7 @@ export class SpectrumPicker extends React.Component { } componentDidMount() { - let spectrumOptions = _.assignIn( + const spectrumOptions = _.assignIn( { flat: true, showAlpha: true, diff --git a/public/app/core/components/form_dropdown/form_dropdown.ts b/public/app/core/components/form_dropdown/form_dropdown.ts index 7ac55e54cf1..007c7c3acb1 100644 --- a/public/app/core/components/form_dropdown/form_dropdown.ts +++ b/public/app/core/components/form_dropdown/form_dropdown.ts @@ -132,7 +132,7 @@ export class FormDropdownCtrl { this.optionCache = options; // extract texts - let optionTexts = _.map(options, op => { + const optionTexts = _.map(options, op => { return _.escape(op.text); }); diff --git a/public/app/core/components/grafana_app.ts b/public/app/core/components/grafana_app.ts index bd6b6975006..1f55bc332ac 100644 --- a/public/app/core/components/grafana_app.ts +++ b/public/app/core/components/grafana_app.ts @@ -140,7 +140,7 @@ export function grafanaAppDirective(playlistSrv, contextSrv, $timeout, $rootScop } // close all drops - for (let drop of Drop.drops) { + for (const drop of Drop.drops) { drop.destroy(); } }); diff --git a/public/app/core/components/info_popover.ts b/public/app/core/components/info_popover.ts index 59332a6f716..ae4feeec701 100644 --- a/public/app/core/components/info_popover.ts +++ b/public/app/core/components/info_popover.ts @@ -8,10 +8,10 @@ export function infoPopover() { template: '', transclude: true, link: function(scope, elem, attrs, ctrl, transclude) { - let offset = attrs.offset || '0 -10px'; - let position = attrs.position || 'right middle'; + const offset = attrs.offset || '0 -10px'; + const position = attrs.position || 'right middle'; let classes = 'drop-help drop-hide-out-of-bounds'; - let openOn = 'hover'; + const openOn = 'hover'; elem.addClass('gf-form-help-icon'); @@ -24,14 +24,14 @@ export function infoPopover() { } transclude(function(clone, newScope) { - let content = document.createElement('div'); + const content = document.createElement('div'); content.className = 'markdown-html'; _.each(clone, node => { content.appendChild(node); }); - let dropOptions = { + const dropOptions = { target: elem[0], content: content, position: position, @@ -52,9 +52,9 @@ export function infoPopover() { // Create drop in next digest after directive content is rendered. scope.$applyAsync(() => { - let drop = new Drop(dropOptions); + const drop = new Drop(dropOptions); - let unbind = scope.$on('$destroy', function() { + const unbind = scope.$on('$destroy', function() { drop.destroy(); unbind(); }); diff --git a/public/app/core/components/manage_dashboards/manage_dashboards.ts b/public/app/core/components/manage_dashboards/manage_dashboards.ts index 86cd3066c48..59a34d08c12 100644 --- a/public/app/core/components/manage_dashboards/manage_dashboards.ts +++ b/public/app/core/components/manage_dashboards/manage_dashboards.ts @@ -103,10 +103,10 @@ export class ManageDashboardsCtrl { this.sections = result; - for (let section of this.sections) { + for (const section of this.sections) { section.checked = false; - for (let dashboard of section.items) { + for (const dashboard of section.items) { dashboard.checked = false; } } @@ -119,7 +119,7 @@ export class ManageDashboardsCtrl { selectionChanged() { let selectedDashboards = 0; - for (let section of this.sections) { + for (const section of this.sections) { selectedDashboards += _.filter(section.items, { checked: true }).length; } @@ -129,7 +129,7 @@ export class ManageDashboardsCtrl { } getFoldersAndDashboardsToDelete() { - let selectedDashboards = { + const selectedDashboards = { folders: [], dashboards: [], }; @@ -148,7 +148,7 @@ export class ManageDashboardsCtrl { getFolderIds(sections) { const ids = []; - for (let s of sections) { + for (const s of sections) { if (s.checked) { ids.push(s.id); } @@ -191,7 +191,7 @@ export class ManageDashboardsCtrl { } getDashboardsToMove() { - let selectedDashboards = []; + const selectedDashboards = []; for (const section of this.sections) { const selected = _.filter(section.items, { checked: true }); @@ -264,7 +264,7 @@ export class ManageDashboardsCtrl { } onSelectAllChanged() { - for (let section of this.sections) { + for (const section of this.sections) { if (!section.hideHeader) { section.checked = this.selectAllChecked; } diff --git a/public/app/core/components/scroll/scroll.ts b/public/app/core/components/scroll/scroll.ts index 3f9865e6dce..5cdbdb62ee3 100644 --- a/public/app/core/components/scroll/scroll.ts +++ b/public/app/core/components/scroll/scroll.ts @@ -17,7 +17,7 @@ export function geminiScrollbar() { restrict: 'A', link: function(scope, elem, attrs) { let scrollRoot = elem.parent(); - let scroller = elem; + const scroller = elem; if (attrs.grafanaScrollbar && attrs.grafanaScrollbar === 'scrollonroot') { scrollRoot = scroller; @@ -27,7 +27,7 @@ export function geminiScrollbar() { $(scrollBarHTML).appendTo(scrollRoot); elem.addClass(scrollerClass); - let scrollParams = { + const scrollParams = { root: scrollRoot[0], scroller: scroller[0], bar: '.baron__bar', @@ -37,7 +37,7 @@ export function geminiScrollbar() { direction: 'v', }; - let scrollbar = baron(scrollParams); + const scrollbar = baron(scrollParams); let lastPos = 0; diff --git a/public/app/core/components/search/SearchResult.tsx b/public/app/core/components/search/SearchResult.tsx index 5ab4bba8edb..3141d29ac7f 100644 --- a/public/app/core/components/search/SearchResult.tsx +++ b/public/app/core/components/search/SearchResult.tsx @@ -54,7 +54,7 @@ export class SearchResultSection extends React.Component { }; render() { - let collapseClassNames = classNames({ + const collapseClassNames = classNames({ fa: true, 'fa-plus': !this.props.section.expanded, 'fa-minus': this.props.section.expanded, diff --git a/public/app/core/components/sidemenu/sidemenu.ts b/public/app/core/components/sidemenu/sidemenu.ts index fb9d9be7f70..5649963c3dc 100644 --- a/public/app/core/components/sidemenu/sidemenu.ts +++ b/public/app/core/components/sidemenu/sidemenu.ts @@ -17,13 +17,13 @@ export class SideMenuCtrl { this.isSignedIn = contextSrv.isSignedIn; this.user = contextSrv.user; - let navTree = _.cloneDeep(config.bootData.navTree); + const navTree = _.cloneDeep(config.bootData.navTree); this.mainLinks = _.filter(navTree, item => !item.hideFromMenu); this.bottomNav = _.filter(navTree, item => item.hideFromMenu); this.loginUrl = 'login?redirect=' + encodeURIComponent(this.$location.path()); if (contextSrv.user.orgCount > 1) { - let profileNode = _.find(this.bottomNav, { id: 'profile' }); + const profileNode = _.find(this.bottomNav, { id: 'profile' }); if (profileNode) { profileNode.showOrgSwitcher = true; } diff --git a/public/app/core/controllers/login_ctrl.ts b/public/app/core/controllers/login_ctrl.ts index 0a66f83d08a..6662686b238 100644 --- a/public/app/core/controllers/login_ctrl.ts +++ b/public/app/core/controllers/login_ctrl.ts @@ -45,8 +45,8 @@ export class LoginCtrl { }; $scope.changeView = function() { - let loginView = document.querySelector('#login-view'); - let changePasswordView = document.querySelector('#change-password-view'); + const loginView = document.querySelector('#login-view'); + const changePasswordView = document.querySelector('#change-password-view'); loginView.className += ' add'; setTimeout(() => { diff --git a/public/app/core/directives/dropdown_typeahead.ts b/public/app/core/directives/dropdown_typeahead.ts index c9e44c5e786..af8c4ddc3bb 100644 --- a/public/app/core/directives/dropdown_typeahead.ts +++ b/public/app/core/directives/dropdown_typeahead.ts @@ -4,12 +4,12 @@ import coreModule from '../core_module'; /** @ngInject */ export function dropdownTypeahead($compile) { - let inputTemplate = + const inputTemplate = ''; - let buttonTemplate = + const buttonTemplate = ''; @@ -21,8 +21,8 @@ export function dropdownTypeahead($compile) { model: '=ngModel', }, link: function($scope, elem, attrs) { - let $input = $(inputTemplate); - let $button = $(buttonTemplate); + const $input = $(inputTemplate); + const $button = $(buttonTemplate); $input.appendTo(elem); $button.appendTo(elem); @@ -42,7 +42,7 @@ export function dropdownTypeahead($compile) { }); } - let typeaheadValues = _.reduce( + const typeaheadValues = _.reduce( $scope.menuItems, function(memo, value, index) { if (!value.submenu) { @@ -60,8 +60,8 @@ export function dropdownTypeahead($compile) { ); $scope.menuItemSelected = function(index, subIndex) { - let menuItem = $scope.menuItems[index]; - let payload: any = { $item: menuItem }; + const menuItem = $scope.menuItems[index]; + const payload: any = { $item: menuItem }; if (menuItem.submenu && subIndex !== void 0) { payload.$subItem = menuItem.submenu[subIndex]; } @@ -74,7 +74,7 @@ export function dropdownTypeahead($compile) { minLength: 1, items: 10, updater: function(value) { - let result: any = {}; + const result: any = {}; _.each($scope.menuItems, function(menuItem) { _.each(menuItem.submenu, function(submenuItem) { if (value === menuItem.text + ' ' + submenuItem.text) { @@ -124,10 +124,10 @@ export function dropdownTypeahead($compile) { /** @ngInject */ export function dropdownTypeahead2($compile) { - let inputTemplate = + const inputTemplate = ''; - let buttonTemplate = + const buttonTemplate = ''; @@ -139,8 +139,8 @@ export function dropdownTypeahead2($compile) { model: '=ngModel', }, link: function($scope, elem, attrs) { - let $input = $(inputTemplate); - let $button = $(buttonTemplate); + const $input = $(inputTemplate); + const $button = $(buttonTemplate); $input.appendTo(elem); $button.appendTo(elem); @@ -160,7 +160,7 @@ export function dropdownTypeahead2($compile) { }); } - let typeaheadValues = _.reduce( + const typeaheadValues = _.reduce( $scope.menuItems, function(memo, value, index) { if (!value.submenu) { @@ -178,8 +178,8 @@ export function dropdownTypeahead2($compile) { ); $scope.menuItemSelected = function(index, subIndex) { - let menuItem = $scope.menuItems[index]; - let payload: any = { $item: menuItem }; + const menuItem = $scope.menuItems[index]; + const payload: any = { $item: menuItem }; if (menuItem.submenu && subIndex !== void 0) { payload.$subItem = menuItem.submenu[subIndex]; } @@ -192,7 +192,7 @@ export function dropdownTypeahead2($compile) { minLength: 1, items: 10, updater: function(value) { - let result: any = {}; + const result: any = {}; _.each($scope.menuItems, function(menuItem) { _.each(menuItem.submenu, function(submenuItem) { if (value === menuItem.text + ' ' + submenuItem.text) { diff --git a/public/app/core/directives/metric_segment.ts b/public/app/core/directives/metric_segment.ts index 3718d7fbd4a..117f776f487 100644 --- a/public/app/core/directives/metric_segment.ts +++ b/public/app/core/directives/metric_segment.ts @@ -4,16 +4,16 @@ import coreModule from '../core_module'; /** @ngInject */ export function metricSegment($compile, $sce) { - let inputTemplate = + const inputTemplate = ''; - let linkTemplate = + const linkTemplate = ''; - let selectTemplate = + const selectTemplate = ''; @@ -25,13 +25,13 @@ export function metricSegment($compile, $sce) { debounce: '@', }, link: function($scope, elem) { - let $input = $(inputTemplate); - let segment = $scope.segment; - let $button = $(segment.selectMode ? selectTemplate : linkTemplate); + const $input = $(inputTemplate); + const segment = $scope.segment; + const $button = $(segment.selectMode ? selectTemplate : linkTemplate); let options = null; let cancelBlur = null; let linkMode = true; - let debounceLookup = $scope.debounce; + const debounceLookup = $scope.debounce; $input.appendTo(elem); $button.appendTo(elem); @@ -44,7 +44,7 @@ export function metricSegment($compile, $sce) { value = _.unescape(value); $scope.$apply(function() { - let selected = _.find($scope.altSegments, { value: value }); + const selected = _.find($scope.altSegments, { value: value }); if (selected) { segment.value = selected.value; segment.html = selected.html || selected.value; @@ -141,10 +141,10 @@ export function metricSegment($compile, $sce) { matcher: $scope.matcher, }); - let typeahead = $input.data('typeahead'); + const typeahead = $input.data('typeahead'); typeahead.lookup = function() { this.query = this.$element.val() || ''; - let 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; }; @@ -169,7 +169,7 @@ export function metricSegment($compile, $sce) { linkMode = false; - let typeahead = $input.data('typeahead'); + const typeahead = $input.data('typeahead'); if (typeahead) { $input.val(''); typeahead.lookup(); @@ -200,8 +200,8 @@ export function metricSegmentModel(uiSegmentSrv, $q) { let cachedOptions; $scope.valueToSegment = function(value) { - let option = _.find($scope.options, { value: value }); - let segment = { + const option = _.find($scope.options, { value: value }); + const segment = { cssClass: attrs.cssClass, custom: attrs.custom, value: option ? option.text : value, @@ -234,7 +234,7 @@ export function metricSegmentModel(uiSegmentSrv, $q) { $scope.onSegmentChange = function() { if (cachedOptions) { - let option = _.find(cachedOptions, { text: $scope.segment.value }); + const option = _.find(cachedOptions, { text: $scope.segment.value }); if (option && option.value !== $scope.property) { $scope.property = option.value; } else if (attrs.custom !== 'false') { diff --git a/public/app/core/directives/misc.ts b/public/app/core/directives/misc.ts index 299de05f112..034b312aa0e 100644 --- a/public/app/core/directives/misc.ts +++ b/public/app/core/directives/misc.ts @@ -156,7 +156,7 @@ function gfDropdown($parse, $compile, $timeout) { var ul = ['']; for (let index = 0; index < items.length; index++) { - let item = items[index]; + const item = items[index]; if (item.divider) { ul.splice(index + 1, 0, '
  • '); diff --git a/public/app/core/directives/value_select_dropdown.ts b/public/app/core/directives/value_select_dropdown.ts index d384904c2d8..69504c1bb1b 100644 --- a/public/app/core/directives/value_select_dropdown.ts +++ b/public/app/core/directives/value_select_dropdown.ts @@ -46,16 +46,16 @@ export class ValueSelectDropdownCtrl { } updateLinkText() { - let current = this.variable.current; + const current = this.variable.current; if (current.tags && current.tags.length) { // filer out values that are in selected tags - let selectedAndNotInTag = _.filter(this.variable.options, option => { + const selectedAndNotInTag = _.filter(this.variable.options, option => { if (!option.selected) { return false; } for (let i = 0; i < current.tags.length; i++) { - let tag = current.tags[i]; + const tag = current.tags[i]; if (_.indexOf(tag.values, option.value) !== -1) { return false; } @@ -64,7 +64,7 @@ export class ValueSelectDropdownCtrl { }); // convert values to text - let currentTexts = _.map(selectedAndNotInTag, 'text'); + const currentTexts = _.map(selectedAndNotInTag, 'text'); // join texts this.linkText = currentTexts.join(' + '); @@ -142,7 +142,7 @@ export class ValueSelectDropdownCtrl { commitChange = commitChange || false; excludeOthers = excludeOthers || false; - let setAllExceptCurrentTo = newValue => { + const setAllExceptCurrentTo = newValue => { _.each(this.options, other => { if (option !== other) { other.selected = newValue; @@ -246,9 +246,9 @@ export function valueSelectDropdown($compile, $window, $timeout, $rootScope) { controllerAs: 'vm', bindToController: true, link: function(scope, elem) { - let bodyEl = angular.element($window.document.body); - let linkEl = elem.find('.variable-value-link'); - let inputEl = elem.find('input'); + const bodyEl = angular.element($window.document.body); + const linkEl = elem.find('.variable-value-link'); + const inputEl = elem.find('input'); function openDropdown() { inputEl.css('width', Math.max(linkEl.width(), 80) + 'px'); @@ -288,7 +288,7 @@ export function valueSelectDropdown($compile, $window, $timeout, $rootScope) { } }); - let cleanUp = $rootScope.$on('template-variable-value-updated', () => { + const cleanUp = $rootScope.$on('template-variable-value-updated', () => { scope.vm.updateLinkText(); }); diff --git a/public/app/core/nav_model_srv.ts b/public/app/core/nav_model_srv.ts index a9ebd4e79ed..2bed33e70da 100644 --- a/public/app/core/nav_model_srv.ts +++ b/public/app/core/nav_model_srv.ts @@ -41,14 +41,14 @@ export class NavModelSrv { var children = this.navItems; var nav = new NavModel(); - for (let id of args) { + for (const id of args) { // if its a number then it's the index to use for main if (_.isNumber(id)) { nav.main = nav.breadcrumbs[id]; break; } - let node = _.find(children, { id: id }); + const node = _.find(children, { id: id }); nav.breadcrumbs.push(node); nav.node = node; nav.main = node; @@ -56,7 +56,7 @@ export class NavModelSrv { } if (nav.main.children) { - for (let item of nav.main.children) { + for (const item of nav.main.children) { item.active = false; if (item.url === nav.node.url) { diff --git a/public/app/core/services/backend_srv.ts b/public/app/core/services/backend_srv.ts index 1aeeedef4dd..4dd8a123378 100644 --- a/public/app/core/services/backend_srv.ts +++ b/public/app/core/services/backend_srv.ts @@ -276,11 +276,11 @@ export class BackendSrv { deleteFoldersAndDashboards(folderUids, dashboardUids) { const tasks = []; - for (let folderUid of folderUids) { + for (const folderUid of folderUids) { tasks.push(this.createTask(this.deleteFolder.bind(this), true, folderUid, true)); } - for (let dashboardUid of dashboardUids) { + for (const dashboardUid of dashboardUids) { tasks.push(this.createTask(this.deleteDashboard.bind(this), true, dashboardUid, true)); } @@ -290,7 +290,7 @@ export class BackendSrv { moveDashboards(dashboardUids, toFolder) { const tasks = []; - for (let uid of dashboardUids) { + for (const uid of dashboardUids) { tasks.push(this.createTask(this.moveDashboard.bind(this), true, uid, toFolder)); } @@ -304,7 +304,7 @@ export class BackendSrv { } private moveDashboard(uid, toFolder) { - let deferred = this.$q.defer(); + const deferred = this.$q.defer(); this.getDashboardByUid(uid).then(fullDash => { const model = new DashboardModel(fullDash.dashboard, fullDash.meta); @@ -315,7 +315,7 @@ export class BackendSrv { } const clone = model.getSaveModelClone(); - let options = { + const options = { folderId: toFolder.id, overwrite: false, }; diff --git a/public/app/core/services/bridge_srv.ts b/public/app/core/services/bridge_srv.ts index 4a5649a6c52..bdc2976a94c 100644 --- a/public/app/core/services/bridge_srv.ts +++ b/public/app/core/services/bridge_srv.ts @@ -15,7 +15,7 @@ export class BridgeSrv { init() { this.$rootScope.$on('$routeUpdate', (evt, data) => { - let angularUrl = this.$location.url(); + const angularUrl = this.$location.url(); if (store.view.currentUrl !== angularUrl) { store.view.updatePathAndQuery(this.$location.path(), this.$location.search(), this.$route.current.params); } @@ -28,7 +28,7 @@ export class BridgeSrv { reaction( () => store.view.currentUrl, currentUrl => { - let angularUrl = this.$location.url(); + const angularUrl = this.$location.url(); const url = locationUtil.stripBaseFromUrl(currentUrl); if (angularUrl !== url) { this.$timeout(() => { diff --git a/public/app/core/services/dynamic_directive_srv.ts b/public/app/core/services/dynamic_directive_srv.ts index 086843b6f9a..de06daf2c1a 100644 --- a/public/app/core/services/dynamic_directive_srv.ts +++ b/public/app/core/services/dynamic_directive_srv.ts @@ -36,7 +36,7 @@ class DynamicDirectiveSrv { } create(options) { - let directiveDef = { + const directiveDef = { restrict: 'E', scope: options.scope, link: (scope, elem, attrs) => { diff --git a/public/app/core/services/keybindingSrv.ts b/public/app/core/services/keybindingSrv.ts index 9d914a94a1c..5405a347ba0 100644 --- a/public/app/core/services/keybindingSrv.ts +++ b/public/app/core/services/keybindingSrv.ts @@ -210,7 +210,7 @@ export class KeybindingSrv { // duplicate panel this.bind('p d', () => { if (dashboard.meta.focusPanelId && dashboard.meta.canEdit) { - let panelIndex = dashboard.getPanelInfoById(dashboard.meta.focusPanelId).index; + const panelIndex = dashboard.getPanelInfoById(dashboard.meta.focusPanelId).index; dashboard.duplicatePanel(dashboard.panels[panelIndex]); } }); diff --git a/public/app/core/services/ng_react.ts b/public/app/core/services/ng_react.ts index 3c61412669e..aeffaaa9b3b 100644 --- a/public/app/core/services/ng_react.ts +++ b/public/app/core/services/ng_react.ts @@ -295,6 +295,6 @@ var reactDirective = function($injector) { }; }; -let ngModule = angular.module('react', []); +const ngModule = angular.module('react', []); ngModule.directive('reactComponent', ['$injector', reactComponent]); ngModule.factory('reactDirective', ['$injector', reactDirective]); diff --git a/public/app/core/services/search_srv.ts b/public/app/core/services/search_srv.ts index 9f32e21f3f6..017b2c15efc 100644 --- a/public/app/core/services/search_srv.ts +++ b/public/app/core/services/search_srv.ts @@ -85,10 +85,10 @@ export class SearchSrv { } search(options) { - let sections: any = {}; - let promises = []; - let query = _.clone(options); - let hasFilters = + const sections: any = {}; + const promises = []; + const query = _.clone(options); + const hasFilters = options.query || (options.tag && options.tag.length > 0) || options.starred || @@ -124,7 +124,7 @@ export class SearchSrv { } // create folder index - for (let hit of results) { + for (const hit of results) { if (hit.type === 'dash-folder') { sections[hit.id] = { id: hit.id, @@ -140,7 +140,7 @@ export class SearchSrv { } } - for (let hit of results) { + for (const hit of results) { if (hit.type === 'dash-folder') { continue; } @@ -185,7 +185,7 @@ export class SearchSrv { return Promise.resolve(section); } - let query = { + const query = { folderIds: [section.id], }; diff --git a/public/app/core/services/segment_srv.ts b/public/app/core/services/segment_srv.ts index 042340e6102..5250febc11a 100644 --- a/public/app/core/services/segment_srv.ts +++ b/public/app/core/services/segment_srv.ts @@ -3,7 +3,7 @@ import coreModule from '../core_module'; /** @ngInject */ export function uiSegmentSrv($sce, templateSrv) { - let self = this; + const self = this; function MetricSegment(options) { if (options === '*' || options.value === '*') { @@ -78,7 +78,7 @@ export function uiSegmentSrv($sce, templateSrv) { this.transformToSegments = function(addTemplateVars, variableTypeFilter) { return function(results) { - let segments = _.map(results, function(segment) { + const segments = _.map(results, function(segment) { return self.newSegment({ value: segment.text, expandable: segment.expandable }); }); diff --git a/public/app/core/specs/backend_srv.test.ts b/public/app/core/specs/backend_srv.test.ts index b19bd117766..e9cd5973d36 100644 --- a/public/app/core/specs/backend_srv.test.ts +++ b/public/app/core/specs/backend_srv.test.ts @@ -2,14 +2,14 @@ import { BackendSrv } from 'app/core/services/backend_srv'; jest.mock('app/core/store'); describe('backend_srv', function() { - let _httpBackend = options => { + const _httpBackend = options => { if (options.url === 'gateway-error') { return Promise.reject({ status: 502 }); } return Promise.resolve({}); }; - let _backendSrv = new BackendSrv(_httpBackend, {}, {}, {}, {}); + const _backendSrv = new BackendSrv(_httpBackend, {}, {}, {}, {}); describe('when handling errors', () => { it('should return the http status code', async () => { diff --git a/public/app/core/specs/file_export.test.ts b/public/app/core/specs/file_export.test.ts index 915ce08fcd2..ced94fcdbc0 100644 --- a/public/app/core/specs/file_export.test.ts +++ b/public/app/core/specs/file_export.test.ts @@ -2,7 +2,7 @@ import * as fileExport from '../utils/file_export'; import { beforeEach, expect } from 'test/lib/common'; describe('file_export', () => { - let ctx: any = {}; + const ctx: any = {}; beforeEach(() => { ctx.seriesList = [ @@ -28,7 +28,7 @@ describe('file_export', () => { describe('when exporting series as rows', () => { it('should export points in proper order', () => { - let text = fileExport.convertSeriesListToCsv(ctx.seriesList, ctx.timeFormat); + const text = fileExport.convertSeriesListToCsv(ctx.seriesList, ctx.timeFormat); const expectedText = '"Series";"Time";"Value"\r\n' + '"series_1";"1500026100";1\r\n' + @@ -48,7 +48,7 @@ describe('file_export', () => { describe('when exporting series as columns', () => { it('should export points in proper order', () => { - let text = fileExport.convertSeriesListToCsvColumns(ctx.seriesList, ctx.timeFormat); + const text = fileExport.convertSeriesListToCsvColumns(ctx.seriesList, ctx.timeFormat); const expectedText = '"Time";"series_1";"series_2"\r\n' + '"1500026100";1;11\r\n' + diff --git a/public/app/core/specs/search.test.ts b/public/app/core/specs/search.test.ts index 8aea35af213..3cc789b3cc5 100644 --- a/public/app/core/specs/search.test.ts +++ b/public/app/core/specs/search.test.ts @@ -12,7 +12,7 @@ describe('SearchCtrl', () => { search: (options: any) => {}, getDashboardTags: () => {}, }; - let ctrl = new SearchCtrl({ $on: () => {} }, {}, {}, searchSrvStub); + const ctrl = new SearchCtrl({ $on: () => {} }, {}, {}, searchSrvStub); describe('Given an empty result', () => { beforeEach(() => { diff --git a/public/app/core/specs/search_results.test.ts b/public/app/core/specs/search_results.test.ts index 830496be3a8..96dbc8bb963 100644 --- a/public/app/core/specs/search_results.test.ts +++ b/public/app/core/specs/search_results.test.ts @@ -12,7 +12,7 @@ describe('SearchResultsCtrl', () => { let ctrl; describe('when checking an item that is not checked', () => { - let item = { checked: false }; + const item = { checked: false }; let selectionChanged = false; beforeEach(() => { @@ -31,7 +31,7 @@ describe('SearchResultsCtrl', () => { }); describe('when checking an item that is checked', () => { - let item = { checked: true }; + const item = { checked: true }; let selectionChanged = false; beforeEach(() => { @@ -72,7 +72,7 @@ describe('SearchResultsCtrl', () => { folderExpanded = true; }; - let folder = { + const folder = { expanded: false, toggle: () => Promise.resolve(folder), }; @@ -94,7 +94,7 @@ describe('SearchResultsCtrl', () => { folderExpanded = true; }; - let folder = { + const folder = { expanded: true, toggle: () => Promise.resolve(folder), }; diff --git a/public/app/core/specs/ticks.test.ts b/public/app/core/specs/ticks.test.ts index 8b7e0cd73b5..73d0e96cbd2 100644 --- a/public/app/core/specs/ticks.test.ts +++ b/public/app/core/specs/ticks.test.ts @@ -2,7 +2,7 @@ import * as ticks from '../utils/ticks'; describe('ticks', () => { describe('getFlotTickDecimals()', () => { - let ctx: any = {}; + const ctx: any = {}; beforeEach(() => { ctx.axis = {}; diff --git a/public/app/core/specs/time_series.test.ts b/public/app/core/specs/time_series.test.ts index bf50d807e03..35b75b3da5e 100644 --- a/public/app/core/specs/time_series.test.ts +++ b/public/app/core/specs/time_series.test.ts @@ -329,7 +329,7 @@ describe('TimeSeries', function() { describe('legend decimals', function() { let series, panel; - let height = 200; + const height = 200; beforeEach(function() { testData = { alias: 'test', @@ -348,7 +348,7 @@ describe('TimeSeries', function() { }); it('should set decimals based on Y axis (expect calculated decimals = 1)', function() { - let data = [series]; + const data = [series]; // Expect ticks with this data will have decimals = 1 updateLegendValues(data, panel, height); expect(data[0].decimals).toBe(2); @@ -358,21 +358,21 @@ describe('TimeSeries', function() { testData.datapoints = [[10, 2], [0, 3], [100, 4], [80, 5]]; series = new TimeSeries(testData); series.getFlotPairs(); - let data = [series]; + const data = [series]; updateLegendValues(data, panel, height); expect(data[0].decimals).toBe(0); }); it('should set decimals to Y axis decimals + 1', function() { panel.yaxes[0].decimals = 2; - let data = [series]; + const data = [series]; updateLegendValues(data, panel, height); expect(data[0].decimals).toBe(3); }); it('should set decimals to legend decimals value if it was set explicitly', function() { panel.decimals = 3; - let data = [series]; + const data = [series]; updateLegendValues(data, panel, height); expect(data[0].decimals).toBe(3); }); diff --git a/public/app/core/specs/value_select_dropdown.test.ts b/public/app/core/specs/value_select_dropdown.test.ts index 3cc310435b7..024774250b8 100644 --- a/public/app/core/specs/value_select_dropdown.test.ts +++ b/public/app/core/specs/value_select_dropdown.test.ts @@ -3,7 +3,7 @@ import { ValueSelectDropdownCtrl } from '../directives/value_select_dropdown'; import q from 'q'; describe('SelectDropdownCtrl', () => { - let tagValuesMap: any = {}; + const tagValuesMap: any = {}; ValueSelectDropdownCtrl.prototype.onUpdated = jest.fn(); let ctrl; diff --git a/public/app/core/time_series2.ts b/public/app/core/time_series2.ts index f4d0943d52f..c29242c9aca 100644 --- a/public/app/core/time_series2.ts +++ b/public/app/core/time_series2.ts @@ -27,11 +27,11 @@ function translateFillOption(fill) { */ export function updateLegendValues(data: TimeSeries[], panel, height) { for (let i = 0; i < data.length; i++) { - let series = data[i]; + const series = data[i]; const yaxes = panel.yaxes; const seriesYAxis = series.yaxis || 1; const axis = yaxes[seriesYAxis - 1]; - let formater = kbn.valueFormats[axis.format]; + const formater = kbn.valueFormats[axis.format]; // decimal override if (_.isNumber(panel.decimals)) { @@ -54,7 +54,7 @@ export function getDataMinMax(data: TimeSeries[]) { let datamin = null; let datamax = null; - for (let series of data) { + for (const series of data) { if (datamax === null || datamax < series.stats.max) { datamax = series.stats.max; } @@ -225,7 +225,7 @@ export default class TimeSeries { // Due to missing values we could have different timeStep all along the series // so we have to find the minimum one (could occur with aggregators such as ZimSum) if (previousTime !== undefined) { - let timeStep = currentTime - previousTime; + const timeStep = currentTime - previousTime; if (timeStep < this.stats.timeStep) { this.stats.timeStep = timeStep; } diff --git a/public/app/core/utils/colors.ts b/public/app/core/utils/colors.ts index 8a70e093ea2..e8a7366beb5 100644 --- a/public/app/core/utils/colors.ts +++ b/public/app/core/utils/colors.ts @@ -9,7 +9,7 @@ export const ALERTING_COLOR = 'rgba(237, 46, 24, 1)'; export const NO_DATA_COLOR = 'rgba(150, 150, 150, 1)'; export const REGION_FILL_ALPHA = 0.09; -let colors = [ +const colors = [ '#7EB26D', '#EAB839', '#6ED0E0', @@ -69,7 +69,7 @@ let colors = [ ]; export function sortColorsByHue(hexColors) { - let hslColors = _.map(hexColors, hexToHsl); + const hslColors = _.map(hexColors, hexToHsl); let sortedHSLColors = _.sortBy(hslColors, ['h']); sortedHSLColors = _.chunk(sortedHSLColors, PALETTE_ROWS); diff --git a/public/app/core/utils/dag.test.ts b/public/app/core/utils/dag.test.ts index a89ab27cda3..064da13806b 100644 --- a/public/app/core/utils/dag.test.ts +++ b/public/app/core/utils/dag.test.ts @@ -2,16 +2,16 @@ import { Graph } from './dag'; describe('Directed acyclic graph', () => { describe('Given a graph with nodes with different links in between them', () => { - let dag = new Graph(); - let nodeA = dag.createNode('A'); - let nodeB = dag.createNode('B'); - let nodeC = dag.createNode('C'); - let nodeD = dag.createNode('D'); - let nodeE = dag.createNode('E'); - let nodeF = dag.createNode('F'); - let nodeG = dag.createNode('G'); - let nodeH = dag.createNode('H'); - let nodeI = dag.createNode('I'); + const dag = new Graph(); + const nodeA = dag.createNode('A'); + const nodeB = dag.createNode('B'); + const nodeC = dag.createNode('C'); + const nodeD = dag.createNode('D'); + const nodeE = dag.createNode('E'); + const nodeF = dag.createNode('F'); + const nodeG = dag.createNode('G'); + const nodeH = dag.createNode('H'); + const nodeI = dag.createNode('I'); dag.link([nodeB, nodeC, nodeD, nodeE, nodeF, nodeG, nodeH], nodeA); dag.link([nodeC, nodeD, nodeE, nodeF, nodeI], nodeB); dag.link([nodeD, nodeE, nodeF, nodeG], nodeC); diff --git a/public/app/core/utils/dag.ts b/public/app/core/utils/dag.ts index 1d61280fb05..eb7ff1c3b1a 100644 --- a/public/app/core/utils/dag.ts +++ b/public/app/core/utils/dag.ts @@ -26,8 +26,8 @@ export class Edge { unlink() { let pos; - let inode = this.inputNode; - let onode = this.outputNode; + const inode = this.inputNode; + const onode = this.outputNode; if (!(inode && onode)) { return; @@ -96,12 +96,12 @@ export class Node { } getOptimizedInputEdges(): Edge[] { - let toBeRemoved = []; + const toBeRemoved = []; this.inputEdges.forEach(e => { - let inputEdgesNodes = e.inputNode.inputEdges.map(e => e.inputNode); + const inputEdgesNodes = e.inputNode.inputEdges.map(e => e.inputNode); inputEdgesNodes.forEach(n => { - let edgeToRemove = n.getEdgeTo(this.name); + const edgeToRemove = n.getEdgeTo(this.name); if (edgeToRemove) { toBeRemoved.push(edgeToRemove); } @@ -124,7 +124,7 @@ export class Graph { } createNodes(names: string[]): Node[] { - let nodes = []; + const nodes = []; names.forEach(name => { nodes.push(this.createNode(name)); }); @@ -134,8 +134,8 @@ export class Graph { link(input: string | string[] | Node | Node[], output: string | string[] | Node | Node[]): Edge[] { let inputArr = []; let outputArr = []; - let inputNodes = []; - let outputNodes = []; + const inputNodes = []; + const outputNodes = []; if (input instanceof Array) { inputArr = input; @@ -167,7 +167,7 @@ export class Graph { } } - let edges = []; + const edges = []; inputNodes.forEach(input => { outputNodes.forEach(output => { edges.push(this.createEdge().link(input, output)); diff --git a/public/app/core/utils/file_export.ts b/public/app/core/utils/file_export.ts index f25d340a0be..298a06c64fd 100644 --- a/public/app/core/utils/file_export.ts +++ b/public/app/core/utils/file_export.ts @@ -74,7 +74,7 @@ export function convertSeriesListToCsv(seriesList, dateTimeFormat = DEFAULT_DATE } export function exportSeriesListToCsv(seriesList, dateTimeFormat = DEFAULT_DATETIME_FORMAT, excel = false) { - let text = convertSeriesListToCsv(seriesList, dateTimeFormat, excel); + const text = convertSeriesListToCsv(seriesList, dateTimeFormat, excel); saveSaveBlob(text, EXPORT_FILENAME); } @@ -115,7 +115,7 @@ export function convertSeriesListToCsvColumns(seriesList, dateTimeFormat = DEFAU function mergeSeriesByTime(seriesList) { let timestamps = []; for (let i = 0; i < seriesList.length; i++) { - let seriesPoints = seriesList[i].datapoints; + const seriesPoints = seriesList[i].datapoints; for (let j = 0; j < seriesPoints.length; j++) { timestamps.push(seriesPoints[j][POINT_TIME_INDEX]); } @@ -123,9 +123,9 @@ function mergeSeriesByTime(seriesList) { timestamps = sortedUniq(timestamps.sort()); for (let i = 0; i < seriesList.length; i++) { - let seriesPoints = seriesList[i].datapoints; - let seriesTimestamps = seriesPoints.map(p => p[POINT_TIME_INDEX]); - let extendedSeries = []; + const seriesPoints = seriesList[i].datapoints; + const seriesTimestamps = seriesPoints.map(p => p[POINT_TIME_INDEX]); + const extendedSeries = []; let pointIndex; for (let j = 0; j < timestamps.length; j++) { pointIndex = sortedIndexOf(seriesTimestamps, timestamps[j]); @@ -141,7 +141,7 @@ function mergeSeriesByTime(seriesList) { } export function exportSeriesListToCsvColumns(seriesList, dateTimeFormat = DEFAULT_DATETIME_FORMAT, excel = false) { - let text = convertSeriesListToCsvColumns(seriesList, dateTimeFormat, excel); + const text = convertSeriesListToCsvColumns(seriesList, dateTimeFormat, excel); saveSaveBlob(text, EXPORT_FILENAME); } @@ -157,11 +157,11 @@ export function convertTableDataToCsv(table, excel = false) { } export function exportTableDataToCsv(table, excel = false) { - let text = convertTableDataToCsv(table, excel); + const text = convertTableDataToCsv(table, excel); saveSaveBlob(text, EXPORT_FILENAME); } export function saveSaveBlob(payload, fname) { - let blob = new Blob([payload], { type: 'text/csv;charset=utf-8;header=present;' }); + const blob = new Blob([payload], { type: 'text/csv;charset=utf-8;header=present;' }); saveAs(blob, fname); } diff --git a/public/app/core/utils/outline.ts b/public/app/core/utils/outline.ts index 94393e781e9..cc06102bfdc 100644 --- a/public/app/core/utils/outline.ts +++ b/public/app/core/utils/outline.ts @@ -1,6 +1,6 @@ // based on http://www.paciellogroup.com/blog/2012/04/how-to-remove-css-outlines-in-an-accessible-manner/ function outlineFixer() { - let d: any = document; + const d: any = document; var style_element = d.createElement('STYLE'); var dom_events = 'addEventListener' in d; diff --git a/public/app/core/utils/rangeutil.ts b/public/app/core/utils/rangeutil.ts index 95cfe42f0b8..8e0f87df686 100644 --- a/public/app/core/utils/rangeutil.ts +++ b/public/app/core/utils/rangeutil.ts @@ -92,7 +92,7 @@ function formatDate(date) { // now/d // if no to then to now is assumed export function describeTextRange(expr: any) { - let isLast = expr.indexOf('+') !== 0; + const isLast = expr.indexOf('+') !== 0; if (expr.indexOf('now') === -1) { expr = (isLast ? 'now-' : 'now') + expr; } @@ -108,11 +108,11 @@ export function describeTextRange(expr: any) { opt = { from: 'now', to: expr }; } - let parts = /^now([-+])(\d+)(\w)/.exec(expr); + const parts = /^now([-+])(\d+)(\w)/.exec(expr); if (parts) { - let unit = parts[3]; - let amount = parseInt(parts[2]); - let span = spans[unit]; + const unit = parts[3]; + const amount = parseInt(parts[2]); + const span = spans[unit]; if (span) { opt.display = isLast ? 'Last ' : 'Next '; opt.display += amount + ' ' + span.display; diff --git a/public/app/core/utils/sort_by_keys.ts b/public/app/core/utils/sort_by_keys.ts index 9dff252576a..0020d04f290 100644 --- a/public/app/core/utils/sort_by_keys.ts +++ b/public/app/core/utils/sort_by_keys.ts @@ -7,7 +7,7 @@ export default function sortByKeys(input) { if (_.isPlainObject(input)) { var sortedObject = {}; - for (let key of _.keys(input).sort()) { + for (const key of _.keys(input).sort()) { sortedObject[key] = sortByKeys(input[key]); } return sortedObject; diff --git a/public/app/core/utils/tags.ts b/public/app/core/utils/tags.ts index 678fd8c94be..d0f244be76b 100644 --- a/public/app/core/utils/tags.ts +++ b/public/app/core/utils/tags.ts @@ -67,9 +67,9 @@ const TAG_BORDER_COLORS = [ * @param name tag name */ export function getTagColorsFromName(name: string): { color: string; borderColor: string } { - let hash = djb2(name.toLowerCase()); - let color = TAG_COLORS[Math.abs(hash % TAG_COLORS.length)]; - let borderColor = TAG_BORDER_COLORS[Math.abs(hash % TAG_BORDER_COLORS.length)]; + const hash = djb2(name.toLowerCase()); + const color = TAG_COLORS[Math.abs(hash % TAG_COLORS.length)]; + const borderColor = TAG_BORDER_COLORS[Math.abs(hash % TAG_BORDER_COLORS.length)]; return { color, borderColor }; } diff --git a/public/app/core/utils/ticks.ts b/public/app/core/utils/ticks.ts index 66e6a7ce4fc..d87dedccab1 100644 --- a/public/app/core/utils/ticks.ts +++ b/public/app/core/utils/ticks.ts @@ -7,7 +7,7 @@ * @param count Ticks count */ export function tickStep(start: number, stop: number, count: number): number { - let e10 = Math.sqrt(50), + const e10 = Math.sqrt(50), e5 = Math.sqrt(10), e2 = Math.sqrt(2); @@ -76,7 +76,7 @@ export function getFlotRange(panelMin, panelMax, datamin, datamax) { let min = +(panelMin != null ? panelMin : datamin); let max = +(panelMax != null ? panelMax : datamax); - let delta = max - min; + const delta = max - min; if (delta === 0.0) { // Grafana fix: wide Y min and max using increased wideFactor @@ -123,11 +123,11 @@ export function getFlotTickDecimals(datamin, datamax, axis, height) { const { min, max } = getFlotRange(axis.min, axis.max, datamin, datamax); const noTicks = 0.3 * Math.sqrt(height); const delta = (max - min) / noTicks; - let dec = -Math.floor(Math.log(delta) / Math.LN10); + const dec = -Math.floor(Math.log(delta) / Math.LN10); - let magn = Math.pow(10, -dec); + const magn = Math.pow(10, -dec); // norm is between 1.0 and 10.0 - let norm = delta / magn; + const norm = delta / magn; let size; if (norm < 1.5) { @@ -159,10 +159,10 @@ export function getFlotTickDecimals(datamin, datamax, axis, height) { */ export function grafanaTimeFormat(ticks, min, max) { if (min && max && ticks) { - let range = max - min; - let secPerTick = range / ticks / 1000; - let oneDay = 86400000; - let oneYear = 31536000000; + const range = max - min; + const secPerTick = range / ticks / 1000; + const oneDay = 86400000; + const oneYear = 31536000000; if (secPerTick <= 45) { return '%H:%M:%S'; @@ -193,7 +193,7 @@ export function logp(value, base) { * Get decimal precision of number (3.14 => 2) */ export function getPrecision(num: number): number { - let str = num.toString(); + const str = num.toString(); return getStringPrecision(str); } @@ -201,7 +201,7 @@ export function getPrecision(num: number): number { * Get decimal precision of number stored as a string ("3.14" => 2) */ export function getStringPrecision(num: string): number { - let dot_index = num.indexOf('.'); + const dot_index = num.indexOf('.'); if (dot_index === -1) { return 0; } else { diff --git a/public/app/core/utils/url.ts b/public/app/core/utils/url.ts index b57d5721d57..857e76d9094 100644 --- a/public/app/core/utils/url.ts +++ b/public/app/core/utils/url.ts @@ -3,14 +3,14 @@ */ export function toUrlParams(a) { - let s = []; - let rbracket = /\[\]$/; + const s = []; + const rbracket = /\[\]$/; - let isArray = function(obj) { + const isArray = function(obj) { return Object.prototype.toString.call(obj) === '[object Array]'; }; - let add = function(k, v) { + const add = function(k, v) { v = typeof v === 'function' ? v() : v === null ? '' : v === undefined ? '' : v; if (typeof v !== 'boolean') { s[s.length] = encodeURIComponent(k) + '=' + encodeURIComponent(v); @@ -19,7 +19,7 @@ export function toUrlParams(a) { } }; - let buildParams = function(prefix, obj) { + const buildParams = function(prefix, obj) { var i, len, key; if (prefix) { diff --git a/public/app/core/utils/version.ts b/public/app/core/utils/version.ts index 6ee1400df51..8b249563d86 100644 --- a/public/app/core/utils/version.ts +++ b/public/app/core/utils/version.ts @@ -9,7 +9,7 @@ export class SemVersion { meta: string; constructor(version: string) { - let match = versionPattern.exec(version); + const match = versionPattern.exec(version); if (match) { this.major = Number(match[1]); this.minor = Number(match[2] || 0); @@ -19,7 +19,7 @@ export class SemVersion { } isGtOrEq(version: string): boolean { - let compared = new SemVersion(version); + const compared = new SemVersion(version); return !(this.major < compared.major || this.minor < compared.minor || this.patch < compared.patch); } @@ -29,6 +29,6 @@ export class SemVersion { } export function isVersionGtOrEq(a: string, b: string): boolean { - let a_semver = new SemVersion(a); + const a_semver = new SemVersion(a); return a_semver.isGtOrEq(b); } diff --git a/public/app/features/alerting/alert_tab_ctrl.ts b/public/app/features/alerting/alert_tab_ctrl.ts index 79baa1e3f5a..a25d37913d4 100644 --- a/public/app/features/alerting/alert_tab_ctrl.ts +++ b/public/app/features/alerting/alert_tab_ctrl.ts @@ -184,7 +184,7 @@ export class AlertTabCtrl { ThresholdMapper.alertToGraphThresholds(this.panel); - for (let addedNotification of alert.notifications) { + for (const addedNotification of alert.notifications) { var model = _.find(this.notifications, { id: addedNotification.id }); if (model && model.isDefault === false) { model.iconClass = this.getNotificationIcon(model.type); @@ -192,7 +192,7 @@ export class AlertTabCtrl { } } - for (let notification of this.notifications) { + for (const notification of this.notifications) { if (notification.isDefault) { notification.iconClass = this.getNotificationIcon(notification.type); notification.bgColor = '#00678b'; diff --git a/public/app/features/alerting/notification_edit_ctrl.ts b/public/app/features/alerting/notification_edit_ctrl.ts index 18b1c4d1d55..eb14766d1fb 100644 --- a/public/app/features/alerting/notification_edit_ctrl.ts +++ b/public/app/features/alerting/notification_edit_ctrl.ts @@ -30,7 +30,7 @@ export class AlertNotificationEditCtrl { this.notifiers = notifiers; // add option templates - for (let notifier of this.notifiers) { + for (const notifier of this.notifiers) { this.$templateCache.put(this.getNotifierTemplateId(notifier.type), notifier.optionsTemplate); } diff --git a/public/app/features/alerting/threshold_mapper.ts b/public/app/features/alerting/threshold_mapper.ts index 9142c74b6e3..50324dc18ca 100644 --- a/public/app/features/alerting/threshold_mapper.ts +++ b/public/app/features/alerting/threshold_mapper.ts @@ -1,7 +1,7 @@ export class ThresholdMapper { static alertToGraphThresholds(panel) { for (var i = 0; i < panel.alert.conditions.length; i++) { - let condition = panel.alert.conditions[i]; + const condition = panel.alert.conditions[i]; if (condition.type !== 'query') { continue; } @@ -11,18 +11,18 @@ export class ThresholdMapper { switch (evaluator.type) { case 'gt': { - let value = evaluator.params[0]; + const value = evaluator.params[0]; thresholds.push({ value: value, op: 'gt' }); break; } case 'lt': { - let value = evaluator.params[0]; + const value = evaluator.params[0]; thresholds.push({ value: value, op: 'lt' }); break; } case 'outside_range': { - let value1 = evaluator.params[0]; - let value2 = evaluator.params[1]; + const value1 = evaluator.params[0]; + const value2 = evaluator.params[1]; if (value1 > value2) { thresholds.push({ value: value1, op: 'gt' }); @@ -35,8 +35,8 @@ export class ThresholdMapper { break; } case 'within_range': { - let value1 = evaluator.params[0]; - let value2 = evaluator.params[1]; + const value1 = evaluator.params[0]; + const value2 = evaluator.params[1]; if (value1 > value2) { thresholds.push({ value: value1, op: 'lt' }); diff --git a/public/app/features/annotations/annotations_srv.ts b/public/app/features/annotations/annotations_srv.ts index 5578a979146..b8def36829a 100644 --- a/public/app/features/annotations/annotations_srv.ts +++ b/public/app/features/annotations/annotations_srv.ts @@ -91,7 +91,7 @@ export class AnnotationsSrv { var range = this.timeSrv.timeRange(); var promises = []; - for (let annotation of dashboard.annotations.list) { + for (const annotation of dashboard.annotations.list) { if (!annotation.enable) { continue; } diff --git a/public/app/features/annotations/event_editor.ts b/public/app/features/annotations/event_editor.ts index 1f94e978029..90c425438ab 100644 --- a/public/app/features/annotations/event_editor.ts +++ b/public/app/features/annotations/event_editor.ts @@ -31,7 +31,7 @@ export class EventEditorCtrl { return; } - let saveModel = _.cloneDeep(this.event); + const saveModel = _.cloneDeep(this.event); saveModel.time = saveModel.time.valueOf(); saveModel.timeEnd = 0; @@ -85,7 +85,7 @@ export class EventEditorCtrl { function tryEpochToMoment(timestamp) { if (timestamp && _.isNumber(timestamp)) { - let epoch = Number(timestamp); + const epoch = Number(timestamp); return moment(epoch); } else { return timestamp; diff --git a/public/app/features/annotations/event_manager.ts b/public/app/features/annotations/event_manager.ts index 7db6a19f2c6..a6fceac2e54 100644 --- a/public/app/features/annotations/event_manager.ts +++ b/public/app/features/annotations/event_manager.ts @@ -125,11 +125,11 @@ export class EventManager { } } - let regions = getRegions(annotations); + const regions = getRegions(annotations); addRegionMarking(regions, flotOptions); - let eventSectionHeight = 20; - let eventSectionMargin = 7; + const eventSectionHeight = 20; + const eventSectionMargin = 7; flotOptions.grid.eventSectionHeight = eventSectionMargin; flotOptions.xaxis.eventSectionHeight = eventSectionHeight; @@ -147,8 +147,8 @@ function getRegions(events) { } function addRegionMarking(regions, flotOptions) { - let markings = flotOptions.grid.markings; - let defaultColor = DEFAULT_ANNOTATION_COLOR; + const markings = flotOptions.grid.markings; + const defaultColor = DEFAULT_ANNOTATION_COLOR; let fillColor; _.each(regions, region => { @@ -167,7 +167,7 @@ function addRegionMarking(regions, flotOptions) { } function addAlphaToRGB(colorString: string, alpha: number): string { - let color = tinycolor(colorString); + const color = tinycolor(colorString); if (color.isValid()) { color.setAlpha(alpha); return color.toRgbString(); diff --git a/public/app/features/annotations/events_processing.ts b/public/app/features/annotations/events_processing.ts index 667285d7d43..6e610fb1457 100644 --- a/public/app/features/annotations/events_processing.ts +++ b/public/app/features/annotations/events_processing.ts @@ -7,20 +7,20 @@ import _ from 'lodash'; * @param options */ export function makeRegions(annotations, options) { - let [regionEvents, singleEvents] = _.partition(annotations, 'regionId'); - let regions = getRegions(regionEvents, options.range); + const [regionEvents, singleEvents] = _.partition(annotations, 'regionId'); + const regions = getRegions(regionEvents, options.range); annotations = _.concat(regions, singleEvents); return annotations; } function getRegions(events, range) { - let region_events = _.filter(events, event => { + const region_events = _.filter(events, event => { return event.regionId; }); let regions = _.groupBy(region_events, 'regionId'); regions = _.compact( _.map(regions, region_events => { - let region_obj = _.head(region_events); + const region_obj = _.head(region_events); if (region_events && region_events.length > 1) { region_obj.timeEnd = region_events[1].time; region_obj.isRegion = true; @@ -57,9 +57,9 @@ export function dedupAnnotations(annotations) { let dedup = []; // Split events by annotationId property existence - let events = _.partition(annotations, 'id'); + const events = _.partition(annotations, 'id'); - let eventsById = _.groupBy(events[0], 'id'); + const eventsById = _.groupBy(events[0], 'id'); dedup = _.map(eventsById, eventGroup => { if (eventGroup.length > 1 && !_.every(eventGroup, isPanelAlert)) { // Get first non-panel alert diff --git a/public/app/features/annotations/specs/annotations_srv.test.ts b/public/app/features/annotations/specs/annotations_srv.test.ts index 7db7b6c9f05..97696767536 100644 --- a/public/app/features/annotations/specs/annotations_srv.test.ts +++ b/public/app/features/annotations/specs/annotations_srv.test.ts @@ -3,7 +3,7 @@ import 'app/features/dashboard/time_srv'; import { AnnotationsSrv } from '../annotations_srv'; describe('AnnotationsSrv', function() { - let $rootScope = { + const $rootScope = { onAppEvent: jest.fn(), }; let $q; @@ -11,7 +11,7 @@ describe('AnnotationsSrv', function() { let backendSrv; let timeSrv; - let annotationsSrv = new AnnotationsSrv($rootScope, $q, datasourceSrv, backendSrv, timeSrv); + const annotationsSrv = new AnnotationsSrv($rootScope, $q, datasourceSrv, backendSrv, timeSrv); describe('When translating the query result', () => { const annotationSource = { diff --git a/public/app/features/annotations/specs/annotations_srv_specs.test.ts b/public/app/features/annotations/specs/annotations_srv_specs.test.ts index 35def83e4a9..49457f34d05 100644 --- a/public/app/features/annotations/specs/annotations_srv_specs.test.ts +++ b/public/app/features/annotations/specs/annotations_srv_specs.test.ts @@ -24,7 +24,7 @@ describe('Annotations', () => { { id: 2, time: 2 }, ]; - let regions = makeRegions(testAnnotations, { range: range }); + const regions = makeRegions(testAnnotations, { range: range }); expect(regions).toEqual(expectedAnnotations); }); @@ -33,7 +33,7 @@ describe('Annotations', () => { testAnnotations = [{ id: 5, time: 4, regionId: 5 }]; const expectedAnnotations = [{ id: 5, regionId: 5, isRegion: true, time: 4, timeEnd: 7 }]; - let regions = makeRegions(testAnnotations, { range: range }); + const regions = makeRegions(testAnnotations, { range: range }); expect(regions).toEqual(expectedAnnotations); }); }); @@ -49,7 +49,7 @@ describe('Annotations', () => { ]; const expectedAnnotations = [{ id: 1, time: 1 }, { id: 2, time: 2 }, { id: 5, time: 5 }]; - let deduplicated = dedupAnnotations(testAnnotations); + const deduplicated = dedupAnnotations(testAnnotations); expect(deduplicated).toEqual(expectedAnnotations); }); @@ -63,7 +63,7 @@ describe('Annotations', () => { ]; const expectedAnnotations = [{ id: 1, time: 1 }, { id: 2, time: 2 }, { id: 5, time: 5 }]; - let deduplicated = dedupAnnotations(testAnnotations); + const deduplicated = dedupAnnotations(testAnnotations); expect(deduplicated).toEqual(expectedAnnotations); }); }); diff --git a/public/app/features/dashboard/ad_hoc_filters.ts b/public/app/features/dashboard/ad_hoc_filters.ts index ee57db23675..412761dc716 100644 --- a/public/app/features/dashboard/ad_hoc_filters.ts +++ b/public/app/features/dashboard/ad_hoc_filters.ts @@ -30,7 +30,7 @@ export class AdHocFiltersCtrl { if (this.variable.value && !_.isArray(this.variable.value)) { } - for (let tag of this.variable.filters) { + for (const tag of this.variable.filters) { if (this.segments.length > 0) { this.segments.push(this.uiSegmentSrv.newCondition('AND')); } diff --git a/public/app/features/dashboard/change_tracker.ts b/public/app/features/dashboard/change_tracker.ts index 745b76ce347..1417510bb2c 100644 --- a/public/app/features/dashboard/change_tracker.ts +++ b/public/app/features/dashboard/change_tracker.ts @@ -94,13 +94,13 @@ export class ChangeTracker { // remove stuff that should not count in diff cleanDashboardFromIgnoredChanges(dashData) { // need to new up the domain model class to get access to expand / collapse row logic - let model = new DashboardModel(dashData); + const model = new DashboardModel(dashData); // Expand all rows before making comparison. This is required because row expand / collapse // change order of panel array and panel positions. model.expandRows(); - let dash = model.getSaveModelClone(); + const dash = model.getSaveModelClone(); // ignore time and refresh dash.time = 0; @@ -138,8 +138,8 @@ export class ChangeTracker { } hasChanges() { - let current = this.cleanDashboardFromIgnoredChanges(this.current.getSaveModelClone()); - let original = this.cleanDashboardFromIgnoredChanges(this.original); + const current = this.cleanDashboardFromIgnoredChanges(this.current.getSaveModelClone()); + const original = this.cleanDashboardFromIgnoredChanges(this.original); var currentTimepicker = _.find(current.nav, { type: 'timepicker' }); var originalTimepicker = _.find(original.nav, { type: 'timepicker' }); diff --git a/public/app/features/dashboard/dashboard_import_ctrl.ts b/public/app/features/dashboard/dashboard_import_ctrl.ts index 73e9e316b4e..b70a1847602 100644 --- a/public/app/features/dashboard/dashboard_import_ctrl.ts +++ b/public/app/features/dashboard/dashboard_import_ctrl.ts @@ -51,7 +51,7 @@ export class DashboardImportCtrl { this.inputs = []; if (this.dash.__inputs) { - for (let input of this.dash.__inputs) { + for (const input of this.dash.__inputs) { var inputModel = { name: input.name, label: input.label, @@ -95,7 +95,7 @@ export class DashboardImportCtrl { inputValueChanged() { this.inputsValid = true; - for (let input of this.inputs) { + for (const input of this.inputs) { if (!input.value) { this.inputsValid = false; } diff --git a/public/app/features/dashboard/dashboard_migration.ts b/public/app/features/dashboard/dashboard_migration.ts index 1d319929bfd..3753cbe7c55 100644 --- a/public/app/features/dashboard/dashboard_migration.ts +++ b/public/app/features/dashboard/dashboard_migration.ts @@ -389,7 +389,7 @@ export class DashboardMigrator { upgradeToGridLayout(old) { let yPos = 0; - let widthFactor = GRID_COLUMN_COUNT / 12; + const widthFactor = GRID_COLUMN_COUNT / 12; const maxPanelId = _.max( _.flattenDeep( @@ -407,15 +407,15 @@ export class DashboardMigrator { // Add special "row" panels if even one row is collapsed, repeated or has visible title const showRows = _.some(old.rows, row => row.collapse || row.showTitle || row.repeat); - for (let row of old.rows) { + for (const row of old.rows) { if (row.repeatIteration) { continue; } - let height: any = row.height || DEFAULT_ROW_HEIGHT; + const height: any = row.height || DEFAULT_ROW_HEIGHT; const rowGridHeight = getGridHeight(height); - let rowPanel: any = {}; + const rowPanel: any = {}; let rowPanelModel: PanelModel; if (showRows) { // add special row panel @@ -436,9 +436,9 @@ export class DashboardMigrator { yPos++; } - let rowArea = new RowArea(rowGridHeight, GRID_COLUMN_COUNT, yPos); + const rowArea = new RowArea(rowGridHeight, GRID_COLUMN_COUNT, yPos); - for (let panel of row.panels) { + for (const panel of row.panels) { panel.span = panel.span || DEFAULT_PANEL_SPAN; if (panel.minSpan) { panel.minSpan = Math.min(GRID_COLUMN_COUNT, GRID_COLUMN_COUNT / 12 * panel.minSpan); @@ -446,7 +446,7 @@ export class DashboardMigrator { const panelWidth = Math.floor(panel.span) * widthFactor; const panelHeight = panel.height ? getGridHeight(panel.height) : rowGridHeight; - let panelPos = rowArea.getPanelPosition(panelHeight, panelWidth); + const panelPos = rowArea.getPanelPosition(panelHeight, panelWidth); yPos = rowArea.yPos; panel.gridPos = { x: panelPos.x, diff --git a/public/app/features/dashboard/dashboard_model.ts b/public/app/features/dashboard/dashboard_model.ts index 92392fc80e8..8f61cf06c60 100644 --- a/public/app/features/dashboard/dashboard_model.ts +++ b/public/app/features/dashboard/dashboard_model.ts @@ -95,7 +95,7 @@ export class DashboardModel { addBuiltInAnnotationQuery() { let found = false; - for (let item of this.annotations.list) { + for (const item of this.annotations.list) { if (item.builtIn === 1) { found = true; break; @@ -138,7 +138,7 @@ export class DashboardModel { // cleans meta data and other non persistent state getSaveModelClone(options?) { - let defaults = _.defaults(options || {}, { + const defaults = _.defaults(options || {}, { saveVariables: true, saveTimerange: true, }); @@ -160,8 +160,8 @@ export class DashboardModel { if (!defaults.saveVariables) { for (let i = 0; i < copy.templating.list.length; i++) { - let current = copy.templating.list[i]; - let original = _.find(this.originalTemplating, { name: current.name, type: current.type }); + const current = copy.templating.list[i]; + const original = _.find(this.originalTemplating, { name: current.name, type: current.type }); if (!original) { continue; @@ -213,13 +213,13 @@ export class DashboardModel { getNextPanelId() { let max = 0; - for (let panel of this.panels) { + for (const panel of this.panels) { if (panel.id > max) { max = panel.id; } if (panel.collapsed) { - for (let rowPanel of panel.panels) { + for (const rowPanel of panel.panels) { if (rowPanel.id > max) { max = rowPanel.id; } @@ -237,7 +237,7 @@ export class DashboardModel { } getPanelById(id) { - for (let panel of this.panels) { + for (const panel of this.panels) { if (panel.id === id) { return panel; } @@ -248,7 +248,7 @@ export class DashboardModel { addPanel(panelData) { panelData.id = this.getNextPanelId(); - let panel = new PanelModel(panelData); + const panel = new PanelModel(panelData); this.panels.unshift(panel); @@ -273,15 +273,15 @@ export class DashboardModel { } this.iteration = (this.iteration || new Date().getTime()) + 1; - let panelsToRemove = []; + const panelsToRemove = []; // cleanup scopedVars - for (let panel of this.panels) { + for (const panel of this.panels) { delete panel.scopedVars; } for (let i = 0; i < this.panels.length; i++) { - let panel = this.panels[i]; + const panel = this.panels[i]; if ((!panel.repeat || panel.repeatedByRow) && panel.repeatPanelId && panel.repeatIteration !== this.iteration) { panelsToRemove.push(panel); } @@ -304,7 +304,7 @@ export class DashboardModel { this.iteration = (this.iteration || new Date().getTime()) + 1; for (let i = 0; i < this.panels.length; i++) { - let panel = this.panels[i]; + const panel = this.panels[i]; if (panel.repeat) { this.repeatPanel(panel, i); } @@ -315,9 +315,9 @@ export class DashboardModel { } cleanUpRowRepeats(rowPanels) { - let panelsToRemove = []; + const panelsToRemove = []; for (let i = 0; i < rowPanels.length; i++) { - let panel = rowPanels[i]; + const panel = rowPanels[i]; if (!panel.repeat && panel.repeatPanelId) { panelsToRemove.push(panel); } @@ -333,16 +333,16 @@ export class DashboardModel { let rowPanels = row.panels; if (!row.collapsed) { - let rowPanelIndex = _.findIndex(this.panels, p => p.id === row.id); + const rowPanelIndex = _.findIndex(this.panels, p => p.id === row.id); rowPanels = this.getRowPanels(rowPanelIndex); } this.cleanUpRowRepeats(rowPanels); for (let i = 0; i < rowPanels.length; i++) { - let panel = rowPanels[i]; + const panel = rowPanels[i]; if (panel.repeat) { - let panelIndex = _.findIndex(this.panels, p => p.id === panel.id); + const panelIndex = _.findIndex(this.panels, p => p.id === panel.id); this.repeatPanel(panel, panelIndex); } } @@ -354,7 +354,7 @@ export class DashboardModel { return sourcePanel; } - let clone = new PanelModel(sourcePanel.getSaveModel()); + const clone = new PanelModel(sourcePanel.getSaveModel()); clone.id = this.getNextPanelId(); // insert after source panel + value index @@ -370,13 +370,13 @@ export class DashboardModel { // if first clone return source if (valueIndex === 0) { if (!sourceRowPanel.collapsed) { - let rowPanels = this.getRowPanels(sourcePanelIndex); + const rowPanels = this.getRowPanels(sourcePanelIndex); sourceRowPanel.panels = rowPanels; } return sourceRowPanel; } - let clone = new PanelModel(sourceRowPanel.getSaveModel()); + const clone = new PanelModel(sourceRowPanel.getSaveModel()); // for row clones we need to figure out panels under row to clone and where to insert clone let rowPanels, insertPos; if (sourceRowPanel.collapsed) { @@ -397,7 +397,7 @@ export class DashboardModel { } repeatPanel(panel: PanelModel, panelIndex: number) { - let variable = _.find(this.templating.list, { name: panel.repeat }); + const variable = _.find(this.templating.list, { name: panel.repeat }); if (!variable) { return; } @@ -407,13 +407,13 @@ export class DashboardModel { return; } - let selectedOptions = this.getSelectedVariableOptions(variable); - let minWidth = panel.minSpan || 6; + const selectedOptions = this.getSelectedVariableOptions(variable); + const minWidth = panel.minSpan || 6; let xPos = 0; let yPos = panel.gridPos.y; for (let index = 0; index < selectedOptions.length; index++) { - let option = selectedOptions[index]; + const option = selectedOptions[index]; let copy; copy = this.getPanelRepeatClone(panel, index, panelIndex); @@ -443,9 +443,9 @@ export class DashboardModel { } // Update gridPos for panels below - let yOffset = yPos - panel.gridPos.y; + const yOffset = yPos - panel.gridPos.y; if (yOffset > 0) { - let panelBelowIndex = panelIndex + selectedOptions.length; + const panelBelowIndex = panelIndex + selectedOptions.length; for (let i = panelBelowIndex; i < this.panels.length; i++) { this.panels[i].gridPos.y += yOffset; } @@ -453,7 +453,7 @@ export class DashboardModel { } repeatRow(panel: PanelModel, panelIndex: number, variable) { - let selectedOptions = this.getSelectedVariableOptions(variable); + const selectedOptions = this.getSelectedVariableOptions(variable); let yPos = panel.gridPos.y; function setScopedVars(panel, variableOption) { @@ -462,12 +462,12 @@ export class DashboardModel { } for (let optionIndex = 0; optionIndex < selectedOptions.length; optionIndex++) { - let option = selectedOptions[optionIndex]; - let rowCopy = this.getRowRepeatClone(panel, optionIndex, panelIndex); + const option = selectedOptions[optionIndex]; + const rowCopy = this.getRowRepeatClone(panel, optionIndex, panelIndex); setScopedVars(rowCopy, option); - let rowHeight = this.getRowHeight(rowCopy); - let rowPanels = rowCopy.panels || []; + const rowHeight = this.getRowHeight(rowCopy); + const rowPanels = rowCopy.panels || []; let panelBelowIndex; if (panel.collapsed) { @@ -483,11 +483,11 @@ export class DashboardModel { panelBelowIndex = panelIndex + optionIndex + 1; } else { // insert after 'row' panel - let insertPos = panelIndex + (rowPanels.length + 1) * optionIndex + 1; + const insertPos = panelIndex + (rowPanels.length + 1) * optionIndex + 1; _.each(rowPanels, (rowPanel, i) => { setScopedVars(rowPanel, option); if (optionIndex > 0) { - let cloneRowPanel = new PanelModel(rowPanel); + const cloneRowPanel = new PanelModel(rowPanel); this.updateRepeatedPanelIds(cloneRowPanel, true); // For exposed row additionally set proper Y grid position and add it to dashboard panels cloneRowPanel.gridPos.y += rowHeight * optionIndex; @@ -650,29 +650,29 @@ export class DashboardModel { formatDate(date, format?) { date = moment.isMoment(date) ? date : moment(date); format = format || 'YYYY-MM-DD HH:mm:ss'; - let timezone = this.getTimezone(); + const timezone = this.getTimezone(); return timezone === 'browser' ? moment(date).format(format) : moment.utc(date).format(format); } destroy() { this.events.removeAllListeners(); - for (let panel of this.panels) { + for (const panel of this.panels) { panel.destroy(); } } toggleRow(row: PanelModel) { - let rowIndex = _.indexOf(this.panels, row); + const rowIndex = _.indexOf(this.panels, row); if (row.collapsed) { row.collapsed = false; - let hasRepeat = _.some(row.panels, p => p.repeat); + const hasRepeat = _.some(row.panels, p => p.repeat); if (row.panels.length > 0) { // Use first panel to figure out if it was moved or pushed - let firstPanel = row.panels[0]; - let yDiff = firstPanel.gridPos.y - (row.gridPos.y + row.gridPos.h); + const firstPanel = row.panels[0]; + const yDiff = firstPanel.gridPos.y - (row.gridPos.y + row.gridPos.h); // start inserting after row let insertPos = rowIndex + 1; @@ -680,7 +680,7 @@ export class DashboardModel { // needed to know home much panels below should be pushed down let yMax = row.gridPos.y; - for (let panel of row.panels) { + for (const panel of row.panels) { // make sure y is adjusted (in case row moved while collapsed) // console.log('yDiff', yDiff); panel.gridPos.y -= yDiff; @@ -713,7 +713,7 @@ export class DashboardModel { return; } - let rowPanels = this.getRowPanels(rowIndex); + const rowPanels = this.getRowPanels(rowIndex); // remove panels _.pull(this.panels, ...rowPanels); @@ -729,10 +729,10 @@ export class DashboardModel { * Will return all panels after rowIndex until it encounters another row */ getRowPanels(rowIndex: number): PanelModel[] { - let rowPanels = []; + const rowPanels = []; for (let index = rowIndex + 1; index < this.panels.length; index++) { - let panel = this.panels[index]; + const panel = this.panels[index]; // break when encountering another row if (panel.type === 'row') { @@ -791,7 +791,7 @@ export class DashboardModel { } private updateSchema(old) { - let migrator = new DashboardMigrator(this); + const migrator = new DashboardMigrator(this); migrator.updateSchema(old); } diff --git a/public/app/features/dashboard/dashgrid/AddPanelPanel.tsx b/public/app/features/dashboard/dashgrid/AddPanelPanel.tsx index f1f2290ce40..9459fc41753 100644 --- a/public/app/features/dashboard/dashgrid/AddPanelPanel.tsx +++ b/public/app/features/dashboard/dashgrid/AddPanelPanel.tsx @@ -68,18 +68,18 @@ export class AddPanelPanel extends React.Component item) .value(); let copiedPanels = []; - let copiedPanelJson = store.get(LS_PANEL_COPY_KEY); + const copiedPanelJson = store.get(LS_PANEL_COPY_KEY); if (copiedPanelJson) { - let copiedPanel = JSON.parse(copiedPanelJson); - let pluginInfo = _.find(panels, { id: copiedPanel.type }); + const copiedPanel = JSON.parse(copiedPanelJson); + const pluginInfo = _.find(panels, { id: copiedPanel.type }); if (pluginInfo) { - let pluginCopy = _.cloneDeep(pluginInfo); + const pluginCopy = _.cloneDeep(pluginInfo); pluginCopy.name = copiedPanel.title; pluginCopy.sort = -1; pluginCopy.defaults = copiedPanel; @@ -129,7 +129,7 @@ export class AddPanelPanel extends React.Component; } @@ -156,7 +156,7 @@ export class AddPanelPanel extends React.Component { return regex.test(panel.name); }); @@ -189,12 +189,12 @@ export class AddPanelPanel extends React.Component { const layout = []; this.panelMap = {}; - for (let panel of this.dashboard.panels) { - let stringId = panel.id.toString(); + for (const panel of this.dashboard.panels) { + const stringId = panel.id.toString(); this.panelMap[stringId] = panel; if (!panel.gridPos) { @@ -103,7 +103,7 @@ export class DashboardGrid extends React.Component { continue; } - let panelPos: any = { + const panelPos: any = { i: stringId, x: panel.gridPos.x, y: panel.gridPos.y, @@ -174,7 +174,7 @@ export class DashboardGrid extends React.Component { renderPanels() { const panelElements = []; - for (let panel of this.dashboard.panels) { + for (const panel of this.dashboard.panels) { const panelClasses = classNames({ panel: true, 'panel--fullscreen': panel.fullscreen }); panelElements.push(
    diff --git a/public/app/features/dashboard/dashnav/dashnav.ts b/public/app/features/dashboard/dashnav/dashnav.ts index 628f09349d3..a83efe7d390 100644 --- a/public/app/features/dashboard/dashnav/dashnav.ts +++ b/public/app/features/dashboard/dashnav/dashnav.ts @@ -22,7 +22,7 @@ export class DashNavCtrl { } toggleSettings() { - let search = this.$location.search(); + const search = this.$location.search(); if (search.editview) { delete search.editview; } else { @@ -32,7 +32,7 @@ export class DashNavCtrl { } close() { - let search = this.$location.search(); + const search = this.$location.search(); if (search.editview) { delete search.editview; } else if (search.fullscreen) { diff --git a/public/app/features/dashboard/export/export_modal.ts b/public/app/features/dashboard/export/export_modal.ts index 2e61ce9f8a8..d314f13be4b 100644 --- a/public/app/features/dashboard/export/export_modal.ts +++ b/public/app/features/dashboard/export/export_modal.ts @@ -29,7 +29,7 @@ export class DashExportCtrl { saveJson() { var clone = this.dash; - let editScope = this.$rootScope.$new(); + const editScope = this.$rootScope.$new(); editScope.object = clone; editScope.enableCopy = true; diff --git a/public/app/features/dashboard/export/exporter.ts b/public/app/features/dashboard/export/exporter.ts index fc24de76fcc..91e9f12ae54 100644 --- a/public/app/features/dashboard/export/exporter.ts +++ b/public/app/features/dashboard/export/exporter.ts @@ -24,7 +24,7 @@ export class DashboardExporter { var promises = []; var variableLookup: any = {}; - for (let variable of saveModel.templating.list) { + for (const variable of saveModel.templating.list) { variableLookup[variable.name] = variable; } @@ -69,7 +69,7 @@ export class DashboardExporter { } if (panel.targets) { - for (let target of panel.targets) { + for (const target of panel.targets) { if (target.datasource !== undefined) { templateizeDatasourceUsage(target); } @@ -88,19 +88,19 @@ export class DashboardExporter { }; // check up panel data sources - for (let panel of saveModel.panels) { + for (const panel of saveModel.panels) { processPanel(panel); // handle collapsed rows if (panel.collapsed !== undefined && panel.collapsed === true && panel.panels) { - for (let rowPanel of panel.panels) { + for (const rowPanel of panel.panels) { processPanel(rowPanel); } } } // templatize template vars - for (let variable of saveModel.templating.list) { + for (const variable of saveModel.templating.list) { if (variable.type === 'query') { templateizeDatasourceUsage(variable); variable.options = []; @@ -110,7 +110,7 @@ export class DashboardExporter { } // templatize annotations vars - for (let annotationDef of saveModel.annotations.list) { + for (const annotationDef of saveModel.annotations.list) { templateizeDatasourceUsage(annotationDef); } @@ -129,7 +129,7 @@ export class DashboardExporter { }); // templatize constants - for (let variable of saveModel.templating.list) { + for (const variable of saveModel.templating.list) { if (variable.type === 'constant') { var refName = 'VAR_' + variable.name.replace(' ', '_').toUpperCase(); inputs.push({ diff --git a/public/app/features/dashboard/history/history.ts b/public/app/features/dashboard/history/history.ts index be6ad5af1ba..3563ccc7766 100644 --- a/public/app/features/dashboard/history/history.ts +++ b/public/app/features/dashboard/history/history.ts @@ -67,7 +67,7 @@ export class HistoryListCtrl { } revisionSelectionChanged() { - let selected = _.filter(this.revisions, { checked: true }).length; + const selected = _.filter(this.revisions, { checked: true }).length; this.canCompare = selected === 2; } @@ -134,7 +134,7 @@ export class HistoryListCtrl { .getHistoryList(this.dashboard, options) .then(revisions => { // set formatted dates & default values - for (let rev of revisions) { + for (const rev of revisions) { rev.createdDateString = this.formatDate(rev.created); rev.ageString = this.formatBasicDate(rev.created); rev.checked = false; diff --git a/public/app/features/dashboard/settings/settings.ts b/public/app/features/dashboard/settings/settings.ts index 457cac5af72..1d4a70d42aa 100755 --- a/public/app/features/dashboard/settings/settings.ts +++ b/public/app/features/dashboard/settings/settings.ts @@ -109,7 +109,7 @@ export class SettingsCtrl { const params = this.$location.search(); const url = this.$location.path(); - for (let section of this.sections) { + for (const section of this.sections) { const sectionParams = _.defaults({ editview: section.id }, params); section.url = config.appSubUrl + url + '?' + $.param(sectionParams); } diff --git a/public/app/features/dashboard/shareModalCtrl.ts b/public/app/features/dashboard/shareModalCtrl.ts index c32c2a79190..fff307c2510 100644 --- a/public/app/features/dashboard/shareModalCtrl.ts +++ b/public/app/features/dashboard/shareModalCtrl.ts @@ -91,7 +91,7 @@ export function ShareModalCtrl($scope, $rootScope, $location, $timeout, timeSrv, // This function will try to return the proper full name of the local timezone // Chrome does not handle the timezone offset (but phantomjs does) $scope.getLocalTimeZone = function() { - let utcOffset = '&tz=UTC' + encodeURIComponent(moment().format('Z')); + const utcOffset = '&tz=UTC' + encodeURIComponent(moment().format('Z')); // Older browser does not the internationalization API if (!(window).Intl) { diff --git a/public/app/features/dashboard/specs/dashboard_migration.test.ts b/public/app/features/dashboard/specs/dashboard_migration.test.ts index 07a29d58e65..f440dbb49f2 100644 --- a/public/app/features/dashboard/specs/dashboard_migration.test.ts +++ b/public/app/features/dashboard/specs/dashboard_migration.test.ts @@ -151,18 +151,18 @@ describe('DashboardModel', function() { it('should create proper grid', function() { model.rows = [createRow({ collapse: false, height: 8 }, [[6], [6]])]; - let dashboard = new DashboardModel(model); - let panelGridPos = getGridPositions(dashboard); - let expectedGrid = [{ x: 0, y: 0, w: 12, h: 8 }, { x: 12, y: 0, w: 12, h: 8 }]; + const dashboard = new DashboardModel(model); + const panelGridPos = getGridPositions(dashboard); + const expectedGrid = [{ x: 0, y: 0, w: 12, h: 8 }, { x: 12, y: 0, w: 12, h: 8 }]; expect(panelGridPos).toEqual(expectedGrid); }); it('should add special "row" panel if row is collapsed', function() { model.rows = [createRow({ collapse: true, height: 8 }, [[6], [6]]), createRow({ height: 8 }, [[12]])]; - let dashboard = new DashboardModel(model); - let panelGridPos = getGridPositions(dashboard); - let expectedGrid = [ + const dashboard = new DashboardModel(model); + const panelGridPos = getGridPositions(dashboard); + const expectedGrid = [ { x: 0, y: 0, w: 24, h: 8 }, // row { x: 0, y: 1, w: 24, h: 8 }, // row { x: 0, y: 2, w: 24, h: 8 }, @@ -176,9 +176,9 @@ describe('DashboardModel', function() { createRow({ showTitle: true, title: 'Row', height: 8 }, [[6], [6]]), createRow({ height: 8 }, [[12]]), ]; - let dashboard = new DashboardModel(model); - let panelGridPos = getGridPositions(dashboard); - let expectedGrid = [ + const dashboard = new DashboardModel(model); + const panelGridPos = getGridPositions(dashboard); + const expectedGrid = [ { x: 0, y: 0, w: 24, h: 8 }, // row { x: 0, y: 1, w: 12, h: 8 }, { x: 12, y: 1, w: 12, h: 8 }, @@ -196,9 +196,9 @@ describe('DashboardModel', function() { createRow({ height: 8 }, [[12], [6], [6]]), createRow({ collapse: true, height: 8 }, [[12]]), ]; - let dashboard = new DashboardModel(model); - let panelGridPos = getGridPositions(dashboard); - let expectedGrid = [ + const dashboard = new DashboardModel(model); + const panelGridPos = getGridPositions(dashboard); + const expectedGrid = [ { x: 0, y: 0, w: 24, h: 8 }, // row { x: 0, y: 1, w: 24, h: 8 }, // row { x: 0, y: 2, w: 24, h: 8 }, @@ -214,9 +214,9 @@ describe('DashboardModel', function() { it('should add all rows if even one collapsed or titled row is present', function() { model.rows = [createRow({ collapse: true, height: 8 }, [[6], [6]]), createRow({ height: 8 }, [[12]])]; - let dashboard = new DashboardModel(model); - let panelGridPos = getGridPositions(dashboard); - let expectedGrid = [ + const dashboard = new DashboardModel(model); + const panelGridPos = getGridPositions(dashboard); + const expectedGrid = [ { x: 0, y: 0, w: 24, h: 8 }, // row { x: 0, y: 1, w: 24, h: 8 }, // row { x: 0, y: 2, w: 24, h: 8 }, @@ -230,9 +230,9 @@ describe('DashboardModel', function() { createRow({ height: 6 }, [[6], [6, 3], [6, 3]]), createRow({ height: 6 }, [[4], [4], [4, 3], [4, 3]]), ]; - let dashboard = new DashboardModel(model); - let panelGridPos = getGridPositions(dashboard); - let expectedGrid = [ + const dashboard = new DashboardModel(model); + const panelGridPos = getGridPositions(dashboard); + const expectedGrid = [ { x: 0, y: 0, w: 12, h: 6 }, { x: 12, y: 0, w: 12, h: 3 }, { x: 12, y: 3, w: 12, h: 3 }, @@ -247,9 +247,9 @@ describe('DashboardModel', function() { it('should place panel to the right side of panel having bigger height', function() { model.rows = [createRow({ height: 6 }, [[4], [2, 3], [4, 6], [2, 3], [2, 3]])]; - let dashboard = new DashboardModel(model); - let panelGridPos = getGridPositions(dashboard); - let expectedGrid = [ + const dashboard = new DashboardModel(model); + const panelGridPos = getGridPositions(dashboard); + const expectedGrid = [ { x: 0, y: 0, w: 8, h: 6 }, { x: 8, y: 0, w: 4, h: 3 }, { x: 12, y: 0, w: 8, h: 6 }, @@ -262,9 +262,9 @@ describe('DashboardModel', function() { it('should fill current row if it possible', function() { model.rows = [createRow({ height: 9 }, [[4], [2, 3], [4, 6], [2, 3], [2, 3], [8, 3]])]; - let dashboard = new DashboardModel(model); - let panelGridPos = getGridPositions(dashboard); - let expectedGrid = [ + const dashboard = new DashboardModel(model); + const panelGridPos = getGridPositions(dashboard); + const expectedGrid = [ { x: 0, y: 0, w: 8, h: 9 }, { x: 8, y: 0, w: 4, h: 3 }, { x: 12, y: 0, w: 8, h: 6 }, @@ -278,9 +278,9 @@ describe('DashboardModel', function() { it('should fill current row if it possible (2)', function() { model.rows = [createRow({ height: 8 }, [[4], [2, 3], [4, 6], [2, 3], [2, 3], [8, 3]])]; - let dashboard = new DashboardModel(model); - let panelGridPos = getGridPositions(dashboard); - let expectedGrid = [ + const dashboard = new DashboardModel(model); + const panelGridPos = getGridPositions(dashboard); + const expectedGrid = [ { x: 0, y: 0, w: 8, h: 8 }, { x: 8, y: 0, w: 4, h: 3 }, { x: 12, y: 0, w: 8, h: 6 }, @@ -294,9 +294,9 @@ describe('DashboardModel', function() { it('should fill current row if panel height more than row height', function() { model.rows = [createRow({ height: 6 }, [[4], [2, 3], [4, 8], [2, 3], [2, 3]])]; - let dashboard = new DashboardModel(model); - let panelGridPos = getGridPositions(dashboard); - let expectedGrid = [ + const dashboard = new DashboardModel(model); + const panelGridPos = getGridPositions(dashboard); + const expectedGrid = [ { x: 0, y: 0, w: 8, h: 6 }, { x: 8, y: 0, w: 4, h: 3 }, { x: 12, y: 0, w: 8, h: 8 }, @@ -309,9 +309,9 @@ describe('DashboardModel', function() { it('should wrap panels to multiple rows', function() { model.rows = [createRow({ height: 6 }, [[6], [6], [12], [6], [3], [3]])]; - let dashboard = new DashboardModel(model); - let panelGridPos = getGridPositions(dashboard); - let expectedGrid = [ + const dashboard = new DashboardModel(model); + const panelGridPos = getGridPositions(dashboard); + const expectedGrid = [ { x: 0, y: 0, w: 12, h: 6 }, { x: 12, y: 0, w: 12, h: 6 }, { x: 0, y: 6, w: 24, h: 6 }, @@ -328,9 +328,9 @@ describe('DashboardModel', function() { createRow({ showTitle: true, title: 'Row', height: 8, repeat: 'server' }, [[6]]), createRow({ height: 8 }, [[12]]), ]; - let dashboard = new DashboardModel(model); - let panelGridPos = getGridPositions(dashboard); - let expectedGrid = [ + const dashboard = new DashboardModel(model); + const panelGridPos = getGridPositions(dashboard); + const expectedGrid = [ { x: 0, y: 0, w: 24, h: 8 }, { x: 0, y: 1, w: 12, h: 8 }, { x: 0, y: 9, w: 24, h: 8 }, @@ -359,7 +359,7 @@ describe('DashboardModel', function() { ), ]; - let dashboard = new DashboardModel(model); + const dashboard = new DashboardModel(model); expect(dashboard.panels[0].repeat).toBe('server'); expect(dashboard.panels.length).toBe(2); }); @@ -368,7 +368,7 @@ describe('DashboardModel', function() { model.rows = [createRow({ height: 8 }, [[6]])]; model.rows[0].panels[0] = { minSpan: 12 }; - let dashboard = new DashboardModel(model); + const dashboard = new DashboardModel(model); expect(dashboard.panels[0].minSpan).toBe(24); }); @@ -376,7 +376,7 @@ describe('DashboardModel', function() { model.rows = [createRow({ collapse: true, height: 8 }, [[6], [6]])]; model.rows[0].panels[0] = {}; - let dashboard = new DashboardModel(model); + const dashboard = new DashboardModel(model); expect(dashboard.panels[0].id).toBe(1); }); }); @@ -386,15 +386,15 @@ function createRow(options, panelDescriptions: any[]) { const PANEL_HEIGHT_STEP = GRID_CELL_HEIGHT + GRID_CELL_VMARGIN; let { collapse, height, showTitle, title, repeat, repeatIteration } = options; height = height * PANEL_HEIGHT_STEP; - let panels = []; + const panels = []; _.each(panelDescriptions, panelDesc => { - let panel = { span: panelDesc[0] }; + const panel = { span: panelDesc[0] }; if (panelDesc.length > 1) { panel['height'] = panelDesc[1] * PANEL_HEIGHT_STEP; } panels.push(panel); }); - let row = { + const row = { collapse, height, showTitle, diff --git a/public/app/features/dashboard/specs/dashboard_model.test.ts b/public/app/features/dashboard/specs/dashboard_model.test.ts index 6ac642cd58e..28029653a6c 100644 --- a/public/app/features/dashboard/specs/dashboard_model.test.ts +++ b/public/app/features/dashboard/specs/dashboard_model.test.ts @@ -457,16 +457,16 @@ describe('DashboardModel', function() { }); it('getSaveModelClone should return original time when saveTimerange=false', () => { - let options = { saveTimerange: false }; - let saveModel = model.getSaveModelClone(options); + const options = { saveTimerange: false }; + const saveModel = model.getSaveModelClone(options); expect(saveModel.time.from).toBe('now-6h'); expect(saveModel.time.to).toBe('now'); }); it('getSaveModelClone should return updated time when saveTimerange=true', () => { - let options = { saveTimerange: true }; - let saveModel = model.getSaveModelClone(options); + const options = { saveTimerange: true }; + const saveModel = model.getSaveModelClone(options); expect(saveModel.time.from).toBe('now-3h'); expect(saveModel.time.to).toBe('now-1h'); @@ -478,16 +478,16 @@ describe('DashboardModel', function() { }); it('getSaveModelClone should return original time when saveTimerange=false', () => { - let options = { saveTimerange: false }; - let saveModel = model.getSaveModelClone(options); + const options = { saveTimerange: false }; + const saveModel = model.getSaveModelClone(options); expect(saveModel.time.from).toBe('now-6h'); expect(saveModel.time.to).toBe('now'); }); it('getSaveModelClone should return updated time when saveTimerange=true', () => { - let options = { saveTimerange: true }; - let saveModel = model.getSaveModelClone(options); + const options = { saveTimerange: true }; + const saveModel = model.getSaveModelClone(options); expect(saveModel.time.from).toBe('now-3h'); expect(saveModel.time.to).toBe('now-1h'); @@ -542,8 +542,8 @@ describe('DashboardModel', function() { it('getSaveModelClone should return original variable when saveVariables=false', () => { model.templating.list[0].current.text = 'server_002'; - let options = { saveVariables: false }; - let saveModel = model.getSaveModelClone(options); + const options = { saveVariables: false }; + const saveModel = model.getSaveModelClone(options); expect(saveModel.templating.list[0].current.text).toBe('server_001'); }); @@ -551,8 +551,8 @@ describe('DashboardModel', function() { it('getSaveModelClone should return updated variable when saveVariables=true', () => { model.templating.list[0].current.text = 'server_002'; - let options = { saveVariables: true }; - let saveModel = model.getSaveModelClone(options); + const options = { saveVariables: true }; + const saveModel = model.getSaveModelClone(options); expect(saveModel.templating.list[0].current.text).toBe('server_002'); }); @@ -620,8 +620,8 @@ describe('DashboardModel', function() { it('getSaveModelClone should return original variable when saveVariables=false', () => { model.templating.list[0].filters[0].value = 'server 1'; - let options = { saveVariables: false }; - let saveModel = model.getSaveModelClone(options); + const options = { saveVariables: false }; + const saveModel = model.getSaveModelClone(options); expect(saveModel.templating.list[0].filters[0].value).toBe('server 20'); }); @@ -629,8 +629,8 @@ describe('DashboardModel', function() { it('getSaveModelClone should return updated variable when saveVariables=true', () => { model.templating.list[0].filters[0].value = 'server 1'; - let options = { saveVariables: true }; - let saveModel = model.getSaveModelClone(options); + const options = { saveVariables: true }; + const saveModel = model.getSaveModelClone(options); expect(saveModel.templating.list[0].filters[0].value).toBe('server 1'); }); diff --git a/public/app/features/dashboard/specs/history_ctrl.test.ts b/public/app/features/dashboard/specs/history_ctrl.test.ts index 991ecb2c60d..632f3489dae 100644 --- a/public/app/features/dashboard/specs/history_ctrl.test.ts +++ b/public/app/features/dashboard/specs/history_ctrl.test.ts @@ -70,7 +70,7 @@ describe('HistoryListCtrl', () => { }); it('should add a checked property to each revision', () => { - let actual = _.filter(historyListCtrl.revisions, rev => rev.hasOwnProperty('checked')); + const actual = _.filter(historyListCtrl.revisions, rev => rev.hasOwnProperty('checked')); expect(actual.length).toBe(4); }); @@ -78,7 +78,7 @@ describe('HistoryListCtrl', () => { historyListCtrl.revisions[0].checked = true; historyListCtrl.revisions[2].checked = true; historyListCtrl.reset(); - let actual = _.filter(historyListCtrl.revisions, rev => !rev.checked); + const actual = _.filter(historyListCtrl.revisions, rev => !rev.checked); expect(actual.length).toBe(4); }); }); diff --git a/public/app/features/dashboard/specs/history_srv.test.ts b/public/app/features/dashboard/specs/history_srv.test.ts index 401b098a0e1..5c8578ecf39 100644 --- a/public/app/features/dashboard/specs/history_srv.test.ts +++ b/public/app/features/dashboard/specs/history_srv.test.ts @@ -8,7 +8,7 @@ describe('historySrv', function() { const versionsResponse = versions(); const restoreResponse = restore; - let backendSrv = { + const backendSrv = { get: jest.fn(() => Promise.resolve({})), post: jest.fn(() => Promise.resolve({})), }; @@ -44,7 +44,7 @@ describe('historySrv', function() { describe('restoreDashboard', () => { it('should return a success response given valid parameters', function() { - let version = 6; + const version = 6; backendSrv.post = jest.fn(() => Promise.resolve(restoreResponse(version))); historySrv = new HistorySrv(backendSrv); return historySrv.restoreDashboard(dash, version).then(function(response) { @@ -54,7 +54,7 @@ describe('historySrv', function() { it('should return an empty object when not given an id', async () => { historySrv = new HistorySrv(backendSrv); - let rsp = await historySrv.restoreDashboard(emptyDash, 6); + const rsp = await historySrv.restoreDashboard(emptyDash, 6); expect(rsp).toEqual({}); }); }); diff --git a/public/app/features/dashboard/specs/repeat.test.ts b/public/app/features/dashboard/specs/repeat.test.ts index 09bb3b7c494..d8c9e3bc2ed 100644 --- a/public/app/features/dashboard/specs/repeat.test.ts +++ b/public/app/features/dashboard/specs/repeat.test.ts @@ -8,7 +8,7 @@ describe('given dashboard with panel repeat', function() { var dashboard; beforeEach(function() { - let dashboardJSON = { + const dashboardJSON = { panels: [ { id: 1, type: 'row', gridPos: { x: 0, y: 0, h: 1, w: 24 } }, { id: 2, repeat: 'apps', repeatDirection: 'h', gridPos: { x: 0, y: 1, h: 2, w: 8 } }, diff --git a/public/app/features/dashboard/specs/viewstate_srv.test.ts b/public/app/features/dashboard/specs/viewstate_srv.test.ts index 08166c6f2bd..740e3c3b9a8 100644 --- a/public/app/features/dashboard/specs/viewstate_srv.test.ts +++ b/public/app/features/dashboard/specs/viewstate_srv.test.ts @@ -4,12 +4,12 @@ import config from 'app/core/config'; import { DashboardViewState } from '../view_state_srv'; describe('when updating view state', () => { - let location = { + const location = { replace: jest.fn(), search: jest.fn(), }; - let $scope = { + const $scope = { onAppEvent: jest.fn(() => {}), dashboard: { meta: {}, @@ -17,7 +17,7 @@ describe('when updating view state', () => { }, }; - let $rootScope = {}; + const $rootScope = {}; let viewState; beforeEach(() => { diff --git a/public/app/features/dashboard/validation_srv.ts b/public/app/features/dashboard/validation_srv.ts index 817be7ca0e3..3e8306039d7 100644 --- a/public/app/features/dashboard/validation_srv.ts +++ b/public/app/features/dashboard/validation_srv.ts @@ -37,7 +37,7 @@ export class ValidationSrv { }); } - let deferred = this.$q.defer(); + const deferred = this.$q.defer(); const promises = []; promises.push(this.backendSrv.search({ type: hitTypes.FOLDER, folderIds: [folderId], query: name })); @@ -54,7 +54,7 @@ export class ValidationSrv { hits = hits.concat(res[1]); } - for (let hit of hits) { + for (const hit of hits) { if (nameLowerCased === hit.title.toLowerCase()) { deferred.reject({ type: 'EXISTING', diff --git a/public/app/features/dashboard/view_state_srv.ts b/public/app/features/dashboard/view_state_srv.ts index 1ed2d61df71..5bd4db6fddc 100644 --- a/public/app/features/dashboard/view_state_srv.ts +++ b/public/app/features/dashboard/view_state_srv.ts @@ -111,9 +111,9 @@ export class DashboardViewState { } toggleCollapsedPanelRow(panelId) { - for (let panel of this.dashboard.panels) { + for (const panel of this.dashboard.panels) { if (panel.collapsed) { - for (let rowPanel of panel.panels) { + for (const rowPanel of panel.panels) { if (rowPanel.id === panelId) { this.dashboard.toggleRow(panel); return; diff --git a/public/app/features/org/org_users_ctrl.ts b/public/app/features/org/org_users_ctrl.ts index d35b967626a..625e2749399 100644 --- a/public/app/features/org/org_users_ctrl.ts +++ b/public/app/features/org/org_users_ctrl.ts @@ -44,7 +44,7 @@ export class OrgUsersCtrl { } onQueryUpdated() { - let regex = new RegExp(this.searchQuery, 'ig'); + const regex = new RegExp(this.searchQuery, 'ig'); this.users = _.filter(this.unfiltered, item => { return regex.test(item.email) || regex.test(item.login); }); diff --git a/public/app/features/panel/metrics_tab.ts b/public/app/features/panel/metrics_tab.ts index 4da40f214a1..94aa142a6b8 100644 --- a/public/app/features/panel/metrics_tab.ts +++ b/public/app/features/panel/metrics_tab.ts @@ -28,7 +28,7 @@ export class MetricsTabCtrl { this.datasources = datasourceSrv.getMetricSources(); this.panelDsValue = this.panelCtrl.panel.datasource; - for (let ds of this.datasources) { + for (const ds of this.datasources) { if (ds.value === this.panelDsValue) { this.datasourceInstance = ds; } diff --git a/public/app/features/panel/panel_ctrl.ts b/public/app/features/panel/panel_ctrl.ts index 6402227164f..6a583b700ef 100644 --- a/public/app/features/panel/panel_ctrl.ts +++ b/public/app/features/panel/panel_ctrl.ts @@ -138,7 +138,7 @@ export class PanelCtrl { } getMenu() { - let menu = []; + const menu = []; menu.push({ text: 'View', click: 'ctrl.viewPanel();', @@ -166,7 +166,7 @@ export class PanelCtrl { // Additional items from sub-class menu.push(...this.getAdditionalMenuItems()); - let extendedMenu = this.getExtendedMenu(); + const extendedMenu = this.getExtendedMenu(); menu.push({ text: 'More ...', click: '', @@ -189,7 +189,7 @@ export class PanelCtrl { } getExtendedMenu() { - let menu = []; + const menu = []; if (!this.fullscreen && this.dashboard.meta.canEdit) { menu.push({ text: 'Duplicate', @@ -259,7 +259,7 @@ export class PanelCtrl { } editPanelJson() { - let editScope = this.$scope.$root.$new(); + const editScope = this.$scope.$root.$new(); editScope.object = this.panel.getSaveModel(); editScope.updateHandler = this.replacePanel.bind(this); editScope.enableCopy = true; @@ -276,12 +276,12 @@ export class PanelCtrl { } replacePanel(newPanel, oldPanel) { - let dashboard = this.dashboard; - let index = _.findIndex(dashboard.panels, panel => { + const dashboard = this.dashboard; + const index = _.findIndex(dashboard.panels, panel => { return panel.id === oldPanel.id; }); - let deletedPanel = dashboard.panels.splice(index, 1); + const deletedPanel = dashboard.panels.splice(index, 1); this.dashboard.events.emit('panel-removed', deletedPanel); newPanel = new PanelModel(newPanel); @@ -333,7 +333,7 @@ export class PanelCtrl { if (this.panel.links && this.panel.links.length > 0) { html += ''; @@ -73,7 +73,7 @@ function renderMenuItem(item, ctrl) { function createMenuTemplate(ctrl) { let html = ''; - for (let item of ctrl.getMenu()) { + for (const item of ctrl.getMenu()) { html += renderMenuItem(item, ctrl); } @@ -86,7 +86,7 @@ function panelHeader($compile) { restrict: 'E', template: template, link: function(scope, elem, attrs) { - let menuElem = elem.find('.panel-menu'); + const menuElem = elem.find('.panel-menu'); let menuScope; let isDragged; @@ -99,7 +99,7 @@ function panelHeader($compile) { } menuScope = scope.$new(); - let menuHtml = createMenuTemplate(scope.ctrl); + const menuHtml = createMenuTemplate(scope.ctrl); menuElem.html(menuHtml); $compile(menuElem)(menuScope); @@ -132,12 +132,12 @@ function panelHeader($compile) { .find('[data-toggle=dropdown]') .parentsUntil('.panel') .parent(); - let menuElem = elem.find('[data-toggle=dropdown]').parent(); + const menuElem = elem.find('[data-toggle=dropdown]').parent(); panelElem = panelElem && panelElem.length ? panelElem[0] : undefined; if (panelElem) { panelElem = $(panelElem); $(panelGridClass).removeClass(menuOpenClass); - let state = !menuElem.hasClass('open'); + const state = !menuElem.hasClass('open'); panelElem.toggleClass(menuOpenClass, state); } } diff --git a/public/app/features/panel/solo_panel_ctrl.ts b/public/app/features/panel/solo_panel_ctrl.ts index 242d2e7da3e..85773a3a778 100644 --- a/public/app/features/panel/solo_panel_ctrl.ts +++ b/public/app/features/panel/solo_panel_ctrl.ts @@ -34,7 +34,7 @@ export class SoloPanelCtrl { }; $scope.initPanelScope = function() { - let panelInfo = $scope.dashboard.getPanelInfoById(panelId); + const panelInfo = $scope.dashboard.getPanelInfoById(panelId); // fake row ctrl scope $scope.ctrl = { diff --git a/public/app/features/panellinks/specs/link_srv.test.ts b/public/app/features/panellinks/specs/link_srv.test.ts index 2ec38961e29..521a4edef15 100644 --- a/public/app/features/panellinks/specs/link_srv.test.ts +++ b/public/app/features/panellinks/specs/link_srv.test.ts @@ -2,7 +2,7 @@ import { LinkSrv } from '../link_srv'; import _ from 'lodash'; jest.mock('angular', () => { - let AngularJSMock = require('test/mocks/angular'); + const AngularJSMock = require('test/mocks/angular'); return new AngularJSMock(); }); diff --git a/public/app/features/playlist/playlist_routes.ts b/public/app/features/playlist/playlist_routes.ts index b898820e371..3cb9aceaefb 100644 --- a/public/app/features/playlist/playlist_routes.ts +++ b/public/app/features/playlist/playlist_routes.ts @@ -24,7 +24,7 @@ function grafanaRoutes($routeProvider) { controller: 'PlaylistsCtrl', resolve: { init: function(playlistSrv, $route) { - let playlistId = $route.current.params.id; + const playlistId = $route.current.params.id; playlistSrv.start(playlistId); }, }, diff --git a/public/app/features/playlist/specs/playlist_edit_ctrl.test.ts b/public/app/features/playlist/specs/playlist_edit_ctrl.test.ts index f313c6e8e6a..183947f5072 100644 --- a/public/app/features/playlist/specs/playlist_edit_ctrl.test.ts +++ b/public/app/features/playlist/specs/playlist_edit_ctrl.test.ts @@ -4,7 +4,7 @@ import { PlaylistEditCtrl } from '../playlist_edit_ctrl'; describe('PlaylistEditCtrl', () => { var ctx: any; beforeEach(() => { - let navModelSrv = { + const navModelSrv = { getNav: () => { return { breadcrumbs: [], node: {} }; }, diff --git a/public/app/features/plugins/ds_list_ctrl.ts b/public/app/features/plugins/ds_list_ctrl.ts index 89c760ae253..71c1a516842 100644 --- a/public/app/features/plugins/ds_list_ctrl.ts +++ b/public/app/features/plugins/ds_list_ctrl.ts @@ -17,7 +17,7 @@ export class DataSourcesCtrl { } onQueryUpdated() { - let regex = new RegExp(this.searchQuery, 'ig'); + const regex = new RegExp(this.searchQuery, 'ig'); this.datasources = _.filter(this.unfiltered, item => { regex.lastIndex = 0; return regex.test(item.name) || regex.test(item.type); diff --git a/public/app/features/plugins/plugin_component.ts b/public/app/features/plugins/plugin_component.ts index 1936e57f558..bdfb47bc861 100644 --- a/public/app/features/plugins/plugin_component.ts +++ b/public/app/features/plugins/plugin_component.ts @@ -68,7 +68,7 @@ function pluginDirectiveLoader($compile, datasourceSrv, $rootScope, $q, $http, $ }, }; - let panelInfo = config.panels[scope.panel.type]; + const panelInfo = config.panels[scope.panel.type]; var panelCtrlPromise = Promise.resolve(UnknownPanelCtrl); if (panelInfo) { panelCtrlPromise = importPluginModule(panelInfo.module).then(function(panelModule) { @@ -107,7 +107,7 @@ function pluginDirectiveLoader($compile, datasourceSrv, $rootScope, $q, $http, $ switch (attrs.type) { // QueryCtrl case 'query-ctrl': { - let datasource = scope.target.datasource || scope.ctrl.panel.datasource; + const datasource = scope.target.datasource || scope.ctrl.panel.datasource; return datasourceSrv.get(datasource).then(ds => { scope.datasource = ds; @@ -160,7 +160,7 @@ function pluginDirectiveLoader($compile, datasourceSrv, $rootScope, $q, $http, $ } // AppConfigCtrl case 'app-config-ctrl': { - let model = scope.ctrl.model; + const model = scope.ctrl.model; return importPluginModule(model.module).then(function(appModule) { return { baseUrl: model.baseUrl, @@ -173,7 +173,7 @@ function pluginDirectiveLoader($compile, datasourceSrv, $rootScope, $q, $http, $ } // App Page case 'app-page': { - let appModel = scope.ctrl.appModel; + const appModel = scope.ctrl.appModel; return importPluginModule(appModel.module).then(function(appModule) { return { baseUrl: appModel.baseUrl, diff --git a/public/app/features/plugins/plugin_edit_ctrl.ts b/public/app/features/plugins/plugin_edit_ctrl.ts index 6aa8b2bc38f..93c2008651d 100644 --- a/public/app/features/plugins/plugin_edit_ctrl.ts +++ b/public/app/features/plugins/plugin_edit_ctrl.ts @@ -53,7 +53,7 @@ export class PluginEditCtrl { url: `plugins/${this.model.id}/edit?tab=config`, }); - let hasDashboards = _.find(model.includes, { type: 'dashboard' }); + const hasDashboards = _.find(model.includes, { type: 'dashboard' }); if (hasDashboards) { this.navModel.main.children.push({ @@ -69,7 +69,7 @@ export class PluginEditCtrl { this.tab = this.$routeParams.tab || defaultTab; - for (let tab of this.navModel.main.children) { + for (const tab of this.navModel.main.children) { if (tab.id === this.tab) { tab.active = true; } @@ -98,7 +98,7 @@ export class PluginEditCtrl { initReadme() { return this.backendSrv.get(`/api/plugins/${this.pluginId}/markdown/readme`).then(res => { var md = new Remarkable({ - linkify: true + linkify: true, }); this.readmeHtml = this.$sce.trustAsHtml(md.render(res)); }); diff --git a/public/app/features/plugins/plugin_list_ctrl.ts b/public/app/features/plugins/plugin_list_ctrl.ts index 8e303143946..315252364cc 100644 --- a/public/app/features/plugins/plugin_list_ctrl.ts +++ b/public/app/features/plugins/plugin_list_ctrl.ts @@ -20,7 +20,7 @@ export class PluginListCtrl { } onQueryUpdated() { - let regex = new RegExp(this.searchQuery, 'ig'); + const regex = new RegExp(this.searchQuery, 'ig'); this.plugins = _.filter(this.allPlugins, item => { return regex.test(item.name) || regex.test(item.type); }); diff --git a/public/app/features/plugins/plugin_loader.ts b/public/app/features/plugins/plugin_loader.ts index cce494d0a60..e227dbb910c 100644 --- a/public/app/features/plugins/plugin_loader.ts +++ b/public/app/features/plugins/plugin_loader.ts @@ -140,12 +140,12 @@ const flotDeps = [ 'jquery.flot.events', 'jquery.flot.gauge', ]; -for (let flotDep of flotDeps) { +for (const flotDep of flotDeps) { exposeToPlugin(flotDep, { fakeDep: 1 }); } export function importPluginModule(path: string): Promise { - let builtIn = builtInPlugins[path]; + const builtIn = builtInPlugins[path]; if (builtIn) { return Promise.resolve(builtIn); } diff --git a/public/app/features/plugins/plugin_page_ctrl.ts b/public/app/features/plugins/plugin_page_ctrl.ts index 397916aacc8..a2920e55a2a 100644 --- a/public/app/features/plugins/plugin_page_ctrl.ts +++ b/public/app/features/plugins/plugin_page_ctrl.ts @@ -33,7 +33,7 @@ export class AppPageCtrl { return; } - let pluginNav = this.navModelSrv.getNav('plugin-page-' + app.id); + const pluginNav = this.navModelSrv.getNav('plugin-page-' + app.id); this.navModel = { main: { diff --git a/public/app/features/plugins/specs/datasource_srv.test.ts b/public/app/features/plugins/specs/datasource_srv.test.ts index b63e8537837..653e431cb9f 100644 --- a/public/app/features/plugins/specs/datasource_srv.test.ts +++ b/public/app/features/plugins/specs/datasource_srv.test.ts @@ -16,7 +16,7 @@ const templateSrv = { }; describe('datasource_srv', function() { - let _datasourceSrv = new DatasourceSrv({}, {}, {}, templateSrv); + const _datasourceSrv = new DatasourceSrv({}, {}, {}, templateSrv); describe('when loading explore sources', () => { beforeEach(() => { @@ -46,7 +46,7 @@ describe('datasource_srv', function() { describe('when loading metric sources', () => { let metricSources; - let unsortedDatasources = { + const unsortedDatasources = { mmm: { type: 'test-db', meta: { metrics: { m: 1 } }, diff --git a/public/app/features/templating/specs/editor_ctrl.test.ts b/public/app/features/templating/specs/editor_ctrl.test.ts index f49d0ccd9c6..bba175c2d86 100644 --- a/public/app/features/templating/specs/editor_ctrl.test.ts +++ b/public/app/features/templating/specs/editor_ctrl.test.ts @@ -9,7 +9,7 @@ jest.mock('app/core/app_events', () => { }); describe('VariableEditorCtrl', () => { - let scope = { + const scope = { runQuery: () => { return Promise.resolve({}); }, diff --git a/public/app/features/templating/specs/variable_srv_init.test.ts b/public/app/features/templating/specs/variable_srv_init.test.ts index ea8689f528b..e011d4d0d15 100644 --- a/public/app/features/templating/specs/variable_srv_init.test.ts +++ b/public/app/features/templating/specs/variable_srv_init.test.ts @@ -5,7 +5,7 @@ import { VariableSrv } from '../variable_srv'; import $q from 'q'; describe('VariableSrv init', function() { - let templateSrv = { + const templateSrv = { init: vars => { this.variables = vars; }, @@ -17,8 +17,8 @@ describe('VariableSrv init', function() { }), }; - let $injector = {}; - let $rootscope = { + const $injector = {}; + const $rootscope = { $on: () => {}, }; diff --git a/public/app/features/templating/variable_srv.ts b/public/app/features/templating/variable_srv.ts index bd214639552..e3e75d6a036 100644 --- a/public/app/features/templating/variable_srv.ts +++ b/public/app/features/templating/variable_srv.ts @@ -23,7 +23,7 @@ export class VariableSrv { this.templateSrv.init(this.variables); // init variables - for (let variable of this.variables) { + for (const variable of this.variables) { variable.initLock = this.$q.defer(); } @@ -60,7 +60,7 @@ export class VariableSrv { processVariable(variable, queryParams) { var dependencies = []; - for (let otherVariable of this.variables) { + for (const otherVariable of this.variables) { if (variable.dependsOn(otherVariable)) { dependencies.push(otherVariable.initLock.promise); } @@ -212,13 +212,13 @@ export class VariableSrv { }); let defaultText = urlValue; - let defaultValue = urlValue; + const defaultValue = urlValue; if (!option && _.isArray(urlValue)) { defaultText = []; for (let n = 0; n < urlValue.length; n++) { - let t = _.find(variable.options, op => { + const t = _.find(variable.options, op => { return op.value === urlValue[n]; }); @@ -275,7 +275,7 @@ export class VariableSrv { this.addVariable(variable); } - let filters = variable.filters; + const filters = variable.filters; let filter = _.find(filters, { key: options.key, value: options.value }); if (!filter) { @@ -288,7 +288,7 @@ export class VariableSrv { } createGraph() { - let g = new Graph(); + const g = new Graph(); this.variables.forEach(v1 => { g.createNode(v1.name); diff --git a/public/app/plugins/datasource/cloudwatch/datasource.ts b/public/app/plugins/datasource/cloudwatch/datasource.ts index 087bd19da71..63a35e72add 100644 --- a/public/app/plugins/datasource/cloudwatch/datasource.ts +++ b/public/app/plugins/datasource/cloudwatch/datasource.ts @@ -45,7 +45,7 @@ export default class CloudWatchDatasource { item.returnData = typeof item.hide === 'undefined' ? true : !item.hide; // valid ExtendedStatistics is like p90.00, check the pattern - let hasInvalidStatistics = item.statistics.some(s => { + const hasInvalidStatistics = item.statistics.some(s => { return s.indexOf('p') === 0 && !/p\d{2}\.\d{2}/.test(s); }); if (hasInvalidStatistics) { @@ -402,7 +402,7 @@ export default class CloudWatchDatasource { value: v, }; }); - let useSelectedVariables = + const useSelectedVariables = selectedVariables.some(s => { return s.value === currentVariables[0].value; }) || currentVariables[0].value === '$__all'; diff --git a/public/app/plugins/datasource/cloudwatch/specs/datasource.test.ts b/public/app/plugins/datasource/cloudwatch/specs/datasource.test.ts index a8968008661..eae3e91d37d 100644 --- a/public/app/plugins/datasource/cloudwatch/specs/datasource.test.ts +++ b/public/app/plugins/datasource/cloudwatch/specs/datasource.test.ts @@ -4,18 +4,18 @@ import * as dateMath from 'app/core/utils/datemath'; import _ from 'lodash'; describe('CloudWatchDatasource', function() { - let instanceSettings = { + const instanceSettings = { jsonData: { defaultRegion: 'us-east-1', access: 'proxy' }, }; - let templateSrv = { + const templateSrv = { data: {}, templateSettings: { interpolate: /\[\[([\s\S]+?)\]\]/g }, replace: text => _.template(text, templateSrv.templateSettings)(templateSrv.data), variableExists: () => false, }; - let timeSrv = { + const timeSrv = { time: { from: 'now-1h', to: 'now' }, timeRange: () => { return { @@ -24,8 +24,8 @@ describe('CloudWatchDatasource', function() { }; }, }; - let backendSrv = {}; - let ctx = { + const backendSrv = {}; + const ctx = { backendSrv, templateSrv, }; @@ -121,7 +121,7 @@ describe('CloudWatchDatasource', function() { }); }); - it('should cancel query for invalid extended statistics', function () { + it('should cancel query for invalid extended statistics', function() { var query = { range: { from: 'now-1h', to: 'now' }, rangeRaw: { from: 1483228800, to: 1483232400 }, @@ -252,7 +252,7 @@ describe('CloudWatchDatasource', function() { function describeMetricFindQuery(query, func) { describe('metricFindQuery ' + query, () => { - let scenario: any = {}; + const scenario: any = {}; scenario.setup = setupCallback => { beforeEach(() => { setupCallback(); @@ -461,12 +461,12 @@ describe('CloudWatchDatasource', function() { 3600, ], ]; - for (let t of testData) { - let target = t[0]; - let options = t[1]; - let now = new Date(options.range.from.valueOf() + t[2] * 1000); - let expected = t[3]; - let actual = ctx.ds.getPeriod(target, options, now); + for (const t of testData) { + const target = t[0]; + const options = t[1]; + const now = new Date(options.range.from.valueOf() + t[2] * 1000); + const expected = t[3]; + const actual = ctx.ds.getPeriod(target, options, now); expect(actual).toBe(expected); } }); diff --git a/public/app/plugins/datasource/elasticsearch/datasource.ts b/public/app/plugins/datasource/elasticsearch/datasource.ts index 5a8e83a16cb..b77ebe6b738 100644 --- a/public/app/plugins/datasource/elasticsearch/datasource.ts +++ b/public/app/plugins/datasource/elasticsearch/datasource.ts @@ -414,13 +414,13 @@ export class ElasticDatasource { return true; } - for (let bucketAgg of target.bucketAggs) { + for (const bucketAgg of target.bucketAggs) { if (this.templateSrv.variableExists(bucketAgg.field) || this.objectContainsTemplate(bucketAgg.settings)) { return true; } } - for (let metric of target.metrics) { + for (const metric of target.metrics) { if ( this.templateSrv.variableExists(metric.field) || this.objectContainsTemplate(metric.settings) || @@ -449,13 +449,13 @@ export class ElasticDatasource { return false; } - for (let key of Object.keys(obj)) { + for (const key of Object.keys(obj)) { if (this.isPrimitive(obj[key])) { if (this.templateSrv.variableExists(obj[key])) { return true; } } else if (Array.isArray(obj[key])) { - for (let item of obj[key]) { + for (const item of obj[key]) { if (this.objectContainsTemplate(item)) { return true; } diff --git a/public/app/plugins/datasource/elasticsearch/elastic_response.ts b/public/app/plugins/datasource/elasticsearch/elastic_response.ts index a378ab8b55f..e792d290d5b 100644 --- a/public/app/plugins/datasource/elasticsearch/elastic_response.ts +++ b/public/app/plugins/datasource/elasticsearch/elastic_response.ts @@ -112,29 +112,29 @@ export class ElasticResponse { processAggregationDocs(esAgg, aggDef, target, table, props) { // add columns if (table.columns.length === 0) { - for (let propKey of _.keys(props)) { + for (const propKey of _.keys(props)) { table.addColumn({ text: propKey, filterable: true }); } table.addColumn({ text: aggDef.field, filterable: true }); } // helper func to add values to value array - let addMetricValue = (values, metricName, value) => { + const addMetricValue = (values, metricName, value) => { table.addColumn({ text: metricName }); values.push(value); }; - for (let bucket of esAgg.buckets) { - let values = []; + for (const bucket of esAgg.buckets) { + const values = []; - for (let propValues of _.values(props)) { + for (const propValues of _.values(props)) { values.push(propValues); } // add bucket key (value) values.push(bucket.key); - for (let metric of target.metrics) { + for (const metric of target.metrics) { switch (metric.type) { case 'count': { addMetricValue(values, this.getMetricName(metric.type), bucket.doc_count); @@ -157,7 +157,7 @@ export class ElasticResponse { } default: { let metricName = this.getMetricName(metric.type); - let otherMetrics = _.filter(target.metrics, { type: metric.type }); + const otherMetrics = _.filter(target.metrics, { type: metric.type }); // if more of the same metric type include field field name in property if (otherMetrics.length > 1) { diff --git a/public/app/plugins/datasource/elasticsearch/specs/datasource.test.ts b/public/app/plugins/datasource/elasticsearch/specs/datasource.test.ts index 36e7a63a005..d1e2e3ba835 100644 --- a/public/app/plugins/datasource/elasticsearch/specs/datasource.test.ts +++ b/public/app/plugins/datasource/elasticsearch/specs/datasource.test.ts @@ -6,21 +6,21 @@ import { ElasticDatasource } from '../datasource'; import * as dateMath from 'app/core/utils/datemath'; describe('ElasticDatasource', function() { - let backendSrv = { + const backendSrv = { datasourceRequest: jest.fn(), }; - let $rootScope = { + const $rootScope = { $on: jest.fn(), appEvent: jest.fn(), }; - let templateSrv = { + const templateSrv = { replace: jest.fn(text => text), getAdhocFilters: jest.fn(() => []), }; - let timeSrv = { + const timeSrv = { time: { from: 'now-1h', to: 'now' }, timeRange: jest.fn(() => { return { @@ -33,7 +33,7 @@ describe('ElasticDatasource', function() { }), }; - let ctx = { + const ctx = { $rootScope, backendSrv, }; diff --git a/public/app/plugins/datasource/grafana/datasource.ts b/public/app/plugins/datasource/grafana/datasource.ts index 9fa32fa6503..c3687161414 100644 --- a/public/app/plugins/datasource/grafana/datasource.ts +++ b/public/app/plugins/datasource/grafana/datasource.ts @@ -17,7 +17,7 @@ class GrafanaDatasource { if (res.results) { _.forEach(res.results, queryRes => { - for (let series of queryRes.series) { + for (const series of queryRes.series) { data.push({ target: series.name, datapoints: series.points, diff --git a/public/app/plugins/datasource/graphite/datasource.ts b/public/app/plugins/datasource/graphite/datasource.ts index bc1c5722c3f..d4bdabd1f56 100644 --- a/public/app/plugins/datasource/graphite/datasource.ts +++ b/public/app/plugins/datasource/graphite/datasource.ts @@ -210,8 +210,8 @@ export function GraphiteDatasource(instanceSettings, $q, backendSrv, templateSrv }; this.metricFindQuery = function(query, optionalOptions) { - let options = optionalOptions || {}; - let interpolatedQuery = templateSrv.replace(query); + const options = optionalOptions || {}; + const interpolatedQuery = templateSrv.replace(query); // special handling for tag_values([,]*), this is used for template variables let matches = interpolatedQuery.match(/^tag_values\(([^,]+)((, *[^,]+)*)\)$/); @@ -242,7 +242,7 @@ export function GraphiteDatasource(instanceSettings, $q, backendSrv, templateSrv return this.getTagsAutoComplete(expressions, undefined, options); } - let httpOptions: any = { + const httpOptions: any = { method: 'GET', url: '/metrics/find', params: { @@ -268,9 +268,9 @@ export function GraphiteDatasource(instanceSettings, $q, backendSrv, templateSrv }; this.getTags = function(optionalOptions) { - let options = optionalOptions || {}; + const options = optionalOptions || {}; - let httpOptions: any = { + const httpOptions: any = { method: 'GET', url: '/tags', // for cancellations @@ -293,9 +293,9 @@ export function GraphiteDatasource(instanceSettings, $q, backendSrv, templateSrv }; this.getTagValues = function(tag, optionalOptions) { - let options = optionalOptions || {}; + const options = optionalOptions || {}; - let httpOptions: any = { + const httpOptions: any = { method: 'GET', url: '/tags/' + templateSrv.replace(tag), // for cancellations @@ -322,9 +322,9 @@ export function GraphiteDatasource(instanceSettings, $q, backendSrv, templateSrv }; this.getTagsAutoComplete = (expressions, tagPrefix, optionalOptions) => { - let options = optionalOptions || {}; + const options = optionalOptions || {}; - let httpOptions: any = { + const httpOptions: any = { method: 'GET', url: '/tags/autoComplete/tags', params: { @@ -357,9 +357,9 @@ export function GraphiteDatasource(instanceSettings, $q, backendSrv, templateSrv }; this.getTagValuesAutoComplete = (expressions, tag, valuePrefix, optionalOptions) => { - let options = optionalOptions || {}; + const options = optionalOptions || {}; - let httpOptions: any = { + const httpOptions: any = { method: 'GET', url: '/tags/autoComplete/values', params: { @@ -393,9 +393,9 @@ export function GraphiteDatasource(instanceSettings, $q, backendSrv, templateSrv }; this.getVersion = function(optionalOptions) { - let options = optionalOptions || {}; + const options = optionalOptions || {}; - let httpOptions = { + const httpOptions = { method: 'GET', url: '/version', requestId: options.requestId, @@ -404,7 +404,7 @@ export function GraphiteDatasource(instanceSettings, $q, backendSrv, templateSrv return this.doGraphiteRequest(httpOptions) .then(results => { if (results.data) { - let semver = new SemVersion(results.data); + const semver = new SemVersion(results.data); return semver.isValid() ? results.data : ''; } return ''; @@ -437,7 +437,7 @@ export function GraphiteDatasource(instanceSettings, $q, backendSrv, templateSrv return this.funcDefsPromise; } - let httpOptions = { + const httpOptions = { method: 'GET', url: '/functions', }; @@ -461,7 +461,7 @@ export function GraphiteDatasource(instanceSettings, $q, backendSrv, templateSrv }; this.testDatasource = function() { - let query = { + const query = { panelId: 3, rangeRaw: { from: 'now-1h', to: 'now' }, targets: [{ target: 'constantLine(100)' }], diff --git a/public/app/plugins/datasource/graphite/graphite_query.ts b/public/app/plugins/datasource/graphite/graphite_query.ts index baa58237708..7563a42f583 100644 --- a/public/app/plugins/datasource/graphite/graphite_query.ts +++ b/public/app/plugins/datasource/graphite/graphite_query.ts @@ -59,11 +59,11 @@ export default class GraphiteQuery { } checkForSeriesByTag() { - let seriesByTagFunc = _.find(this.functions, func => func.def.name === 'seriesByTag'); + const seriesByTagFunc = _.find(this.functions, func => func.def.name === 'seriesByTag'); if (seriesByTagFunc) { this.seriesByTagUsed = true; seriesByTagFunc.hidden = true; - let tags = this.splitSeriesByTagParams(seriesByTagFunc); + const tags = this.splitSeriesByTagParams(seriesByTagFunc); this.tags = tags; } } @@ -186,8 +186,8 @@ export default class GraphiteQuery { let refCount = 0; _.each(targetsByRefId, (t, id) => { if (id !== refId) { - let match = nestedSeriesRefRegex.exec(t.target); - let count = match && match.length ? match.length - 1 : 0; + const match = nestedSeriesRefRegex.exec(t.target); + const count = match && match.length ? match.length - 1 : 0; refCount += count; } }); @@ -232,9 +232,9 @@ export default class GraphiteQuery { const tagPattern = /([^\!=~]+)(\!?=~?)(.*)/; return _.flatten( _.map(func.params, (param: string) => { - let matches = tagPattern.exec(param); + const matches = tagPattern.exec(param); if (matches) { - let tag = matches.slice(1); + const tag = matches.slice(1); if (tag.length === 3) { return { key: tag[0], @@ -253,7 +253,7 @@ export default class GraphiteQuery { } getSeriesByTagFunc() { - let seriesByTagFuncIndex = this.getSeriesByTagFuncIndex(); + const seriesByTagFuncIndex = this.getSeriesByTagFuncIndex(); if (seriesByTagFuncIndex >= 0) { return this.functions[seriesByTagFuncIndex]; } else { @@ -262,7 +262,7 @@ export default class GraphiteQuery { } addTag(tag) { - let newTagParam = renderTagString(tag); + const newTagParam = renderTagString(tag); this.getSeriesByTagFunc().params.push(newTagParam); this.tags.push(tag); } @@ -280,7 +280,7 @@ export default class GraphiteQuery { return; } - let newTagParam = renderTagString(tag); + const newTagParam = renderTagString(tag); this.getSeriesByTagFunc().params[tagIndex] = newTagParam; this.tags[tagIndex] = tag; } diff --git a/public/app/plugins/datasource/graphite/query_ctrl.ts b/public/app/plugins/datasource/graphite/query_ctrl.ts index 0563de61705..f73c21e4cc7 100644 --- a/public/app/plugins/datasource/graphite/query_ctrl.ts +++ b/public/app/plugins/datasource/graphite/query_ctrl.ts @@ -49,7 +49,7 @@ export class GraphiteQueryCtrl extends QueryCtrl { return this.uiSegmentSrv.newSegment(segment); }); - let checkOtherSegmentsIndex = this.queryModel.checkOtherSegmentsIndex || 0; + const checkOtherSegmentsIndex = this.queryModel.checkOtherSegmentsIndex || 0; this.checkOtherSegments(checkOtherSegmentsIndex); if (this.queryModel.seriesByTagUsed) { @@ -195,7 +195,7 @@ export class GraphiteQueryCtrl extends QueryCtrl { } if (segment.type === 'tag') { - let tag = removeTagPrefix(segment.value); + const tag = removeTagPrefix(segment.value); this.pause(); this.addSeriesByTagFunc(tag); return; @@ -273,10 +273,10 @@ export class GraphiteQueryCtrl extends QueryCtrl { } addSeriesByTagFunc(tag) { - let newFunc = this.datasource.createFuncInstance('seriesByTag', { + const newFunc = this.datasource.createFuncInstance('seriesByTag', { withDefaultParams: false, }); - let tagParam = `${tag}=`; + const tagParam = `${tag}=`; newFunc.params = [tagParam]; this.queryModel.addFunction(newFunc); newFunc.added = true; @@ -303,23 +303,23 @@ export class GraphiteQueryCtrl extends QueryCtrl { getAllTags() { return this.datasource.getTags().then(values => { - let altTags = _.map(values, 'text'); + const altTags = _.map(values, 'text'); altTags.splice(0, 0, this.removeTagValue); return mapToDropdownOptions(altTags); }); } getTags(index, tagPrefix) { - let tagExpressions = this.queryModel.renderTagExpressions(index); + const tagExpressions = this.queryModel.renderTagExpressions(index); return this.datasource.getTagsAutoComplete(tagExpressions, tagPrefix).then(values => { - let altTags = _.map(values, 'text'); + const altTags = _.map(values, 'text'); altTags.splice(0, 0, this.removeTagValue); return mapToDropdownOptions(altTags); }); } getTagsAsSegments(tagPrefix) { - let tagExpressions = this.queryModel.renderTagExpressions(); + const tagExpressions = this.queryModel.renderTagExpressions(); return this.datasource.getTagsAutoComplete(tagExpressions, tagPrefix).then(values => { return _.map(values, val => { return this.uiSegmentSrv.newSegment({ @@ -336,18 +336,18 @@ export class GraphiteQueryCtrl extends QueryCtrl { } getAllTagValues(tag) { - let tagKey = tag.key; + const tagKey = tag.key; return this.datasource.getTagValues(tagKey).then(values => { - let altValues = _.map(values, 'text'); + const altValues = _.map(values, 'text'); return mapToDropdownOptions(altValues); }); } getTagValues(tag, index, valuePrefix) { - let tagExpressions = this.queryModel.renderTagExpressions(index); - let tagKey = tag.key; + const tagExpressions = this.queryModel.renderTagExpressions(index); + const tagKey = tag.key; return this.datasource.getTagValuesAutoComplete(tagExpressions, tagKey, valuePrefix).then(values => { - let altValues = _.map(values, 'text'); + const altValues = _.map(values, 'text'); // Add template variables as additional values _.eachRight(this.templateSrv.variables, variable => { altValues.push('${' + variable.name + ':regex}'); @@ -362,8 +362,8 @@ export class GraphiteQueryCtrl extends QueryCtrl { } addNewTag(segment) { - let newTagKey = segment.value; - let newTag = { key: newTagKey, operator: '=', value: '' }; + const newTagKey = segment.value; + const newTag = { key: newTagKey, operator: '=', value: '' }; this.queryModel.addTag(newTag); this.targetChanged(); this.fixTagSegments(); diff --git a/public/app/plugins/datasource/graphite/specs/datasource.test.ts b/public/app/plugins/datasource/graphite/specs/datasource.test.ts index f94378c57a6..826f2fed344 100644 --- a/public/app/plugins/datasource/graphite/specs/datasource.test.ts +++ b/public/app/plugins/datasource/graphite/specs/datasource.test.ts @@ -5,7 +5,7 @@ import $q from 'q'; import { TemplateSrvStub } from 'test/specs/helpers'; describe('graphiteDatasource', () => { - let ctx: any = { + const ctx: any = { backendSrv: {}, $q: $q, templateSrv: new TemplateSrvStub(), @@ -18,7 +18,7 @@ describe('graphiteDatasource', () => { }); describe('When querying graphite with one target using query editor target spec', function() { - let query = { + const query = { panelId: 3, dashboardId: 5, rangeRaw: { from: 'now-1h', to: 'now' }, @@ -56,7 +56,7 @@ describe('graphiteDatasource', () => { }); it('should query correctly', function() { - let params = requestOptions.data.split('&'); + const params = requestOptions.data.split('&'); expect(params).toContain('target=prod1.count'); expect(params).toContain('target=prod2.count'); expect(params).toContain('from=-1h'); @@ -64,7 +64,7 @@ describe('graphiteDatasource', () => { }); it('should exclude undefined params', function() { - let params = requestOptions.data.split('&'); + const params = requestOptions.data.split('&'); expect(params).not.toContain('cacheTimeout=undefined'); }); @@ -157,28 +157,28 @@ describe('graphiteDatasource', () => { describe('building graphite params', function() { it('should return empty array if no targets', function() { - let results = ctx.ds.buildGraphiteParams({ + const results = ctx.ds.buildGraphiteParams({ targets: [{}], }); expect(results.length).toBe(0); }); it('should uri escape targets', function() { - let results = ctx.ds.buildGraphiteParams({ + const results = ctx.ds.buildGraphiteParams({ targets: [{ target: 'prod1.{test,test2}' }, { target: 'prod2.count' }], }); expect(results).toContain('target=prod1.%7Btest%2Ctest2%7D'); }); it('should replace target placeholder', function() { - let results = ctx.ds.buildGraphiteParams({ + const results = ctx.ds.buildGraphiteParams({ targets: [{ target: 'series1' }, { target: 'series2' }, { target: 'asPercent(#A,#B)' }], }); expect(results[2]).toBe('target=asPercent(series1%2Cseries2)'); }); it('should replace target placeholder for hidden series', function() { - let results = ctx.ds.buildGraphiteParams({ + const results = ctx.ds.buildGraphiteParams({ targets: [ { target: 'series1', hide: true }, { target: 'sumSeries(#A)', hide: true }, @@ -189,28 +189,28 @@ describe('graphiteDatasource', () => { }); it('should replace target placeholder when nesting query references', function() { - let results = ctx.ds.buildGraphiteParams({ + const results = ctx.ds.buildGraphiteParams({ targets: [{ target: 'series1' }, { target: 'sumSeries(#A)' }, { target: 'asPercent(#A,#B)' }], }); expect(results[2]).toBe('target=' + encodeURIComponent('asPercent(series1,sumSeries(series1))')); }); it('should fix wrong minute interval parameters', function() { - let results = ctx.ds.buildGraphiteParams({ + const results = ctx.ds.buildGraphiteParams({ targets: [{ target: "summarize(prod.25m.count, '25m', 'sum')" }], }); expect(results[0]).toBe('target=' + encodeURIComponent("summarize(prod.25m.count, '25min', 'sum')")); }); it('should fix wrong month interval parameters', function() { - let results = ctx.ds.buildGraphiteParams({ + const results = ctx.ds.buildGraphiteParams({ targets: [{ target: "summarize(prod.5M.count, '5M', 'sum')" }], }); expect(results[0]).toBe('target=' + encodeURIComponent("summarize(prod.5M.count, '5mon', 'sum')")); }); it('should ignore empty targets', function() { - let results = ctx.ds.buildGraphiteParams({ + const results = ctx.ds.buildGraphiteParams({ targets: [{ target: 'series1' }, { target: '' }], }); expect(results.length).toBe(2); @@ -308,19 +308,19 @@ describe('graphiteDatasource', () => { function accessScenario(name, url, fn) { describe('access scenario ' + name, function() { - let ctx: any = { + const ctx: any = { backendSrv: {}, $q: $q, templateSrv: new TemplateSrvStub(), instanceSettings: { url: 'url', name: 'graphiteProd', jsonData: {} }, }; - let httpOptions = { + const httpOptions = { headers: {}, }; describe('when using proxy mode', () => { - let options = { dashboardId: 1, panelId: 2 }; + const options = { dashboardId: 1, panelId: 2 }; it('tracing headers should be added', () => { ctx.instanceSettings.url = url; diff --git a/public/app/plugins/datasource/graphite/specs/graphite_query.test.ts b/public/app/plugins/datasource/graphite/specs/graphite_query.test.ts index d54caae05f8..2169db16c25 100644 --- a/public/app/plugins/datasource/graphite/specs/graphite_query.test.ts +++ b/public/app/plugins/datasource/graphite/specs/graphite_query.test.ts @@ -2,7 +2,7 @@ import gfunc from '../gfunc'; import GraphiteQuery from '../graphite_query'; describe('Graphite query model', () => { - let ctx: any = { + const ctx: any = { datasource: { getFuncDef: gfunc.getFuncDef, getFuncDefs: jest.fn().mockReturnValue(Promise.resolve(gfunc.getFuncDefs('1.0'))), diff --git a/public/app/plugins/datasource/graphite/specs/query_ctrl.test.ts b/public/app/plugins/datasource/graphite/specs/query_ctrl.test.ts index b38ad56427b..7826a458968 100644 --- a/public/app/plugins/datasource/graphite/specs/query_ctrl.test.ts +++ b/public/app/plugins/datasource/graphite/specs/query_ctrl.test.ts @@ -3,7 +3,7 @@ import gfunc from '../gfunc'; import { GraphiteQueryCtrl } from '../query_ctrl'; describe('GraphiteQueryCtrl', () => { - let ctx = { + const ctx = { datasource: { metricFindQuery: jest.fn(() => Promise.resolve([])), getFuncDefs: jest.fn(() => Promise.resolve(gfunc.getFuncDefs('1.0'))), diff --git a/public/app/plugins/datasource/influxdb/datasource.ts b/public/app/plugins/datasource/influxdb/datasource.ts index b9f2b2e03fb..8f5850fa0e8 100644 --- a/public/app/plugins/datasource/influxdb/datasource.ts +++ b/public/app/plugins/datasource/influxdb/datasource.ts @@ -147,15 +147,15 @@ export default class InfluxDatasource { } targetContainsTemplate(target) { - for (let group of target.groupBy) { - for (let param of group.params) { + for (const group of target.groupBy) { + for (const param of group.params) { if (this.templateSrv.variableExists(param)) { return true; } } } - for (let i in target.tags) { + for (const i in target.tags) { if (this.templateSrv.variableExists(target.tags[i].value)) { return true; } @@ -219,7 +219,7 @@ export default class InfluxDatasource { return this._seriesQuery(query) .then(res => { - let error = _.get(res, 'results[0].error'); + const error = _.get(res, 'results[0].error'); if (error) { return { status: 'error', message: error }; } @@ -234,7 +234,7 @@ export default class InfluxDatasource { const currentUrl = this.urls.shift(); this.urls.push(currentUrl); - let params: any = {}; + const params: any = {}; if (this.username) { params.u = this.username; @@ -252,7 +252,7 @@ export default class InfluxDatasource { data = null; } - let req: any = { + const req: any = { method: method, url: currentUrl + url, params: params, diff --git a/public/app/plugins/datasource/influxdb/influx_query.ts b/public/app/plugins/datasource/influxdb/influx_query.ts index 2ef74170068..1ad684699bf 100644 --- a/public/app/plugins/datasource/influxdb/influx_query.ts +++ b/public/app/plugins/datasource/influxdb/influx_query.ts @@ -202,10 +202,10 @@ export default class InfluxQuery { var query = 'SELECT '; var i, y; for (i = 0; i < this.selectModels.length; i++) { - let parts = this.selectModels[i]; + const parts = this.selectModels[i]; var selectText = ''; for (y = 0; y < parts.length; y++) { - let part = parts[y]; + const part = parts[y]; selectText = part.render(selectText); } diff --git a/public/app/plugins/datasource/influxdb/query_ctrl.ts b/public/app/plugins/datasource/influxdb/query_ctrl.ts index 2be1ecc7bff..1b9cd2962fc 100644 --- a/public/app/plugins/datasource/influxdb/query_ctrl.ts +++ b/public/app/plugins/datasource/influxdb/query_ctrl.ts @@ -36,7 +36,7 @@ export class InfluxQueryCtrl extends QueryCtrl { } this.tagSegments = []; - for (let tag of this.target.tags) { + for (const tag of this.target.tags) { if (!tag.operator) { if (/^\/.*\/$/.test(tag.value)) { tag.operator = '=~'; @@ -106,7 +106,7 @@ export class InfluxQueryCtrl extends QueryCtrl { if (!this.queryModel.hasGroupByTime()) { options.push(this.uiSegmentSrv.newSegment({ value: 'time($interval)' })); } - for (let tag of tags) { + for (const tag of tags) { options.push(this.uiSegmentSrv.newSegment({ value: 'tag(' + tag.text + ')' })); } return options; @@ -251,7 +251,7 @@ export class InfluxQueryCtrl extends QueryCtrl { }); if (addTemplateVars) { - for (let variable of this.templateSrv.variables) { + for (const variable of this.templateSrv.variables) { segments.unshift( this.uiSegmentSrv.newSegment({ type: 'value', diff --git a/public/app/plugins/datasource/influxdb/specs/datasource.test.ts b/public/app/plugins/datasource/influxdb/specs/datasource.test.ts index 10974cdad97..60f49bd4905 100644 --- a/public/app/plugins/datasource/influxdb/specs/datasource.test.ts +++ b/public/app/plugins/datasource/influxdb/specs/datasource.test.ts @@ -3,7 +3,7 @@ import $q from 'q'; import { TemplateSrvStub } from 'test/specs/helpers'; describe('InfluxDataSource', () => { - let ctx: any = { + const ctx: any = { backendSrv: {}, $q: $q, templateSrv: new TemplateSrvStub(), @@ -16,8 +16,8 @@ describe('InfluxDataSource', () => { }); describe('When issuing metricFindQuery', () => { - let query = 'SELECT max(value) FROM measurement WHERE $timeFilter'; - let queryOptions: any = { + const query = 'SELECT max(value) FROM measurement WHERE $timeFilter'; + const queryOptions: any = { range: { from: '2018-01-01T00:00:00Z', to: '2018-01-02T00:00:00Z', diff --git a/public/app/plugins/datasource/influxdb/specs/query_ctrl.test.ts b/public/app/plugins/datasource/influxdb/specs/query_ctrl.test.ts index 4e3fc47a5fd..88d4fb143cd 100644 --- a/public/app/plugins/datasource/influxdb/specs/query_ctrl.test.ts +++ b/public/app/plugins/datasource/influxdb/specs/query_ctrl.test.ts @@ -3,7 +3,7 @@ import { uiSegmentSrv } from 'app/core/services/segment_srv'; import { InfluxQueryCtrl } from '../query_ctrl'; describe('InfluxDBQueryCtrl', () => { - let ctx = {}; + const ctx = {}; beforeEach(() => { InfluxQueryCtrl.prototype.datasource = { diff --git a/public/app/plugins/datasource/mssql/query_ctrl.ts b/public/app/plugins/datasource/mssql/query_ctrl.ts index 884eb634f54..1b64a571c6c 100644 --- a/public/app/plugins/datasource/mssql/query_ctrl.ts +++ b/public/app/plugins/datasource/mssql/query_ctrl.ts @@ -59,7 +59,7 @@ export class MssqlQueryCtrl extends QueryCtrl { this.lastQueryMeta = null; this.lastQueryError = null; - let anySeriesFromQuery = _.find(dataList, { refId: this.target.refId }); + const anySeriesFromQuery = _.find(dataList, { refId: this.target.refId }); if (anySeriesFromQuery) { this.lastQueryMeta = anySeriesFromQuery.meta; } @@ -67,7 +67,7 @@ export class MssqlQueryCtrl extends QueryCtrl { onDataError(err) { if (err.data && err.data.results) { - let queryRes = err.data.results[this.target.refId]; + const queryRes = err.data.results[this.target.refId]; if (queryRes) { this.lastQueryMeta = queryRes.meta; this.lastQueryError = queryRes.error; diff --git a/public/app/plugins/datasource/mssql/response_parser.ts b/public/app/plugins/datasource/mssql/response_parser.ts index b6f538707b0..0044a49fd7d 100644 --- a/public/app/plugins/datasource/mssql/response_parser.ts +++ b/public/app/plugins/datasource/mssql/response_parser.ts @@ -10,11 +10,11 @@ export default class ResponseParser { return { data: data }; } - for (let key in res.data.results) { - let queryRes = res.data.results[key]; + for (const key in res.data.results) { + const queryRes = res.data.results[key]; if (queryRes.series) { - for (let series of queryRes.series) { + for (const series of queryRes.series) { data.push({ target: series.name, datapoints: series.points, @@ -25,7 +25,7 @@ export default class ResponseParser { } if (queryRes.tables) { - for (let table of queryRes.tables) { + for (const table of queryRes.tables) { table.type = 'table'; table.refId = queryRes.refId; table.meta = queryRes.meta; diff --git a/public/app/plugins/datasource/mysql/query_ctrl.ts b/public/app/plugins/datasource/mysql/query_ctrl.ts index 4961ce9e653..1de1fb768ad 100644 --- a/public/app/plugins/datasource/mysql/query_ctrl.ts +++ b/public/app/plugins/datasource/mysql/query_ctrl.ts @@ -57,7 +57,7 @@ export class MysqlQueryCtrl extends QueryCtrl { this.lastQueryMeta = null; this.lastQueryError = null; - let anySeriesFromQuery = _.find(dataList, { refId: this.target.refId }); + const anySeriesFromQuery = _.find(dataList, { refId: this.target.refId }); if (anySeriesFromQuery) { this.lastQueryMeta = anySeriesFromQuery.meta; } @@ -65,7 +65,7 @@ export class MysqlQueryCtrl extends QueryCtrl { onDataError(err) { if (err.data && err.data.results) { - let queryRes = err.data.results[this.target.refId]; + const queryRes = err.data.results[this.target.refId]; if (queryRes) { this.lastQueryMeta = queryRes.meta; this.lastQueryError = queryRes.error; diff --git a/public/app/plugins/datasource/mysql/response_parser.ts b/public/app/plugins/datasource/mysql/response_parser.ts index e5d8ab79f2a..339dc592ad2 100644 --- a/public/app/plugins/datasource/mysql/response_parser.ts +++ b/public/app/plugins/datasource/mysql/response_parser.ts @@ -10,11 +10,11 @@ export default class ResponseParser { return { data: data }; } - for (let key in res.data.results) { - let queryRes = res.data.results[key]; + for (const key in res.data.results) { + const queryRes = res.data.results[key]; if (queryRes.series) { - for (let series of queryRes.series) { + for (const series of queryRes.series) { data.push({ target: series.name, datapoints: series.points, @@ -25,7 +25,7 @@ export default class ResponseParser { } if (queryRes.tables) { - for (let table of queryRes.tables) { + for (const table of queryRes.tables) { table.type = 'table'; table.refId = queryRes.refId; table.meta = queryRes.meta; diff --git a/public/app/plugins/datasource/mysql/specs/datasource.test.ts b/public/app/plugins/datasource/mysql/specs/datasource.test.ts index 85fa2b8cc4e..e75ba5e32ee 100644 --- a/public/app/plugins/datasource/mysql/specs/datasource.test.ts +++ b/public/app/plugins/datasource/mysql/specs/datasource.test.ts @@ -3,13 +3,13 @@ import { MysqlDatasource } from '../datasource'; import { CustomVariable } from 'app/features/templating/custom_variable'; describe('MySQLDatasource', function() { - let instanceSettings = { name: 'mysql' }; - let backendSrv = {}; - let templateSrv = { + const instanceSettings = { name: 'mysql' }; + const backendSrv = {}; + const templateSrv = { replace: jest.fn(text => text), }; - let ctx = { + const ctx = { backendSrv, }; diff --git a/public/app/plugins/datasource/opentsdb/specs/datasource.test.ts b/public/app/plugins/datasource/opentsdb/specs/datasource.test.ts index 73eca7cffde..befa39fc80e 100644 --- a/public/app/plugins/datasource/opentsdb/specs/datasource.test.ts +++ b/public/app/plugins/datasource/opentsdb/specs/datasource.test.ts @@ -2,14 +2,14 @@ import OpenTsDatasource from '../datasource'; import $q from 'q'; describe('opentsdb', () => { - let ctx = { + const ctx = { backendSrv: {}, ds: {}, templateSrv: { replace: str => str, }, }; - let instanceSettings = { url: '', jsonData: { tsdbVersion: 1 } }; + const instanceSettings = { url: '', jsonData: { tsdbVersion: 1 } }; beforeEach(() => { ctx.ctrl = new OpenTsDatasource(instanceSettings, $q, ctx.backendSrv, ctx.templateSrv); diff --git a/public/app/plugins/datasource/postgres/query_ctrl.ts b/public/app/plugins/datasource/postgres/query_ctrl.ts index 7afd0cf7253..a9073de22cf 100644 --- a/public/app/plugins/datasource/postgres/query_ctrl.ts +++ b/public/app/plugins/datasource/postgres/query_ctrl.ts @@ -57,7 +57,7 @@ export class PostgresQueryCtrl extends QueryCtrl { this.lastQueryMeta = null; this.lastQueryError = null; - let anySeriesFromQuery = _.find(dataList, { refId: this.target.refId }); + const anySeriesFromQuery = _.find(dataList, { refId: this.target.refId }); if (anySeriesFromQuery) { this.lastQueryMeta = anySeriesFromQuery.meta; } @@ -65,7 +65,7 @@ export class PostgresQueryCtrl extends QueryCtrl { onDataError(err) { if (err.data && err.data.results) { - let queryRes = err.data.results[this.target.refId]; + const queryRes = err.data.results[this.target.refId]; if (queryRes) { this.lastQueryMeta = queryRes.meta; this.lastQueryError = queryRes.error; diff --git a/public/app/plugins/datasource/postgres/response_parser.ts b/public/app/plugins/datasource/postgres/response_parser.ts index ebc9598468b..e7f59e13464 100644 --- a/public/app/plugins/datasource/postgres/response_parser.ts +++ b/public/app/plugins/datasource/postgres/response_parser.ts @@ -10,11 +10,11 @@ export default class ResponseParser { return { data: data }; } - for (let key in res.data.results) { - let queryRes = res.data.results[key]; + for (const key in res.data.results) { + const queryRes = res.data.results[key]; if (queryRes.series) { - for (let series of queryRes.series) { + for (const series of queryRes.series) { data.push({ target: series.name, datapoints: series.points, @@ -25,7 +25,7 @@ export default class ResponseParser { } if (queryRes.tables) { - for (let table of queryRes.tables) { + for (const table of queryRes.tables) { table.type = 'table'; table.refId = queryRes.refId; table.meta = queryRes.meta; @@ -109,7 +109,7 @@ export default class ResponseParser { const table = data.data.results[options.annotation.name].tables[0]; let timeColumnIndex = -1; - let titleColumnIndex = -1; + const titleColumnIndex = -1; let textColumnIndex = -1; let tagsColumnIndex = -1; diff --git a/public/app/plugins/datasource/postgres/specs/datasource.test.ts b/public/app/plugins/datasource/postgres/specs/datasource.test.ts index cd6f57ee3fc..ea150750687 100644 --- a/public/app/plugins/datasource/postgres/specs/datasource.test.ts +++ b/public/app/plugins/datasource/postgres/specs/datasource.test.ts @@ -3,13 +3,13 @@ import { PostgresDatasource } from '../datasource'; import { CustomVariable } from 'app/features/templating/custom_variable'; describe('PostgreSQLDatasource', function() { - let instanceSettings = { name: 'postgresql' }; + const instanceSettings = { name: 'postgresql' }; - let backendSrv = {}; - let templateSrv = { + const backendSrv = {}; + const templateSrv = { replace: jest.fn(text => text), }; - let ctx = { + const ctx = { backendSrv, }; diff --git a/public/app/plugins/datasource/prometheus/completer.ts b/public/app/plugins/datasource/prometheus/completer.ts index 0a974378cde..396a5fc1cd7 100644 --- a/public/app/plugins/datasource/prometheus/completer.ts +++ b/public/app/plugins/datasource/prometheus/completer.ts @@ -24,12 +24,12 @@ export class PromCompleter { } getCompletions(editor, session, pos, prefix, callback) { - let wrappedCallback = (err, completions) => { + const wrappedCallback = (err, completions) => { completions = completions.concat(this.templateVariableCompletions); return callback(err, completions); }; - let token = session.getTokenAt(pos.row, pos.column); + const token = session.getTokenAt(pos.row, pos.column); switch (token.type) { case 'entity.name.tag.label-matcher': @@ -51,8 +51,8 @@ export class PromCompleter { if (token.type === 'paren.lparen' && token.value === '[') { var vectors = []; - for (let unit of ['s', 'm', 'h']) { - for (let value of [1, 5, 10, 30]) { + for (const unit of ['s', 'm', 'h']) { + for (const value of [1, 5, 10, 30]) { vectors.push({ caption: value + unit, value: '[' + value + unit, @@ -99,7 +99,7 @@ export class PromCompleter { } getCompletionsForLabelMatcherName(session, pos) { - let metricName = this.findMetricName(session, pos.row, pos.column); + const metricName = this.findMetricName(session, pos.row, pos.column); if (!metricName) { return Promise.resolve(this.transformToCompletions(['__name__', 'instance', 'job'], 'label name')); } @@ -125,7 +125,7 @@ export class PromCompleter { } getCompletionsForLabelMatcherValue(session, pos) { - let metricName = this.findMetricName(session, pos.row, pos.column); + const metricName = this.findMetricName(session, pos.row, pos.column); if (!metricName) { return Promise.resolve([]); } @@ -163,7 +163,7 @@ export class PromCompleter { } getCompletionsForBinaryOperator(session, pos) { - let keywordOperatorToken = this.findToken(session, pos.row, pos.column, 'keyword.control', null, 'identifier'); + const keywordOperatorToken = this.findToken(session, pos.row, pos.column, 'keyword.control', null, 'identifier'); if (!keywordOperatorToken) { return Promise.resolve([]); } @@ -204,7 +204,7 @@ export class PromCompleter { case 'ignoring': case 'group_left': case 'group_right': - let binaryOperatorToken = this.findToken( + const binaryOperatorToken = this.findToken( session, keywordOperatorToken.row, keywordOperatorToken.column, @@ -243,7 +243,7 @@ export class PromCompleter { return labelNames; }); } else { - let metricName = this.findMetricName(session, binaryOperatorToken.row, binaryOperatorToken.column); + const metricName = this.findMetricName(session, binaryOperatorToken.row, binaryOperatorToken.column); return this.getLabelNameAndValueForExpression(metricName, 'metricName').then(result => { var labelNames = this.transformToCompletions( _.uniq( @@ -332,7 +332,7 @@ export class PromCompleter { // current row c = 0; for (idx = 0; idx < tokens.length; idx++) { - let nc = c + tokens[idx].value.length; + const nc = c + tokens[idx].value.length; if (nc >= column) { break; } diff --git a/public/app/plugins/datasource/prometheus/datasource.ts b/public/app/plugins/datasource/prometheus/datasource.ts index ec214be8554..057bb55b3c3 100644 --- a/public/app/plugins/datasource/prometheus/datasource.ts +++ b/public/app/plugins/datasource/prometheus/datasource.ts @@ -317,7 +317,7 @@ export class PrometheusDatasource { options = _.clone(options); - for (let target of options.targets) { + for (const target of options.targets) { if (!target.expr || target.hide) { continue; } @@ -482,21 +482,21 @@ export class PrometheusDatasource { return this.$q.when([]); } - let scopedVars = { + const scopedVars = { __interval: { text: this.interval, value: this.interval }, __interval_ms: { text: kbn.interval_to_ms(this.interval), value: kbn.interval_to_ms(this.interval) }, ...this.getRangeScopedVars(), }; - let interpolated = this.templateSrv.replace(query, scopedVars, this.interpolateQueryExpr); + const interpolated = this.templateSrv.replace(query, scopedVars, this.interpolateQueryExpr); var metricFindQuery = new PrometheusMetricFindQuery(this, interpolated, this.timeSrv); return metricFindQuery.process(); } getRangeScopedVars() { - let range = this.timeSrv.timeRange(); - let msRange = range.to.diff(range.from); - let sRange = Math.round(msRange / 1000); - let regularRange = kbn.secondsToHms(msRange / 1000); + const range = this.timeSrv.timeRange(); + const msRange = range.to.diff(range.from); + const sRange = Math.round(msRange / 1000); + const regularRange = kbn.secondsToHms(msRange / 1000); return { __range_ms: { text: msRange, value: msRange }, __range_s: { text: sRange, value: sRange }, @@ -537,7 +537,7 @@ export class PrometheusDatasource { }) .value(); - for (let value of series.values) { + for (const value of series.values) { if (value[1] === '1') { var event = { annotation: annotation, @@ -557,7 +557,7 @@ export class PrometheusDatasource { } testDatasource() { - let now = new Date().getTime(); + const now = new Date().getTime(); return this.performInstantQuery({ expr: '1+1' }, now / 1000).then(response => { if (response.data.status === 'success') { return { status: 'success', message: 'Data source is working' }; diff --git a/public/app/plugins/datasource/prometheus/result_transformer.ts b/public/app/plugins/datasource/prometheus/result_transformer.ts index 7cb160e2d8c..1b1420c0b46 100644 --- a/public/app/plugins/datasource/prometheus/result_transformer.ts +++ b/public/app/plugins/datasource/prometheus/result_transformer.ts @@ -5,21 +5,21 @@ export class ResultTransformer { constructor(private templateSrv) {} transform(response: any, options: any): any[] { - let prometheusResult = response.data.data.result; + const prometheusResult = response.data.data.result; if (options.format === 'table') { return [this.transformMetricDataToTable(prometheusResult, options.responseListLength, options.refId)]; } else if (options.format === 'heatmap') { let seriesList = []; prometheusResult.sort(sortSeriesByLabel); - for (let metricData of prometheusResult) { + for (const metricData of prometheusResult) { seriesList.push(this.transformMetricData(metricData, options, options.start, options.end)); } seriesList = this.transformToHistogramOverTime(seriesList); return seriesList; } else { - let seriesList = []; - for (let metricData of prometheusResult) { + const seriesList = []; + for (const metricData of prometheusResult) { if (response.data.data.resultType === 'matrix') { seriesList.push(this.transformMetricData(metricData, options, options.start, options.end)); } else if (response.data.data.resultType === 'vector') { @@ -44,7 +44,7 @@ export class ResultTransformer { throw new Error('Prometheus heatmap error: data should be a time series'); } - for (let value of metricData.values) { + for (const value of metricData.values) { let dp_value = parseFloat(value[1]); if (_.isNaN(dp_value)) { dp_value = null; @@ -96,7 +96,7 @@ export class ResultTransformer { metricLabels[label] = labelIndex + 1; table.columns.push({ text: label, filterable: !label.startsWith('__') }); }); - let valueText = resultCount > 1 ? `Value #${refId}` : 'Value'; + const valueText = resultCount > 1 ? `Value #${refId}` : 'Value'; table.columns.push({ text: valueText }); // Populate rows, set value to empty string when label not present. @@ -175,8 +175,8 @@ export class ResultTransformer { le30 30 10 35 => 10 0 5 */ for (let i = seriesList.length - 1; i > 0; i--) { - let topSeries = seriesList[i].datapoints; - let bottomSeries = seriesList[i - 1].datapoints; + const topSeries = seriesList[i].datapoints; + const bottomSeries = seriesList[i - 1].datapoints; if (!topSeries || !bottomSeries) { throw new Error('Prometheus heatmap transform error: data should be a time series'); } diff --git a/public/app/plugins/datasource/prometheus/specs/completer.test.ts b/public/app/plugins/datasource/prometheus/specs/completer.test.ts index b29e4d27233..59fcc6592fb 100644 --- a/public/app/plugins/datasource/prometheus/specs/completer.test.ts +++ b/public/app/plugins/datasource/prometheus/specs/completer.test.ts @@ -13,10 +13,10 @@ describe('Prometheus editor completer', function() { }; } - let editor = {}; + const editor = {}; - let backendSrv = {}; - let datasourceStub = new PrometheusDatasource({}, {}, backendSrv, {}, {}); + const backendSrv = {}; + const datasourceStub = new PrometheusDatasource({}, {}, backendSrv, {}, {}); datasourceStub.performInstantQuery = jest.fn(() => Promise.resolve({ @@ -36,7 +36,7 @@ describe('Prometheus editor completer', function() { ); datasourceStub.performSuggestQuery = jest.fn(() => Promise.resolve(['node_cpu'])); - let templateSrv = { + const templateSrv = { variables: [ { name: 'var_name', @@ -44,7 +44,7 @@ describe('Prometheus editor completer', function() { }, ], }; - let completer = new PromCompleter(datasourceStub, templateSrv); + const completer = new PromCompleter(datasourceStub, templateSrv); describe('When inside brackets', () => { it('Should return range vectors', () => { diff --git a/public/app/plugins/datasource/prometheus/specs/datasource.test.ts b/public/app/plugins/datasource/prometheus/specs/datasource.test.ts index d52019ac4cc..fd963f7986e 100644 --- a/public/app/plugins/datasource/prometheus/specs/datasource.test.ts +++ b/public/app/plugins/datasource/prometheus/specs/datasource.test.ts @@ -14,8 +14,8 @@ import { jest.mock('../metric_find_query'); describe('PrometheusDatasource', () => { - let ctx: any = {}; - let instanceSettings = { + const ctx: any = {}; + const instanceSettings = { url: 'proxied', directUrl: 'direct', user: 'test', @@ -123,7 +123,7 @@ describe('PrometheusDatasource', () => { ctx.ds.performTimeSeriesQuery = jest.fn().mockReturnValue(responseMock); return ctx.ds.query(ctx.query).then(result => { - let results = result.data; + const results = result.data; return expect(results).toMatchObject(expected); }); }); @@ -153,7 +153,7 @@ describe('PrometheusDatasource', () => { ctx.ds.performTimeSeriesQuery = jest.fn().mockReturnValue(responseMock); return ctx.ds.query(ctx.query).then(result => { - let seriesLabels = _.map(result.data, 'target'); + const seriesLabels = _.map(result.data, 'target'); return expect(seriesLabels).toEqual(expected); }); }); @@ -326,7 +326,7 @@ describe('PrometheusDatasource', () => { describe('metricFindQuery', () => { beforeEach(() => { - let query = 'query_result(topk(5,rate(http_request_duration_microseconds_count[$__interval])))'; + const query = 'query_result(topk(5,rate(http_request_duration_microseconds_count[$__interval])))'; ctx.templateSrvMock.replace = jest.fn(); ctx.timeSrvMock.timeRange = () => { return { @@ -343,17 +343,17 @@ describe('PrometheusDatasource', () => { }); it('should have the correct range and range_ms', () => { - let range = ctx.templateSrvMock.replace.mock.calls[0][1].__range; - let rangeMs = ctx.templateSrvMock.replace.mock.calls[0][1].__range_ms; - let rangeS = ctx.templateSrvMock.replace.mock.calls[0][1].__range_s; + const range = ctx.templateSrvMock.replace.mock.calls[0][1].__range; + const rangeMs = ctx.templateSrvMock.replace.mock.calls[0][1].__range_ms; + const rangeS = ctx.templateSrvMock.replace.mock.calls[0][1].__range_s; expect(range).toEqual({ text: '21s', value: '21s' }); expect(rangeMs).toEqual({ text: 21031, value: 21031 }); expect(rangeS).toEqual({ text: 21, value: 21 }); }); it('should pass the default interval value', () => { - let interval = ctx.templateSrvMock.replace.mock.calls[0][1].__interval; - let intervalMs = ctx.templateSrvMock.replace.mock.calls[0][1].__interval_ms; + const interval = ctx.templateSrvMock.replace.mock.calls[0][1].__interval; + const intervalMs = ctx.templateSrvMock.replace.mock.calls[0][1].__interval_ms; expect(interval).toEqual({ text: '15s', value: '15s' }); expect(intervalMs).toEqual({ text: 15000, value: 15000 }); }); @@ -385,23 +385,23 @@ const HOUR = 60 * MINUTE; const time = ({ hours = 0, seconds = 0, minutes = 0 }) => moment(hours * HOUR + minutes * MINUTE + seconds * SECOND); -let ctx = {}; -let instanceSettings = { +const ctx = {}; +const instanceSettings = { url: 'proxied', directUrl: 'direct', user: 'test', password: 'mupp', jsonData: { httpMethod: 'GET' }, }; -let backendSrv = { +const backendSrv = { datasourceRequest: jest.fn(), }; -let templateSrv = { +const templateSrv = { replace: jest.fn(str => str), }; -let timeSrv = { +const timeSrv = { timeRange: () => { return { to: { diff: () => 2000 }, from: '' }; }, @@ -420,7 +420,7 @@ describe('PrometheusDatasource', () => { 'proxied/api/v1/query_range?query=' + encodeURIComponent('test{job="testjob"}') + '&start=60&end=240&step=60'; beforeEach(async () => { - let response = { + const response = { data: { status: 'success', data: { @@ -443,7 +443,7 @@ describe('PrometheusDatasource', () => { }); it('should generate the correct query', () => { - let res = backendSrv.datasourceRequest.mock.calls[0][0]; + const res = backendSrv.datasourceRequest.mock.calls[0][0]; expect(res.method).toBe('GET'); expect(res.url).toBe(urlExpected); }); @@ -465,7 +465,7 @@ describe('PrometheusDatasource', () => { }; beforeEach(async () => { - let response = { + const response = { status: 'success', data: { data: { @@ -530,7 +530,7 @@ describe('PrometheusDatasource', () => { }; beforeEach(async () => { - let response = { + const response = { status: 'success', data: { data: { @@ -553,7 +553,7 @@ describe('PrometheusDatasource', () => { }); }); it('should generate the correct query', () => { - let res = backendSrv.datasourceRequest.mock.calls[0][0]; + const res = backendSrv.datasourceRequest.mock.calls[0][0]; expect(res.method).toBe('GET'); expect(res.url).toBe(urlExpected); }); @@ -579,7 +579,7 @@ describe('PrometheusDatasource', () => { }; beforeEach(async () => { - let response = { + const response = { status: 'success', data: { data: { @@ -625,7 +625,7 @@ describe('PrometheusDatasource', () => { }; beforeEach(async () => { - let response = { + const response = { status: 'success', data: { data: { @@ -664,7 +664,7 @@ describe('PrometheusDatasource', () => { }; it('should be min interval when greater than auto interval', async () => { - let query = { + const query = { // 6 minute range range: { from: time({ minutes: 1 }), to: time({ minutes: 7 }) }, targets: [ @@ -675,12 +675,12 @@ describe('PrometheusDatasource', () => { ], interval: '5s', }; - let urlExpected = 'proxied/api/v1/query_range?query=test&start=60&end=420&step=10'; + const urlExpected = 'proxied/api/v1/query_range?query=test&start=60&end=420&step=10'; backendSrv.datasourceRequest = jest.fn(() => Promise.resolve(response)); ctx.ds = new PrometheusDatasource(instanceSettings, q, backendSrv, templateSrv, timeSrv); await ctx.ds.query(query); - let res = backendSrv.datasourceRequest.mock.calls[0][0]; + const res = backendSrv.datasourceRequest.mock.calls[0][0]; expect(res.method).toBe('GET'); expect(res.url).toBe(urlExpected); }); @@ -696,7 +696,7 @@ describe('PrometheusDatasource', () => { backendSrv.datasourceRequest = jest.fn(() => Promise.resolve(response)); ctx.ds = new PrometheusDatasource(instanceSettings, q, backendSrv, templateSrv, timeSrv); await ctx.ds.query(query); - let res = backendSrv.datasourceRequest.mock.calls[0][0]; + const res = backendSrv.datasourceRequest.mock.calls[0][0]; expect(res.method).toBe('GET'); expect(res.url).toBe(urlExpected); }); @@ -717,7 +717,7 @@ describe('PrometheusDatasource', () => { backendSrv.datasourceRequest = jest.fn(() => Promise.resolve(response)); ctx.ds = new PrometheusDatasource(instanceSettings, q, backendSrv, templateSrv, timeSrv); await ctx.ds.query(query); - let res = backendSrv.datasourceRequest.mock.calls[0][0]; + const res = backendSrv.datasourceRequest.mock.calls[0][0]; expect(res.method).toBe('GET'); expect(res.url).toBe(urlExpected); }); @@ -734,7 +734,7 @@ describe('PrometheusDatasource', () => { backendSrv.datasourceRequest = jest.fn(() => Promise.resolve(response)); ctx.ds = new PrometheusDatasource(instanceSettings, q, backendSrv, templateSrv, timeSrv); await ctx.ds.query(query); - let res = backendSrv.datasourceRequest.mock.calls[0][0]; + const res = backendSrv.datasourceRequest.mock.calls[0][0]; expect(res.method).toBe('GET'); expect(res.url).toBe(urlExpected); }); @@ -756,7 +756,7 @@ describe('PrometheusDatasource', () => { backendSrv.datasourceRequest = jest.fn(() => Promise.resolve(response)); ctx.ds = new PrometheusDatasource(instanceSettings, q, backendSrv, templateSrv, timeSrv); await ctx.ds.query(query); - let res = backendSrv.datasourceRequest.mock.calls[0][0]; + const res = backendSrv.datasourceRequest.mock.calls[0][0]; expect(res.method).toBe('GET'); expect(res.url).toBe(urlExpected); }); @@ -777,7 +777,7 @@ describe('PrometheusDatasource', () => { backendSrv.datasourceRequest = jest.fn(() => Promise.resolve(response)); ctx.ds = new PrometheusDatasource(instanceSettings, q, backendSrv, templateSrv, timeSrv); await ctx.ds.query(query); - let res = backendSrv.datasourceRequest.mock.calls[0][0]; + const res = backendSrv.datasourceRequest.mock.calls[0][0]; expect(res.method).toBe('GET'); expect(res.url).toBe(urlExpected); }); @@ -799,7 +799,7 @@ describe('PrometheusDatasource', () => { backendSrv.datasourceRequest = jest.fn(() => Promise.resolve(response)); ctx.ds = new PrometheusDatasource(instanceSettings, q, backendSrv, templateSrv, timeSrv); await ctx.ds.query(query); - let res = backendSrv.datasourceRequest.mock.calls[0][0]; + const res = backendSrv.datasourceRequest.mock.calls[0][0]; expect(res.method).toBe('GET'); expect(res.url).toBe(urlExpected); }); @@ -821,7 +821,7 @@ describe('PrometheusDatasource', () => { backendSrv.datasourceRequest = jest.fn(() => Promise.resolve(response)); ctx.ds = new PrometheusDatasource(instanceSettings, q, backendSrv, templateSrv, timeSrv); await ctx.ds.query(query); - let res = backendSrv.datasourceRequest.mock.calls[0][0]; + const res = backendSrv.datasourceRequest.mock.calls[0][0]; expect(res.method).toBe('GET'); expect(res.url).toBe(urlExpected); }); @@ -843,7 +843,7 @@ describe('PrometheusDatasource', () => { backendSrv.datasourceRequest = jest.fn(() => Promise.resolve(response)); ctx.ds = new PrometheusDatasource(instanceSettings, q, backendSrv, templateSrv, timeSrv); await ctx.ds.query(query); - let res = backendSrv.datasourceRequest.mock.calls[0][0]; + const res = backendSrv.datasourceRequest.mock.calls[0][0]; expect(res.method).toBe('GET'); expect(res.url).toBe(urlExpected); }); @@ -886,7 +886,7 @@ describe('PrometheusDatasource', () => { backendSrv.datasourceRequest = jest.fn(() => Promise.resolve(response)); ctx.ds = new PrometheusDatasource(instanceSettings, q, backendSrv, templateSrv, timeSrv); await ctx.ds.query(query); - let res = backendSrv.datasourceRequest.mock.calls[0][0]; + const res = backendSrv.datasourceRequest.mock.calls[0][0]; expect(res.method).toBe('GET'); expect(res.url).toBe(urlExpected); @@ -925,7 +925,7 @@ describe('PrometheusDatasource', () => { templateSrv.replace = jest.fn(str => str); ctx.ds = new PrometheusDatasource(instanceSettings, q, backendSrv, templateSrv, timeSrv); await ctx.ds.query(query); - let res = backendSrv.datasourceRequest.mock.calls[0][0]; + const res = backendSrv.datasourceRequest.mock.calls[0][0]; expect(res.method).toBe('GET'); expect(res.url).toBe(urlExpected); @@ -965,7 +965,7 @@ describe('PrometheusDatasource', () => { templateSrv.replace = jest.fn(str => str); ctx.ds = new PrometheusDatasource(instanceSettings, q, backendSrv, templateSrv, timeSrv); await ctx.ds.query(query); - let res = backendSrv.datasourceRequest.mock.calls[0][0]; + const res = backendSrv.datasourceRequest.mock.calls[0][0]; expect(res.method).toBe('GET'); expect(res.url).toBe(urlExpected); @@ -1011,7 +1011,7 @@ describe('PrometheusDatasource', () => { backendSrv.datasourceRequest = jest.fn(() => Promise.resolve(response)); ctx.ds = new PrometheusDatasource(instanceSettings, q, backendSrv, templateSrv, timeSrv); await ctx.ds.query(query); - let res = backendSrv.datasourceRequest.mock.calls[0][0]; + const res = backendSrv.datasourceRequest.mock.calls[0][0]; expect(res.method).toBe('GET'); expect(res.url).toBe(urlExpected); @@ -1051,7 +1051,7 @@ describe('PrometheusDatasource', () => { backendSrv.datasourceRequest = jest.fn(() => Promise.resolve(response)); ctx.ds = new PrometheusDatasource(instanceSettings, q, backendSrv, templateSrv, timeSrv); await ctx.ds.query(query); - let res = backendSrv.datasourceRequest.mock.calls[0][0]; + const res = backendSrv.datasourceRequest.mock.calls[0][0]; expect(res.method).toBe('GET'); expect(res.url).toBe(urlExpected); @@ -1096,7 +1096,7 @@ describe('PrometheusDatasource', () => { templateSrv.replace = jest.fn(str => str); ctx.ds = new PrometheusDatasource(instanceSettings, q, backendSrv, templateSrv, timeSrv); await ctx.ds.query(query); - let res = backendSrv.datasourceRequest.mock.calls[0][0]; + const res = backendSrv.datasourceRequest.mock.calls[0][0]; expect(res.method).toBe('GET'); expect(res.url).toBe(urlExpected); @@ -1116,7 +1116,7 @@ describe('PrometheusDatasource', () => { describe('PrometheusDatasource for POST', () => { // var ctx = new helpers.ServiceTestContext(); - let instanceSettings = { + const instanceSettings = { url: 'proxied', directUrl: 'direct', user: 'test', @@ -1140,7 +1140,7 @@ describe('PrometheusDatasource for POST', () => { }; beforeEach(async () => { - let response = { + const response = { status: 'success', data: { data: { @@ -1161,7 +1161,7 @@ describe('PrometheusDatasource for POST', () => { }); }); it('should generate the correct query', () => { - let res = backendSrv.datasourceRequest.mock.calls[0][0]; + const res = backendSrv.datasourceRequest.mock.calls[0][0]; expect(res.method).toBe('POST'); expect(res.url).toBe(urlExpected); expect(res.data).toEqual(dataExpected); diff --git a/public/app/plugins/datasource/prometheus/specs/metric_find_query.test.ts b/public/app/plugins/datasource/prometheus/specs/metric_find_query.test.ts index 88f6830cd31..bfbf241ba06 100644 --- a/public/app/plugins/datasource/prometheus/specs/metric_find_query.test.ts +++ b/public/app/plugins/datasource/prometheus/specs/metric_find_query.test.ts @@ -4,7 +4,7 @@ import PrometheusMetricFindQuery from '../metric_find_query'; import q from 'q'; describe('PrometheusMetricFindQuery', function() { - let instanceSettings = { + const instanceSettings = { url: 'proxied', directUrl: 'direct', user: 'test', @@ -15,7 +15,7 @@ describe('PrometheusMetricFindQuery', function() { from: moment.utc('2018-04-25 10:00'), to: moment.utc('2018-04-25 11:00'), }; - let ctx: any = { + const ctx: any = { backendSrvMock: { datasourceRequest: jest.fn(() => Promise.resolve({})), }, diff --git a/public/app/plugins/datasource/prometheus/specs/result_transformer.test.ts b/public/app/plugins/datasource/prometheus/specs/result_transformer.test.ts index 68224121414..ac85e1374bb 100644 --- a/public/app/plugins/datasource/prometheus/specs/result_transformer.test.ts +++ b/public/app/plugins/datasource/prometheus/specs/result_transformer.test.ts @@ -1,7 +1,7 @@ import { ResultTransformer } from '../result_transformer'; describe('Prometheus Result Transformer', () => { - let ctx: any = {}; + const ctx: any = {}; beforeEach(() => { ctx.templateSrv = { @@ -111,7 +111,7 @@ describe('Prometheus Result Transformer', () => { }; it('should convert cumulative histogram to regular', () => { - let options = { + const options = { format: 'heatmap', start: 1445000010, end: 1445000030, @@ -171,7 +171,7 @@ describe('Prometheus Result Transformer', () => { ], }, }; - let options = { + const options = { format: 'timeseries', start: 0, end: 2, @@ -194,7 +194,7 @@ describe('Prometheus Result Transformer', () => { ], }, }; - let options = { + const options = { format: 'timeseries', step: 1, start: 0, @@ -218,7 +218,7 @@ describe('Prometheus Result Transformer', () => { ], }, }; - let options = { + const options = { format: 'timeseries', step: 2, start: 0, diff --git a/public/app/plugins/datasource/testdata/datasource.ts b/public/app/plugins/datasource/testdata/datasource.ts index 327abb1d70b..3f4035830ed 100644 --- a/public/app/plugins/datasource/testdata/datasource.ts +++ b/public/app/plugins/datasource/testdata/datasource.ts @@ -39,7 +39,7 @@ class TestDataDatasource { if (res.results) { _.forEach(res.results, queryRes => { - for (let series of queryRes.series) { + for (const series of queryRes.series) { data.push({ target: series.name, datapoints: series.points, diff --git a/public/app/plugins/panel/alertlist/module.ts b/public/app/plugins/panel/alertlist/module.ts index 55869ce626d..b171f590e94 100644 --- a/public/app/plugins/panel/alertlist/module.ts +++ b/public/app/plugins/panel/alertlist/module.ts @@ -42,7 +42,7 @@ class AlertListPanel extends PanelCtrl { this.events.on('init-edit-mode', this.onInitEditMode.bind(this)); this.events.on('refresh', this.onRefresh.bind(this)); - for (let key in this.panel.stateFilter) { + for (const key in this.panel.stateFilter) { this.stateFilter[this.panel.stateFilter[key]] = true; } } @@ -67,7 +67,7 @@ class AlertListPanel extends PanelCtrl { updateStateFilter() { var result = []; - for (let key in this.stateFilter) { + for (const key in this.stateFilter) { if (this.stateFilter[key]) { result.push(key); } diff --git a/public/app/plugins/panel/graph/data_processor.ts b/public/app/plugins/panel/graph/data_processor.ts index f8162c57a10..0e75399445d 100644 --- a/public/app/plugins/panel/graph/data_processor.ts +++ b/public/app/plugins/panel/graph/data_processor.ts @@ -14,7 +14,7 @@ export class DataProcessor { var firstItem; if (options.dataList && options.dataList.length > 0) { firstItem = options.dataList[0]; - let autoDetectMode = this.getAutoDetectXAxisMode(firstItem); + const autoDetectMode = this.getAutoDetectXAxisMode(firstItem); if (this.panel.xaxis.mode !== autoDetectMode) { this.panel.xaxis.mode = autoDetectMode; this.setPanelDefaultsForNewXAxisMode(); @@ -127,7 +127,7 @@ export class DataProcessor { } customHandler(dataItem) { - let nameField = this.panel.xaxis.name; + const nameField = this.panel.xaxis.name; if (!nameField) { throw { message: 'No field name specified to use for x-axis, check your axes settings', @@ -159,9 +159,9 @@ export class DataProcessor { return []; } - let fields = []; + const fields = []; var firstItem = dataList[0]; - let fieldParts = []; + const fieldParts = []; function getPropertiesRecursive(obj) { _.forEach(obj, (value, key) => { @@ -170,7 +170,7 @@ export class DataProcessor { getPropertiesRecursive(value); } else { if (!onlyNumbers || _.isNumber(value)) { - let field = fieldParts.concat(key).join('.'); + const field = fieldParts.concat(key).join('.'); fields.push(field); } } @@ -205,7 +205,7 @@ export class DataProcessor { } pluckDeep(obj: any, property: string) { - let propertyParts = property.split('.'); + const propertyParts = property.split('.'); let value = obj; for (let i = 0; i < propertyParts.length; ++i) { if (value[propertyParts[i]]) { diff --git a/public/app/plugins/panel/graph/graph.ts b/public/app/plugins/panel/graph/graph.ts index 35886aa5bf7..bfbbc855f20 100755 --- a/public/app/plugins/panel/graph/graph.ts +++ b/public/app/plugins/panel/graph/graph.ts @@ -148,7 +148,7 @@ class GraphElement { if ((pos.ctrlKey || pos.metaKey) && (this.dashboard.meta.canEdit || this.dashboard.meta.canMakeEditable)) { // Skip if range selected (added in "plotselected" event handler) - let isRangeSelection = pos.x !== pos.x1; + const isRangeSelection = pos.x !== pos.x1; if (!isRangeSelection) { setTimeout(() => { this.eventManager.updateTime({ from: pos.x, to: null }); @@ -269,7 +269,7 @@ class GraphElement { this.panel.dashes = this.panel.lines ? this.panel.dashes : false; // Populate element - let options: any = this.buildFlotOptions(this.panel); + const options: any = this.buildFlotOptions(this.panel); this.prepareXAxis(options, this.panel); this.configureYAxisOptions(this.data, options); this.thresholdManager.addFlotOptions(options, this.panel); @@ -281,7 +281,7 @@ class GraphElement { buildFlotPairs(data) { for (let i = 0; i < data.length; i++) { - let series = data[i]; + const series = data[i]; series.data = series.getFlotPairs(series.nullPointMode || this.panel.nullPointMode); // if hidden remove points and disable stack @@ -299,7 +299,7 @@ class GraphElement { options.series.bars.align = 'center'; for (let i = 0; i < this.data.length; i++) { - let series = this.data[i]; + const series = this.data[i]; series.data = [[i + 1, series.stats[panel.xaxis.values[0]]]]; } @@ -310,9 +310,9 @@ class GraphElement { let bucketSize: number; if (this.data.length) { - let histMin = _.min(_.map(this.data, s => s.stats.min)); - let histMax = _.max(_.map(this.data, s => s.stats.max)); - let ticks = panel.xaxis.buckets || this.panelWidth / 50; + const histMin = _.min(_.map(this.data, s => s.stats.min)); + const histMax = _.max(_.map(this.data, s => s.stats.max)); + const ticks = panel.xaxis.buckets || this.panelWidth / 50; bucketSize = tickStep(histMin, histMax, ticks); options.series.bars.barWidth = bucketSize * 0.8; this.data = convertToHistogramData(this.data, bucketSize, this.ctrl.hiddenSeries, histMin, histMax); @@ -362,7 +362,7 @@ class GraphElement { gridColor = '#a1a1a1'; } const stack = panel.stack ? true : null; - let options = { + const options = { hooks: { draw: [this.drawHook.bind(this)], processOffset: [this.processOffsetHook.bind(this)], @@ -481,12 +481,12 @@ class GraphElement { addXHistogramAxis(options, bucketSize) { let ticks, min, max; - let defaultTicks = this.panelWidth / 50; + const defaultTicks = this.panelWidth / 50; if (this.data.length && bucketSize) { - let tick_values = []; - for (let d of this.data) { - for (let point of d.data) { + const tick_values = []; + for (const d of this.data) { + for (const point of d.data) { tick_values[point[0]] = true; } } diff --git a/public/app/plugins/panel/graph/graph_tooltip.ts b/public/app/plugins/panel/graph/graph_tooltip.ts index 7bbafc453eb..da2d25b1366 100644 --- a/public/app/plugins/panel/graph/graph_tooltip.ts +++ b/public/app/plugins/panel/graph/graph_tooltip.ts @@ -2,20 +2,20 @@ import $ from 'jquery'; import { appEvents } from 'app/core/core'; export default function GraphTooltip(elem, dashboard, scope, getSeriesFn) { - let self = this; - let ctrl = scope.ctrl; - let panel = ctrl.panel; + const self = this; + const ctrl = scope.ctrl; + const panel = ctrl.panel; - let $tooltip = $('
    '); + const $tooltip = $('
    '); this.destroy = function() { $tooltip.remove(); }; this.findHoverIndexFromDataPoints = function(posX, series, last) { - let ps = series.datapoints.pointsize; - let initial = last * ps; - let len = series.datapoints.points.length; + const ps = series.datapoints.pointsize; + const initial = last * ps; + const len = series.datapoints.points.length; let j; for (j = initial; j < len; j += ps) { // Special case of a non stepped line, highlight the very last point just before a null point @@ -149,7 +149,7 @@ export default function GraphTooltip(elem, dashboard, scope, getSeriesFn) { elem.mouseleave(function() { if (panel.tooltip.shared) { - let plot = elem.data().plot; + const plot = elem.data().plot; if (plot) { $tooltip.detach(); plot.unhighlight(); @@ -177,25 +177,25 @@ export default function GraphTooltip(elem, dashboard, scope, getSeriesFn) { }; this.show = function(pos, item) { - let plot = elem.data().plot; - let plotData = plot.getData(); - let xAxes = plot.getXAxes(); - let xMode = xAxes[0].options.mode; - let seriesList = getSeriesFn(); + const plot = elem.data().plot; + const plotData = plot.getData(); + const xAxes = plot.getXAxes(); + const xMode = xAxes[0].options.mode; + const seriesList = getSeriesFn(); let allSeriesMode = panel.tooltip.shared; let group, value, absoluteTime, hoverInfo, i, series, seriesHtml, tooltipFormat; // if panelRelY is defined another panel wants us to show a tooltip // get pageX from position on x axis and pageY from relative position in original panel if (pos.panelRelY) { - let pointOffset = plot.pointOffset({ x: pos.x }); + const pointOffset = plot.pointOffset({ x: pos.x }); if (Number.isNaN(pointOffset.left) || pointOffset.left < 0 || pointOffset.left > elem.width()) { self.clear(plot); return; } pos.pageX = elem.offset().left + pointOffset.left; pos.pageY = elem.offset().top + elem.height() * pos.panelRelY; - let isVisible = + const isVisible = pos.pageY >= $(window).scrollTop() && pos.pageY <= $(window).innerHeight() + $(window).scrollTop(); if (!isVisible) { self.clear(plot); @@ -223,7 +223,7 @@ export default function GraphTooltip(elem, dashboard, scope, getSeriesFn) { if (allSeriesMode) { plot.unhighlight(); - let seriesHoverInfo = self.getMultiSeriesPlotHoverInfo(plotData, pos); + const seriesHoverInfo = self.getMultiSeriesPlotHoverInfo(plotData, pos); seriesHtml = ''; diff --git a/public/app/plugins/panel/graph/histogram.ts b/public/app/plugins/panel/graph/histogram.ts index ad56e477a85..f8819041cba 100644 --- a/public/app/plugins/panel/graph/histogram.ts +++ b/public/app/plugins/panel/graph/histogram.ts @@ -7,12 +7,12 @@ import TimeSeries from 'app/core/time_series2'; */ export function getSeriesValues(dataList: TimeSeries[]): number[] { const VALUE_INDEX = 0; - let values = []; + const values = []; // Count histogam stats for (let i = 0; i < dataList.length; i++) { - let series = dataList[i]; - let datapoints = series.datapoints; + const series = dataList[i]; + const datapoints = series.datapoints; for (let j = 0; j < datapoints.length; j++) { if (datapoints[j][VALUE_INDEX] !== null) { values.push(datapoints[j][VALUE_INDEX]); @@ -30,10 +30,10 @@ export function getSeriesValues(dataList: TimeSeries[]): number[] { * @param bucketSize */ export function convertValuesToHistogram(values: number[], bucketSize: number, min: number, max: number): any[] { - let histogram = {}; + const histogram = {}; - let minBound = getBucketBound(min, bucketSize); - let maxBound = getBucketBound(max, bucketSize); + const minBound = getBucketBound(min, bucketSize); + const maxBound = getBucketBound(max, bucketSize); let bound = minBound; let n = 0; while (bound <= maxBound) { @@ -43,11 +43,11 @@ export function convertValuesToHistogram(values: number[], bucketSize: number, m } for (let i = 0; i < values.length; i++) { - let bound = getBucketBound(values[i], bucketSize); + const bound = getBucketBound(values[i], bucketSize); histogram[bound] = histogram[bound] + 1; } - let histogam_series = _.map(histogram, (count, bound) => { + const histogam_series = _.map(histogram, (count, bound) => { return [Number(bound), count]; }); @@ -68,10 +68,10 @@ export function convertToHistogramData( max: number ): any[] { return data.map(series => { - let values = getSeriesValues([series]); + const values = getSeriesValues([series]); series.histogram = true; if (!hiddenSeries[series.alias]) { - let histogram = convertValuesToHistogram(values, bucketSize, min, max); + const histogram = convertValuesToHistogram(values, bucketSize, min, max); series.data = histogram; } else { series.data = []; diff --git a/public/app/plugins/panel/graph/jquery.flot.events.ts b/public/app/plugins/panel/graph/jquery.flot.events.ts index 9dfe0a8573f..2f05a76d02b 100644 --- a/public/app/plugins/panel/graph/jquery.flot.events.ts +++ b/public/app/plugins/panel/graph/jquery.flot.events.ts @@ -5,16 +5,16 @@ import Drop from 'tether-drop'; /** @ngInject */ export function createAnnotationToolip(element, event, plot) { - let injector = angular.element(document).injector(); - let content = document.createElement('div'); + const injector = angular.element(document).injector(); + const content = document.createElement('div'); content.innerHTML = ''; injector.invoke([ '$compile', '$rootScope', function($compile, $rootScope) { - let eventManager = plot.getOptions().events.manager; - let tmpScope = $rootScope.$new(true); + const eventManager = plot.getOptions().events.manager; + const tmpScope = $rootScope.$new(true); tmpScope.event = event; tmpScope.onEdit = function() { eventManager.editEvent(event); @@ -24,7 +24,7 @@ export function createAnnotationToolip(element, event, plot) { tmpScope.$digest(); tmpScope.$destroy(); - let drop = new Drop({ + const drop = new Drop({ target: element[0], content: content, position: 'bottom center', @@ -51,7 +51,7 @@ let markerElementToAttachTo = null; /** @ngInject */ export function createEditPopover(element, event, plot) { - let eventManager = plot.getOptions().events.manager; + const eventManager = plot.getOptions().events.manager; if (eventManager.editorOpen) { // update marker element to attach to (needed in case of legend on the right // when there is a double render pass and the inital marker element is removed) @@ -66,15 +66,15 @@ export function createEditPopover(element, event, plot) { // wait for element to be attached and positioned setTimeout(function() { - let injector = angular.element(document).injector(); - let content = document.createElement('div'); + const injector = angular.element(document).injector(); + const content = document.createElement('div'); content.innerHTML = ''; injector.invoke([ '$compile', '$rootScope', function($compile, $rootScope) { - let scope = $rootScope.$new(true); + const scope = $rootScope.$new(true); let drop; scope.event = event; @@ -240,22 +240,22 @@ export class EventMarkers { * create internal objects for the given events */ setupEvents(events) { - let parts = _.partition(events, 'isRegion'); - let regions = parts[0]; + const parts = _.partition(events, 'isRegion'); + const regions = parts[0]; events = parts[1]; $.each(events, (index, event) => { - let ve = new VisualEvent(event, this._buildDiv(event)); + const ve = new VisualEvent(event, this._buildDiv(event)); this._events.push(ve); }); $.each(regions, (index, event) => { - let vre = new VisualEvent(event, this._buildRegDiv(event)); + const vre = new VisualEvent(event, this._buildRegDiv(event)); this._events.push(vre); }); this._events.sort((a, b) => { - let ao = a.getOptions(), + const ao = a.getOptions(), bo = b.getOptions(); if (ao.min > bo.min) { return 1; @@ -293,7 +293,7 @@ export class EventMarkers { let o = this._plot.getPlotOffset(), left, top; - let xaxis = this._plot.getXAxes()[this._plot.getOptions().events.xaxis - 1]; + const xaxis = this._plot.getXAxes()[this._plot.getOptions().events.xaxis - 1]; $.each(this._events, (index, event) => { top = o.top + this._plot.height() - event.visual().height(); @@ -316,16 +316,16 @@ export class EventMarkers { * create a DOM element for the given event */ _buildDiv(event) { - let that = this; + const that = this; - let container = this._plot.getPlaceholder(); - let o = this._plot.getPlotOffset(); - let xaxis = this._plot.getXAxes()[this._plot.getOptions().events.xaxis - 1]; + const container = this._plot.getPlaceholder(); + const o = this._plot.getPlotOffset(); + const xaxis = this._plot.getXAxes()[this._plot.getOptions().events.xaxis - 1]; let top, left, color, markerSize, markerShow, lineStyle, lineWidth; let markerTooltip; // map the eventType to a types object - let eventTypeId = event.eventType; + const eventTypeId = event.eventType; if (this._types === null || !this._types[eventTypeId] || !this._types[eventTypeId].color) { color = '#666'; @@ -369,7 +369,7 @@ export class EventMarkers { top = o.top + this._plot.height() + topOffset; left = xaxis.p2c(event.min) + o.left; - let line = $('
    ') + const line = $('
    ') .css({ position: 'absolute', opacity: 0.8, @@ -385,7 +385,7 @@ export class EventMarkers { .appendTo(container); if (markerShow) { - let marker = $('
    ').css({ + const marker = $('
    ').css({ position: 'absolute', left: -markerSize - Math.round(lineWidth / 2) + 'px', 'font-size': 0, @@ -420,7 +420,7 @@ export class EventMarkers { event: event, }); - let mouseenter = function() { + const mouseenter = function() { createAnnotationToolip(marker, $(this).data('event'), that._plot); }; @@ -428,7 +428,7 @@ export class EventMarkers { createEditPopover(marker, event.editModel, that._plot); } - let mouseleave = function() { + const mouseleave = function() { that._plot.clearSelection(); }; @@ -438,7 +438,7 @@ export class EventMarkers { } } - let drawableEvent = new DrawableEvent( + const drawableEvent = new DrawableEvent( line, function drawFunc(obj) { obj.show(); @@ -465,15 +465,15 @@ export class EventMarkers { * create a DOM element for the given region */ _buildRegDiv(event) { - let that = this; + const that = this; - let container = this._plot.getPlaceholder(); - let o = this._plot.getPlotOffset(); - let xaxis = this._plot.getXAxes()[this._plot.getOptions().events.xaxis - 1]; + const container = this._plot.getPlaceholder(); + const o = this._plot.getPlotOffset(); + const xaxis = this._plot.getXAxes()[this._plot.getOptions().events.xaxis - 1]; let top, left, lineWidth, regionWidth, lineStyle, color, markerTooltip; // map the eventType to a types object - let eventTypeId = event.eventType; + const eventTypeId = event.eventType; if (this._types === null || !this._types[eventTypeId] || !this._types[eventTypeId].color) { color = '#666'; @@ -499,17 +499,17 @@ export class EventMarkers { lineStyle = this._types[eventTypeId].lineStyle.toLowerCase(); } - let topOffset = 2; + const topOffset = 2; top = o.top + this._plot.height() + topOffset; - let timeFrom = Math.min(event.min, event.timeEnd); - let timeTo = Math.max(event.min, event.timeEnd); + const timeFrom = Math.min(event.min, event.timeEnd); + const timeTo = Math.max(event.min, event.timeEnd); left = xaxis.p2c(timeFrom) + o.left; - let right = xaxis.p2c(timeTo) + o.left; + const right = xaxis.p2c(timeTo) + o.left; regionWidth = right - left; _.each([left, right], position => { - let line = $('
    ').css({ + const line = $('
    ').css({ position: 'absolute', opacity: 0.8, left: position + 'px', @@ -524,7 +524,7 @@ export class EventMarkers { line.appendTo(container); }); - let region = $('
    ').css({ + const region = $('
    ').css({ position: 'absolute', opacity: 0.5, left: left + 'px', @@ -541,7 +541,7 @@ export class EventMarkers { event: event, }); - let mouseenter = function() { + const mouseenter = function() { createAnnotationToolip(region, $(this).data('event'), that._plot); }; @@ -549,7 +549,7 @@ export class EventMarkers { createEditPopover(region, event.editModel, that._plot); } - let mouseleave = function() { + const mouseleave = function() { that._plot.clearSelection(); }; @@ -558,7 +558,7 @@ export class EventMarkers { region.hover(mouseenter, mouseleave); } - let drawableEvent = new DrawableEvent( + const drawableEvent = new DrawableEvent( region, function drawFunc(obj) { obj.show(); @@ -585,8 +585,8 @@ export class EventMarkers { * check if the event is inside visible range */ _insidePlot(x) { - let xaxis = this._plot.getXAxes()[this._plot.getOptions().events.xaxis - 1]; - let xc = xaxis.p2c(x); + const xaxis = this._plot.getXAxes()[this._plot.getOptions().events.xaxis - 1]; + const xc = xaxis.p2c(x); return xc > 0 && xc < xaxis.p2c(xaxis.max); } } @@ -598,8 +598,8 @@ export class EventMarkers { /** @ngInject */ export function init(plot) { /*jshint validthis:true */ - let that = this; - let eventMarkers = new EventMarkers(plot); + const that = this; + const eventMarkers = new EventMarkers(plot); plot.getEvents = function() { return eventMarkers._events; @@ -638,7 +638,7 @@ export function init(plot) { }); plot.hooks.draw.push(function(plot) { - let options = plot.getOptions(); + const options = plot.getOptions(); if (eventMarkers.eventsEnabled) { // check for first run @@ -654,7 +654,7 @@ export function init(plot) { }); } -let defaultOptions = { +const defaultOptions = { events: { data: null, types: null, diff --git a/public/app/plugins/panel/graph/legend.ts b/public/app/plugins/panel/graph/legend.ts index f5c35ad98bf..f735fe28b22 100644 --- a/public/app/plugins/panel/graph/legend.ts +++ b/public/app/plugins/panel/graph/legend.ts @@ -16,7 +16,7 @@ module.directive('graphLegend', function(popoverSrv, $timeout) { var i; var legendScrollbar; const legendRightDefaultWidth = 10; - let legendElem = elem.parent(); + const legendElem = elem.parent(); scope.$on('$destroy', function() { destroyScrollbar(); @@ -111,7 +111,7 @@ module.directive('graphLegend', function(popoverSrv, $timeout) { } function render() { - let legendWidth = legendElem.width(); + const legendWidth = legendElem.width(); if (!ctrl.panel.legend.show) { elem.empty(); firstRender = true; @@ -176,7 +176,7 @@ module.directive('graphLegend', function(popoverSrv, $timeout) { } function renderSeriesLegendElements() { - let seriesElements = []; + const seriesElements = []; for (i = 0; i < seriesList.length; i++) { var series = seriesList[i]; @@ -231,7 +231,7 @@ module.directive('graphLegend', function(popoverSrv, $timeout) { } function renderLegendElement(tableHeaderElem) { - let legendWidth = elem.width(); + const legendWidth = elem.width(); var seriesElements = renderSeriesLegendElements(); @@ -262,8 +262,8 @@ module.directive('graphLegend', function(popoverSrv, $timeout) {
    `; - let scrollRoot = elem; - let scroller = elem.find('.graph-legend-scroll'); + const scrollRoot = elem; + const scroller = elem.find('.graph-legend-scroll'); // clear existing scroll bar track to prevent duplication scrollRoot.find('.baron__track').remove(); @@ -272,7 +272,7 @@ module.directive('graphLegend', function(popoverSrv, $timeout) { $(scrollBarHTML).appendTo(scrollRoot); scroller.addClass(scrollerClass); - let scrollbarParams = { + const scrollbarParams = { root: scrollRoot[0], scroller: scroller[0], bar: '.baron__bar', diff --git a/public/app/plugins/panel/graph/module.ts b/public/app/plugins/panel/graph/module.ts index ba151692147..97999158446 100644 --- a/public/app/plugins/panel/graph/module.ts +++ b/public/app/plugins/panel/graph/module.ts @@ -196,7 +196,7 @@ class GraphCtrl extends MetricsPanelCtrl { tip: 'No datapoints returned from data query', }; } else { - for (let series of this.seriesList) { + for (const series of this.seriesList) { if (series.isOutsideRange) { this.dataWarning = { title: 'Data points outside time range', @@ -226,7 +226,7 @@ class GraphCtrl extends MetricsPanelCtrl { return; } - for (let series of this.seriesList) { + for (const series of this.seriesList) { series.applySeriesOverrides(this.panel.seriesOverrides); if (series.unit) { diff --git a/public/app/plugins/panel/graph/specs/graph.test.ts b/public/app/plugins/panel/graph/specs/graph.test.ts index f75f7cd68ea..2ae76bb9c9c 100644 --- a/public/app/plugins/panel/graph/specs/graph.test.ts +++ b/public/app/plugins/panel/graph/specs/graph.test.ts @@ -28,9 +28,9 @@ import moment from 'moment'; import $ from 'jquery'; import { graphDirective } from '../graph'; -let ctx = {}; +const ctx = {}; let ctrl; -let scope = { +const scope = { ctrl: {}, range: { from: moment([2015, 1, 1]), diff --git a/public/app/plugins/panel/graph/specs/graph_ctrl.test.ts b/public/app/plugins/panel/graph/specs/graph_ctrl.test.ts index a0c7dd0ab9c..49efa8d4120 100644 --- a/public/app/plugins/panel/graph/specs/graph_ctrl.test.ts +++ b/public/app/plugins/panel/graph/specs/graph_ctrl.test.ts @@ -4,7 +4,7 @@ import { GraphCtrl } from '../module'; jest.mock('../graph', () => ({})); describe('GraphCtrl', () => { - let injector = { + const injector = { get: () => { return { timeRange: () => { @@ -17,7 +17,7 @@ describe('GraphCtrl', () => { }, }; - let scope = { + const scope = { $on: () => {}, }; @@ -30,7 +30,7 @@ describe('GraphCtrl', () => { }, }; - let ctx = {}; + const ctx = {}; beforeEach(() => { ctx.ctrl = new GraphCtrl(scope, injector, {}); diff --git a/public/app/plugins/panel/graph/specs/histogram.test.ts b/public/app/plugins/panel/graph/specs/histogram.test.ts index 0e9eaa8b98e..adbc0fcba68 100644 --- a/public/app/plugins/panel/graph/specs/histogram.test.ts +++ b/public/app/plugins/panel/graph/specs/histogram.test.ts @@ -11,17 +11,17 @@ describe('Graph Histogam Converter', function() { it('Should convert to series-like array', () => { bucketSize = 10; - let expected = [[0, 2], [10, 3], [20, 2]]; + const expected = [[0, 2], [10, 3], [20, 2]]; - let histogram = convertValuesToHistogram(values, bucketSize, 1, 29); + const histogram = convertValuesToHistogram(values, bucketSize, 1, 29); expect(histogram).toMatchObject(expected); }); it('Should not add empty buckets', () => { bucketSize = 5; - let expected = [[0, 2], [5, 0], [10, 2], [15, 1], [20, 1], [25, 1]]; + const expected = [[0, 2], [5, 0], [10, 2], [15, 1], [20, 1], [25, 1]]; - let histogram = convertValuesToHistogram(values, bucketSize, 1, 29); + const histogram = convertValuesToHistogram(values, bucketSize, 1, 29); expect(histogram).toMatchObject(expected); }); }); @@ -38,18 +38,18 @@ describe('Graph Histogam Converter', function() { }); it('Should convert to values array', () => { - let expected = [1, 2, 10, 11, 17, 20, 29]; + const expected = [1, 2, 10, 11, 17, 20, 29]; - let values = getSeriesValues(data); + const values = getSeriesValues(data); expect(values).toMatchObject(expected); }); it('Should skip null values', () => { data[0].datapoints.push([null, 0]); - let expected = [1, 2, 10, 11, 17, 20, 29]; + const expected = [1, 2, 10, 11, 17, 20, 29]; - let values = getSeriesValues(data); + const values = getSeriesValues(data); expect(values).toMatchObject(expected); }); }); diff --git a/public/app/plugins/panel/graph/specs/series_override_ctrl.test.ts b/public/app/plugins/panel/graph/specs/series_override_ctrl.test.ts index 2e7456a132a..40b6c1ba561 100644 --- a/public/app/plugins/panel/graph/specs/series_override_ctrl.test.ts +++ b/public/app/plugins/panel/graph/specs/series_override_ctrl.test.ts @@ -2,7 +2,7 @@ import '../series_overrides_ctrl'; import { SeriesOverridesCtrl } from '../series_overrides_ctrl'; describe('SeriesOverridesCtrl', () => { - let popoverSrv = {}; + const popoverSrv = {}; let $scope; beforeEach(() => { diff --git a/public/app/plugins/panel/heatmap/color_legend.ts b/public/app/plugins/panel/heatmap/color_legend.ts index cae1e5fac7f..84ecd2389b6 100644 --- a/public/app/plugins/panel/heatmap/color_legend.ts +++ b/public/app/plugins/panel/heatmap/color_legend.ts @@ -6,7 +6,7 @@ import { contextSrv } from 'app/core/core'; import { tickStep } from 'app/core/utils/ticks'; import { getColorScale, getOpacityScale } from './color_scale'; -let module = angular.module('grafana.directives'); +const module = angular.module('grafana.directives'); const LEGEND_HEIGHT_PX = 6; const LEGEND_WIDTH_PX = 100; @@ -21,8 +21,8 @@ module.directive('colorLegend', function() { restrict: 'E', template: '
    ', link: function(scope, elem, attrs) { - let ctrl = scope.ctrl; - let panel = scope.ctrl.panel; + const ctrl = scope.ctrl; + const panel = scope.ctrl.panel; render(); @@ -31,17 +31,17 @@ module.directive('colorLegend', function() { }); function render() { - let legendElem = $(elem).find('svg'); - let legendWidth = Math.floor(legendElem.outerWidth()); + const legendElem = $(elem).find('svg'); + const legendWidth = Math.floor(legendElem.outerWidth()); if (panel.color.mode === 'spectrum') { - let colorScheme = _.find(ctrl.colorSchemes, { + const colorScheme = _.find(ctrl.colorSchemes, { value: panel.color.colorScheme, }); - let colorScale = getColorScale(colorScheme, contextSrv.user.lightTheme, legendWidth); + const colorScale = getColorScale(colorScheme, contextSrv.user.lightTheme, legendWidth); drawSimpleColorLegend(elem, colorScale); } else if (panel.color.mode === 'opacity') { - let colorOptions = panel.color; + const colorOptions = panel.color; drawSimpleOpacityLegend(elem, colorOptions); } } @@ -57,8 +57,8 @@ module.directive('heatmapLegend', function() { restrict: 'E', template: `
    `, link: function(scope, elem, attrs) { - let ctrl = scope.ctrl; - let panel = scope.ctrl.panel; + const ctrl = scope.ctrl; + const panel = scope.ctrl.panel; render(); ctrl.events.on('render', function() { @@ -68,18 +68,18 @@ module.directive('heatmapLegend', function() { function render() { clearLegend(elem); if (!_.isEmpty(ctrl.data) && !_.isEmpty(ctrl.data.cards)) { - let rangeFrom = 0; - let rangeTo = ctrl.data.cardStats.max; - let maxValue = panel.color.max || rangeTo; - let minValue = panel.color.min || 0; + const rangeFrom = 0; + const rangeTo = ctrl.data.cardStats.max; + const maxValue = panel.color.max || rangeTo; + const minValue = panel.color.min || 0; if (panel.color.mode === 'spectrum') { - let colorScheme = _.find(ctrl.colorSchemes, { + const colorScheme = _.find(ctrl.colorSchemes, { value: panel.color.colorScheme, }); drawColorLegend(elem, colorScheme, rangeFrom, rangeTo, maxValue, minValue); } else if (panel.color.mode === 'opacity') { - let colorOptions = panel.color; + const colorOptions = panel.color; drawOpacityLegend(elem, colorOptions, rangeFrom, rangeTo, maxValue, minValue); } } @@ -89,21 +89,21 @@ module.directive('heatmapLegend', function() { }); function drawColorLegend(elem, colorScheme, rangeFrom, rangeTo, maxValue, minValue) { - let legendElem = $(elem).find('svg'); - let legend = d3.select(legendElem.get(0)); + const legendElem = $(elem).find('svg'); + const legend = d3.select(legendElem.get(0)); clearLegend(elem); - let legendWidth = Math.floor(legendElem.outerWidth()) - 30; - let legendHeight = legendElem.attr('height'); + const legendWidth = Math.floor(legendElem.outerWidth()) - 30; + const legendHeight = legendElem.attr('height'); let rangeStep = 1; if (rangeTo - rangeFrom > legendWidth) { rangeStep = Math.floor((rangeTo - rangeFrom) / legendWidth); } - let widthFactor = legendWidth / (rangeTo - rangeFrom); - let valuesRange = d3.range(rangeFrom, rangeTo, rangeStep); + const widthFactor = legendWidth / (rangeTo - rangeFrom); + const valuesRange = d3.range(rangeFrom, rangeTo, rangeStep); - let colorScale = getColorScale(colorScheme, contextSrv.user.lightTheme, maxValue, minValue); + const colorScale = getColorScale(colorScheme, contextSrv.user.lightTheme, maxValue, minValue); legend .selectAll('.heatmap-color-legend-rect') .data(valuesRange) @@ -120,21 +120,21 @@ function drawColorLegend(elem, colorScheme, rangeFrom, rangeTo, maxValue, minVal } function drawOpacityLegend(elem, options, rangeFrom, rangeTo, maxValue, minValue) { - let legendElem = $(elem).find('svg'); - let legend = d3.select(legendElem.get(0)); + const legendElem = $(elem).find('svg'); + const legend = d3.select(legendElem.get(0)); clearLegend(elem); - let legendWidth = Math.floor(legendElem.outerWidth()) - 30; - let legendHeight = legendElem.attr('height'); + const legendWidth = Math.floor(legendElem.outerWidth()) - 30; + const legendHeight = legendElem.attr('height'); let rangeStep = 1; if (rangeTo - rangeFrom > legendWidth) { rangeStep = Math.floor((rangeTo - rangeFrom) / legendWidth); } - let widthFactor = legendWidth / (rangeTo - rangeFrom); - let valuesRange = d3.range(rangeFrom, rangeTo, rangeStep); + const widthFactor = legendWidth / (rangeTo - rangeFrom); + const valuesRange = d3.range(rangeFrom, rangeTo, rangeStep); - let opacityScale = getOpacityScale(options, maxValue, minValue); + const opacityScale = getOpacityScale(options, maxValue, minValue); legend .selectAll('.heatmap-opacity-legend-rect') .data(valuesRange) @@ -152,27 +152,27 @@ function drawOpacityLegend(elem, options, rangeFrom, rangeTo, maxValue, minValue } function drawLegendValues(elem, colorScale, rangeFrom, rangeTo, maxValue, minValue, legendWidth) { - let legendElem = $(elem).find('svg'); - let legend = d3.select(legendElem.get(0)); + const legendElem = $(elem).find('svg'); + const legend = d3.select(legendElem.get(0)); if (legendWidth <= 0 || legendElem.get(0).childNodes.length === 0) { return; } - let legendValueScale = d3 + const legendValueScale = d3 .scaleLinear() .domain([0, rangeTo]) .range([0, legendWidth]); - let ticks = buildLegendTicks(0, rangeTo, maxValue, minValue); - let xAxis = d3 + const ticks = buildLegendTicks(0, rangeTo, maxValue, minValue); + const xAxis = d3 .axisBottom(legendValueScale) .tickValues(ticks) .tickSize(LEGEND_TICK_SIZE); - let colorRect = legendElem.find(':first-child'); - let posY = getSvgElemHeight(legendElem) + LEGEND_VALUE_MARGIN; - let posX = getSvgElemX(colorRect); + const colorRect = legendElem.find(':first-child'); + const posY = getSvgElemHeight(legendElem) + LEGEND_VALUE_MARGIN; + const posX = getSvgElemX(colorRect); d3 .select(legendElem.get(0)) @@ -188,18 +188,18 @@ function drawLegendValues(elem, colorScale, rangeFrom, rangeTo, maxValue, minVal } function drawSimpleColorLegend(elem, colorScale) { - let legendElem = $(elem).find('svg'); + const legendElem = $(elem).find('svg'); clearLegend(elem); - let legendWidth = Math.floor(legendElem.outerWidth()); - let legendHeight = legendElem.attr('height'); + const legendWidth = Math.floor(legendElem.outerWidth()); + const legendHeight = legendElem.attr('height'); if (legendWidth) { - let valuesNumber = Math.floor(legendWidth / 2); - let rangeStep = Math.floor(legendWidth / valuesNumber); - let valuesRange = d3.range(0, legendWidth, rangeStep); + const valuesNumber = Math.floor(legendWidth / 2); + const rangeStep = Math.floor(legendWidth / valuesNumber); + const valuesRange = d3.range(0, legendWidth, rangeStep); - let legend = d3.select(legendElem.get(0)); + const legend = d3.select(legendElem.get(0)); var legendRects = legend.selectAll('.heatmap-color-legend-rect').data(valuesRange); legendRects @@ -215,12 +215,12 @@ function drawSimpleColorLegend(elem, colorScale) { } function drawSimpleOpacityLegend(elem, options) { - let legendElem = $(elem).find('svg'); + const legendElem = $(elem).find('svg'); clearLegend(elem); - let legend = d3.select(legendElem.get(0)); - let legendWidth = Math.floor(legendElem.outerWidth()); - let legendHeight = legendElem.attr('height'); + const legend = d3.select(legendElem.get(0)); + const legendWidth = Math.floor(legendElem.outerWidth()); + const legendHeight = legendElem.attr('height'); if (legendWidth) { let legendOpacityScale; @@ -237,8 +237,8 @@ function drawSimpleOpacityLegend(elem, options) { .range([0, 1]); } - let rangeStep = 10; - let valuesRange = d3.range(0, legendWidth, rangeStep); + const rangeStep = 10; + const valuesRange = d3.range(0, legendWidth, rangeStep); var legendRects = legend.selectAll('.heatmap-opacity-legend-rect').data(valuesRange); legendRects @@ -255,12 +255,12 @@ function drawSimpleOpacityLegend(elem, options) { } function clearLegend(elem) { - let legendElem = $(elem).find('svg'); + const legendElem = $(elem).find('svg'); legendElem.empty(); } function getSvgElemX(elem) { - let svgElem = elem.get(0); + const svgElem = elem.get(0); if (svgElem && svgElem.x && svgElem.x.baseVal) { return svgElem.x.baseVal.value; } else { @@ -269,7 +269,7 @@ function getSvgElemX(elem) { } function getSvgElemHeight(elem) { - let svgElem = elem.get(0); + const svgElem = elem.get(0); if (svgElem && svgElem.height && svgElem.height.baseVal) { return svgElem.height.baseVal.value; } else { @@ -278,13 +278,13 @@ function getSvgElemHeight(elem) { } function buildLegendTicks(rangeFrom, rangeTo, maxValue, minValue) { - let range = rangeTo - rangeFrom; - let tickStepSize = tickStep(rangeFrom, rangeTo, 3); - let ticksNum = Math.round(range / tickStepSize); + const range = rangeTo - rangeFrom; + const tickStepSize = tickStep(rangeFrom, rangeTo, 3); + const ticksNum = Math.round(range / tickStepSize); let ticks = []; for (let i = 0; i < ticksNum; i++) { - let current = tickStepSize * i; + const current = tickStepSize * i; // Add user-defined min and max if it had been set if (isValueCloseTo(minValue, current, tickStepSize)) { ticks.push(minValue); @@ -309,6 +309,6 @@ function buildLegendTicks(rangeFrom, rangeTo, maxValue, minValue) { } function isValueCloseTo(val, valueTo, step) { - let diff = Math.abs(val - valueTo); + const diff = Math.abs(val - valueTo); return diff < step * 0.3; } diff --git a/public/app/plugins/panel/heatmap/color_scale.ts b/public/app/plugins/panel/heatmap/color_scale.ts index 3550c981db2..2234deb8405 100644 --- a/public/app/plugins/panel/heatmap/color_scale.ts +++ b/public/app/plugins/panel/heatmap/color_scale.ts @@ -2,11 +2,11 @@ import * as d3 from 'd3'; import * as d3ScaleChromatic from 'd3-scale-chromatic'; export function getColorScale(colorScheme: any, lightTheme: boolean, maxValue: number, minValue = 0): (d: any) => any { - let colorInterpolator = d3ScaleChromatic[colorScheme.value]; - let colorScaleInverted = colorScheme.invert === 'always' || colorScheme.invert === (lightTheme ? 'light' : 'dark'); + const colorInterpolator = d3ScaleChromatic[colorScheme.value]; + const colorScaleInverted = colorScheme.invert === 'always' || colorScheme.invert === (lightTheme ? 'light' : 'dark'); - let start = colorScaleInverted ? maxValue : minValue; - let end = colorScaleInverted ? minValue : maxValue; + const start = colorScaleInverted ? maxValue : minValue; + const end = colorScaleInverted ? minValue : maxValue; return d3.scaleSequential(colorInterpolator).domain([start, end]); } diff --git a/public/app/plugins/panel/heatmap/heatmap_ctrl.ts b/public/app/plugins/panel/heatmap/heatmap_ctrl.ts index 1d35ff2ea84..66b72f8d37a 100644 --- a/public/app/plugins/panel/heatmap/heatmap_ctrl.ts +++ b/public/app/plugins/panel/heatmap/heatmap_ctrl.ts @@ -13,10 +13,10 @@ import { sortSeriesByLabel, } from './heatmap_data_converter'; -let X_BUCKET_NUMBER_DEFAULT = 30; -let Y_BUCKET_NUMBER_DEFAULT = 10; +const X_BUCKET_NUMBER_DEFAULT = 30; +const Y_BUCKET_NUMBER_DEFAULT = 10; -let panelDefaults = { +const panelDefaults = { heatmap: {}, cards: { cardPadding: null, @@ -57,12 +57,12 @@ let panelDefaults = { highlightCards: true, }; -let colorModes = ['opacity', 'spectrum']; -let opacityScales = ['linear', 'sqrt']; +const colorModes = ['opacity', 'spectrum']; +const opacityScales = ['linear', 'sqrt']; // Schemes from d3-scale-chromatic // https://github.com/d3/d3-scale-chromatic -let colorSchemes = [ +const colorSchemes = [ // Diverging { name: 'Spectral', value: 'interpolateSpectral', invert: 'always' }, { name: 'RdYlGn', value: 'interpolateRdYlGn', invert: 'always' }, @@ -161,11 +161,11 @@ export class HeatmapCtrl extends MetricsPanelCtrl { let xBucketSize, yBucketSize, bucketsData, heatmapStats; const logBase = this.panel.yAxis.logBase; - let xBucketNumber = this.panel.xBucketNumber || X_BUCKET_NUMBER_DEFAULT; - let xBucketSizeByNumber = Math.floor((this.range.to - this.range.from) / xBucketNumber); + const xBucketNumber = this.panel.xBucketNumber || X_BUCKET_NUMBER_DEFAULT; + const xBucketSizeByNumber = Math.floor((this.range.to - this.range.from) / xBucketNumber); // Parse X bucket size (number or interval) - let isIntervalString = kbn.interval_regex.test(this.panel.xBucketSize); + const isIntervalString = kbn.interval_regex.test(this.panel.xBucketSize); if (isIntervalString) { xBucketSize = kbn.interval_to_ms(this.panel.xBucketSize); } else if ( @@ -180,7 +180,7 @@ export class HeatmapCtrl extends MetricsPanelCtrl { // Calculate Y bucket size heatmapStats = this.parseSeries(this.series); - let yBucketNumber = this.panel.yBucketNumber || Y_BUCKET_NUMBER_DEFAULT; + const yBucketNumber = this.panel.yBucketNumber || Y_BUCKET_NUMBER_DEFAULT; if (logBase !== 1) { yBucketSize = this.panel.yAxis.splitFactor; } else { @@ -204,7 +204,7 @@ export class HeatmapCtrl extends MetricsPanelCtrl { yBucketSize = 1; } - let { cards, cardStats } = convertToCards(bucketsData); + const { cards, cardStats } = convertToCards(bucketsData); this.data = { buckets: bucketsData, @@ -241,12 +241,12 @@ export class HeatmapCtrl extends MetricsPanelCtrl { } // Calculate bucket size based on heatmap data - let xBucketBoundSet = _.map(_.keys(bucketsData), key => Number(key)); + const xBucketBoundSet = _.map(_.keys(bucketsData), key => Number(key)); xBucketSize = calculateBucketSize(xBucketBoundSet); // Always let yBucketSize=1 in 'tsbuckets' mode yBucketSize = 1; - let { cards, cardStats } = convertToCards(bucketsData); + const { cards, cardStats } = convertToCards(bucketsData); this.data = { buckets: bucketsData, @@ -284,7 +284,7 @@ export class HeatmapCtrl extends MetricsPanelCtrl { tip: 'No datapoints returned from data query', }; } else { - for (let series of this.series) { + for (const series of this.series) { if (series.isOutsideRange) { this.dataWarning = { title: 'Data points outside time range', @@ -313,17 +313,17 @@ export class HeatmapCtrl extends MetricsPanelCtrl { throw new Error('Heatmap error: data should be a time series'); } - let series = new TimeSeries({ + const series = new TimeSeries({ datapoints: seriesData.datapoints, alias: seriesData.target, }); series.flotpairs = series.getFlotPairs(this.panel.nullPointMode); - let datapoints = seriesData.datapoints || []; + const datapoints = seriesData.datapoints || []; if (datapoints && datapoints.length > 0) { - let last = datapoints[datapoints.length - 1][1]; - let from = this.range.from; + const last = datapoints[datapoints.length - 1][1]; + const from = this.range.from; if (last - from < -10000) { series.isOutsideRange = true; } @@ -333,9 +333,9 @@ export class HeatmapCtrl extends MetricsPanelCtrl { } parseSeries(series) { - let min = _.min(_.map(series, s => s.stats.min)); - let minLog = _.min(_.map(series, s => s.stats.logmin)); - let max = _.max(_.map(series, s => s.stats.max)); + const min = _.min(_.map(series, s => s.stats.min)); + const minLog = _.min(_.map(series, s => s.stats.logmin)); + const max = _.max(_.map(series, s => s.stats.max)); return { max: max, @@ -345,10 +345,10 @@ export class HeatmapCtrl extends MetricsPanelCtrl { } parseHistogramSeries(series) { - let bounds = _.map(series, s => Number(s.alias)); - let min = _.min(bounds); - let minLog = _.min(bounds); - let max = _.max(bounds); + const bounds = _.map(series, s => Number(s.alias)); + const min = _.min(bounds); + const minLog = _.min(bounds); + const max = _.max(bounds); return { max: max, diff --git a/public/app/plugins/panel/heatmap/heatmap_data_converter.ts b/public/app/plugins/panel/heatmap/heatmap_data_converter.ts index 048b19de911..0b3f83bbe46 100644 --- a/public/app/plugins/panel/heatmap/heatmap_data_converter.ts +++ b/public/app/plugins/panel/heatmap/heatmap_data_converter.ts @@ -1,7 +1,7 @@ import _ from 'lodash'; -let VALUE_INDEX = 0; -let TIME_INDEX = 1; +const VALUE_INDEX = 0; +const TIME_INDEX = 1; interface XBucket { x: number; @@ -18,18 +18,18 @@ interface YBucket { * @param seriesList List of time series */ function histogramToHeatmap(seriesList) { - let heatmap = {}; + const heatmap = {}; for (let i = 0; i < seriesList.length; i++) { - let series = seriesList[i]; - let bound = i; + const series = seriesList[i]; + const bound = i; if (isNaN(bound)) { return heatmap; } - for (let point of series.datapoints) { - let count = point[VALUE_INDEX]; - let time = point[TIME_INDEX]; + for (const point of series.datapoints) { + const count = point[VALUE_INDEX]; + const time = point[TIME_INDEX]; if (!_.isNumber(count)) { continue; @@ -101,10 +101,10 @@ function parseHistogramLabel(label: string): number { function convertToCards(buckets) { let min = 0, max = 0; - let cards = []; + const cards = []; _.forEach(buckets, xBucket => { _.forEach(xBucket.buckets, yBucket => { - let card = { + const card = { x: xBucket.x, y: yBucket.y, yBounds: yBucket.bounds, @@ -123,7 +123,7 @@ function convertToCards(buckets) { }); }); - let cardStats = { min, max }; + const cardStats = { min, max }; return { cards, cardStats }; } @@ -146,19 +146,19 @@ function convertToCards(buckets) { */ function mergeZeroBuckets(buckets, minValue) { _.forEach(buckets, xBucket => { - let yBuckets = xBucket.buckets; + const yBuckets = xBucket.buckets; - let emptyBucket = { + const emptyBucket = { bounds: { bottom: 0, top: 0 }, values: [], points: [], count: 0, }; - let nullBucket = yBuckets[0] || emptyBucket; - let minBucket = yBuckets[minValue] || emptyBucket; + const nullBucket = yBuckets[0] || emptyBucket; + const minBucket = yBuckets[minValue] || emptyBucket; - let newBucket = { + const newBucket = { y: 0, bounds: { bottom: minValue, top: minBucket.bounds.top || minValue }, values: [], @@ -211,11 +211,11 @@ function mergeZeroBuckets(buckets, minValue) { * } */ function convertToHeatMap(seriesList, yBucketSize, xBucketSize, logBase = 1) { - let heatmap = {}; + const heatmap = {}; - for (let series of seriesList) { - let datapoints = series.datapoints; - let seriesName = series.label; + for (const series of seriesList) { + const datapoints = series.datapoints; + const seriesName = series.label; // Slice series into X axis buckets // | | ** | | * | **| @@ -224,7 +224,7 @@ function convertToHeatMap(seriesList, yBucketSize, xBucketSize, logBase = 1) { // |____|____|____|____|____|_ // _.forEach(datapoints, point => { - let bucketBound = getBucketBound(point[TIME_INDEX], xBucketSize); + const bucketBound = getBucketBound(point[TIME_INDEX], xBucketSize); pushToXBuckets(heatmap, point, bucketBound, seriesName); }); } @@ -247,13 +247,13 @@ function convertToHeatMap(seriesList, yBucketSize, xBucketSize, logBase = 1) { } function pushToXBuckets(buckets, point, bucketNum, seriesName) { - let value = point[VALUE_INDEX]; + const value = point[VALUE_INDEX]; if (value === null || value === undefined || isNaN(value)) { return; } // Add series name to point for future identification - let point_ext = _.concat(point, seriesName); + const point_ext = _.concat(point, seriesName); if (buckets[bucketNum] && buckets[bucketNum].values) { buckets[bucketNum].values.push(value); @@ -308,18 +308,18 @@ function getBucketBounds(value, bucketSize) { } function getBucketBound(value, bucketSize) { - let bounds = getBucketBounds(value, bucketSize); + const bounds = getBucketBounds(value, bucketSize); return bounds.bottom; } function convertToValueBuckets(xBucket, bucketSize) { - let values = xBucket.values; - let points = xBucket.points; - let buckets = {}; + const values = xBucket.values; + const points = xBucket.points; + const buckets = {}; _.forEach(values, (val, index) => { - let bounds = getBucketBounds(val, bucketSize); - let bucketNum = bounds.bottom; + const bounds = getBucketBounds(val, bucketSize); + const bucketNum = bounds.bottom; pushToYBuckets(buckets, bucketNum, val, points[index], bounds); }); @@ -335,13 +335,13 @@ function getLogScaleBucketBounds(value, yBucketSplitFactor, logBase) { return { bottom: 0, top: 0 }; } - let value_log = logp(value, logBase); + const value_log = logp(value, logBase); let pow, powTop; if (yBucketSplitFactor === 1 || !yBucketSplitFactor) { pow = Math.floor(value_log); powTop = pow + 1; } else { - let additional_bucket_size = 1 / yBucketSplitFactor; + const additional_bucket_size = 1 / yBucketSplitFactor; let additional_log = value_log - Math.floor(value_log); additional_log = Math.floor(additional_log / additional_bucket_size) * additional_bucket_size; pow = Math.floor(value_log) + additional_log; @@ -354,18 +354,18 @@ function getLogScaleBucketBounds(value, yBucketSplitFactor, logBase) { } function getLogScaleBucketBound(value, yBucketSplitFactor, logBase) { - let bounds = getLogScaleBucketBounds(value, yBucketSplitFactor, logBase); + const bounds = getLogScaleBucketBounds(value, yBucketSplitFactor, logBase); return bounds.bottom; } function convertToLogScaleValueBuckets(xBucket, yBucketSplitFactor, logBase) { - let values = xBucket.values; - let points = xBucket.points; + const values = xBucket.values; + const points = xBucket.points; - let buckets = {}; + const buckets = {}; _.forEach(values, (val, index) => { - let bounds = getLogScaleBucketBounds(val, yBucketSplitFactor, logBase); - let bucketNum = bounds.bottom; + const bounds = getLogScaleBucketBounds(val, yBucketSplitFactor, logBase); + const bucketNum = bounds.bottom; pushToYBuckets(buckets, bucketNum, val, points[index], bounds); }); @@ -396,7 +396,7 @@ function calculateBucketSize(bounds: number[], logBase = 1): number { } else { bounds = _.sortBy(bounds); for (let i = 1; i < bounds.length; i++) { - let distance = getDistance(bounds[i], bounds[i - 1], logBase); + const distance = getDistance(bounds[i], bounds[i - 1], logBase); bucketSize = distance < bucketSize ? distance : bucketSize; } } @@ -416,7 +416,7 @@ function getDistance(a: number, b: number, logBase = 1): number { return Math.abs(b - a); } else { // logarithmic distance - let ratio = Math.max(a, b) / Math.min(a, b); + const ratio = Math.max(a, b) / Math.min(a, b); return logp(ratio, logBase); } } diff --git a/public/app/plugins/panel/heatmap/heatmap_tooltip.ts b/public/app/plugins/panel/heatmap/heatmap_tooltip.ts index 6cf9262f520..5e48849ca59 100644 --- a/public/app/plugins/panel/heatmap/heatmap_tooltip.ts +++ b/public/app/plugins/panel/heatmap/heatmap_tooltip.ts @@ -4,10 +4,10 @@ import _ from 'lodash'; import kbn from 'app/core/utils/kbn'; import { getValueBucketBound } from './heatmap_data_converter'; -let TOOLTIP_PADDING_X = 30; -let TOOLTIP_PADDING_Y = 5; -let HISTOGRAM_WIDTH = 160; -let HISTOGRAM_HEIGHT = 40; +const TOOLTIP_PADDING_X = 30; +const TOOLTIP_PADDING_Y = 5; +const HISTOGRAM_WIDTH = 160; +const HISTOGRAM_HEIGHT = 40; export class HeatmapTooltip { tooltip: any; @@ -67,7 +67,7 @@ export class HeatmapTooltip { return; } - let { xBucketIndex, yBucketIndex } = this.getBucketIndexes(pos, data); + const { xBucketIndex, yBucketIndex } = this.getBucketIndexes(pos, data); if (!data.buckets[xBucketIndex]) { this.destroy(); @@ -79,14 +79,14 @@ export class HeatmapTooltip { } let boundBottom, boundTop, valuesNumber; - let xData = data.buckets[xBucketIndex]; + const xData = data.buckets[xBucketIndex]; // Search in special 'zero' bucket also - let yData = _.find(xData.buckets, (bucket, bucketIndex) => { + const yData = _.find(xData.buckets, (bucket, bucketIndex) => { return bucket.bounds.bottom === yBucketIndex || bucketIndex === yBucketIndex.toString(); }); - let tooltipTimeFormat = 'YYYY-MM-DD HH:mm:ss'; - let time = this.dashboard.formatDate(xData.x, tooltipTimeFormat); + const tooltipTimeFormat = 'YYYY-MM-DD HH:mm:ss'; + const time = this.dashboard.formatDate(xData.x, tooltipTimeFormat); // Decimals override. Code from panel/graph/graph.ts let countValueFormatter, bucketBoundFormatter; @@ -97,7 +97,7 @@ export class HeatmapTooltip { // auto decimals // legend and tooltip gets one more decimal precision // than graph legend ticks - let decimals = (this.panelCtrl.decimals || -1) + 1; + const decimals = (this.panelCtrl.decimals || -1) + 1; countValueFormatter = this.countValueFormatter(decimals, this.panelCtrl.scaledDecimals + 2); bucketBoundFormatter = this.panelCtrl.tickValueFormatter(decimals, this.panelCtrl.scaledDecimals + 2); } @@ -117,7 +117,7 @@ export class HeatmapTooltip { boundTop = yBucketIndex < data.tsBuckets.length - 1 ? tickFormatter(yBucketIndex + 1) : ''; } else { // Display 0 if bucket is a special 'zero' bucket - let bottom = yData.y ? yData.bounds.bottom : 0; + const bottom = yData.y ? yData.bounds.bottom : 0; boundBottom = bucketBoundFormatter(bottom); boundTop = bucketBoundFormatter(yData.bounds.top); } @@ -158,7 +158,7 @@ export class HeatmapTooltip { getXBucketIndex(x, data) { // First try to find X bucket by checking x pos is in the // [bucket.x, bucket.x + xBucketSize] interval - let xBucket = _.find(data.buckets, bucket => { + const xBucket = _.find(data.buckets, bucket => { return x > bucket.x && x - bucket.x <= data.xBucketSize; }); return xBucket ? xBucket.x : getValueBucketBound(x, data.xBucketSize, 1); @@ -168,7 +168,7 @@ export class HeatmapTooltip { if (data.tsBuckets) { return Math.floor(y); } - let yBucketIndex = getValueBucketBound(y, data.yBucketSize, this.panel.yAxis.logBase); + const yBucketIndex = getValueBucketBound(y, data.yBucketSize, this.panel.yAxis.logBase); return yBucketIndex; } @@ -180,8 +180,8 @@ export class HeatmapTooltip { } addHistogram(data) { - let xBucket = this.scope.ctrl.data.buckets[data.x]; - let yBucketSize = this.scope.ctrl.data.yBucketSize; + const xBucket = this.scope.ctrl.data.buckets[data.x]; + const yBucketSize = this.scope.ctrl.data.yBucketSize; let min, max, ticks; if (this.scope.ctrl.data.tsBuckets) { min = 0; @@ -193,33 +193,33 @@ export class HeatmapTooltip { ticks = this.scope.ctrl.data.yAxis.ticks; } let histogramData = _.map(xBucket.buckets, bucket => { - let count = bucket.count !== undefined ? bucket.count : bucket.values.length; + const count = bucket.count !== undefined ? bucket.count : bucket.values.length; return [bucket.bounds.bottom, count]; }); histogramData = _.filter(histogramData, d => { return d[0] >= min && d[0] <= max; }); - let scale = this.scope.yScale.copy(); - let histXScale = scale.domain([min, max]).range([0, HISTOGRAM_WIDTH]); + const scale = this.scope.yScale.copy(); + const histXScale = scale.domain([min, max]).range([0, HISTOGRAM_WIDTH]); let barWidth; if (this.panel.yAxis.logBase === 1) { barWidth = Math.floor(HISTOGRAM_WIDTH / (max - min) * yBucketSize * 0.9); } else { - let barNumberFactor = yBucketSize ? yBucketSize : 1; + const barNumberFactor = yBucketSize ? yBucketSize : 1; barWidth = Math.floor(HISTOGRAM_WIDTH / ticks / barNumberFactor * 0.9); } barWidth = Math.max(barWidth, 1); // Normalize histogram Y axis - let histogramDomain = _.reduce(_.map(histogramData, d => d[1]), (sum, val) => sum + val, 0); - let histYScale = d3 + const histogramDomain = _.reduce(_.map(histogramData, d => d[1]), (sum, val) => sum + val, 0); + const histYScale = d3 .scaleLinear() .domain([0, histogramDomain]) .range([0, HISTOGRAM_HEIGHT]); - let histogram = this.tooltip + const histogram = this.tooltip .select('.heatmap-histogram') .append('svg') .attr('width', HISTOGRAM_WIDTH) @@ -247,9 +247,9 @@ export class HeatmapTooltip { return; } - let elem = $(this.tooltip.node())[0]; - let tooltipWidth = elem.clientWidth; - let tooltipHeight = elem.clientHeight; + const elem = $(this.tooltip.node())[0]; + const tooltipWidth = elem.clientWidth; + const tooltipHeight = elem.clientHeight; let left = pos.pageX + TOOLTIP_PADDING_X; let top = pos.pageY + TOOLTIP_PADDING_Y; @@ -266,7 +266,7 @@ export class HeatmapTooltip { } countValueFormatter(decimals, scaledDecimals = null) { - let format = 'short'; + const format = 'short'; return function(value) { return kbn.valueFormats[format](value, decimals, scaledDecimals); }; diff --git a/public/app/plugins/panel/heatmap/rendering.ts b/public/app/plugins/panel/heatmap/rendering.ts index 8ea216be89d..fcbb39f8417 100644 --- a/public/app/plugins/panel/heatmap/rendering.ts +++ b/public/app/plugins/panel/heatmap/rendering.ts @@ -9,7 +9,7 @@ import { HeatmapTooltip } from './heatmap_tooltip'; import { mergeZeroBuckets } from './heatmap_data_converter'; import { getColorScale, getOpacityScale } from './color_scale'; -let MIN_CARD_SIZE = 1, +const MIN_CARD_SIZE = 1, CARD_PADDING = 1, CARD_ROUND = 0, DATA_RANGE_WIDING_FACTOR = 1.2, @@ -117,8 +117,8 @@ export class HeatmapRenderer { } getYAxisWidth(elem) { - let axis_text = elem.selectAll('.axis-y text').nodes(); - let max_text_width = _.max( + const axis_text = elem.selectAll('.axis-y text').nodes(); + const max_text_width = _.max( _.map(axis_text, text => { // Use SVG getBBox method return text.getBBox().width; @@ -129,10 +129,10 @@ export class HeatmapRenderer { } getXAxisHeight(elem) { - let axis_line = elem.select('.axis-x line'); + const axis_line = elem.select('.axis-x line'); if (!axis_line.empty()) { - let axis_line_position = parseFloat(elem.select('.axis-x line').attr('y2')); - let canvas_width = parseFloat(elem.attr('height')); + const axis_line_position = parseFloat(elem.select('.axis-x line').attr('y2')); + const canvas_width = parseFloat(elem.attr('height')); return canvas_width - axis_line_position; } else { // Default height @@ -146,25 +146,25 @@ export class HeatmapRenderer { .domain([this.timeRange.from, this.timeRange.to]) .range([0, this.chartWidth]); - let ticks = this.chartWidth / DEFAULT_X_TICK_SIZE_PX; - let grafanaTimeFormatter = ticksUtils.grafanaTimeFormat(ticks, this.timeRange.from, this.timeRange.to); + const ticks = this.chartWidth / DEFAULT_X_TICK_SIZE_PX; + const grafanaTimeFormatter = ticksUtils.grafanaTimeFormat(ticks, this.timeRange.from, this.timeRange.to); let timeFormat; - let dashboardTimeZone = this.ctrl.dashboard.getTimezone(); + const dashboardTimeZone = this.ctrl.dashboard.getTimezone(); if (dashboardTimeZone === 'utc') { timeFormat = d3.utcFormat(grafanaTimeFormatter); } else { timeFormat = d3.timeFormat(grafanaTimeFormatter); } - let xAxis = d3 + const xAxis = d3 .axisBottom(this.xScale) .ticks(ticks) .tickFormat(timeFormat) .tickPadding(X_AXIS_TICK_PADDING) .tickSize(this.chartHeight); - let posY = this.margin.top; - let posX = this.yAxisWidth; + const posY = this.margin.top; + const posX = this.yAxisWidth; this.heatmap .append('g') .attr('class', 'axis axis-x') @@ -191,11 +191,11 @@ export class HeatmapRenderer { tick_interval = ticksUtils.tickStep(y_min, y_max, ticks); ticks = Math.ceil((y_max - y_min) / tick_interval); - let decimalsAuto = ticksUtils.getPrecision(tick_interval); + const decimalsAuto = ticksUtils.getPrecision(tick_interval); let decimals = this.panel.yAxis.decimals === null ? decimalsAuto : this.panel.yAxis.decimals; // Calculate scaledDecimals for log scales using tick size (as in jquery.flot.js) - let flot_tick_size = ticksUtils.getFlotTickSize(y_min, y_max, ticks, decimalsAuto); - let scaledDecimals = ticksUtils.getScaledDecimals(decimals, flot_tick_size); + const flot_tick_size = ticksUtils.getFlotTickSize(y_min, y_max, ticks, decimalsAuto); + const scaledDecimals = ticksUtils.getScaledDecimals(decimals, flot_tick_size); this.ctrl.decimals = decimals; this.ctrl.scaledDecimals = scaledDecimals; @@ -218,7 +218,7 @@ export class HeatmapRenderer { .domain([y_min, y_max]) .range([this.chartHeight, 0]); - let yAxis = d3 + const yAxis = d3 .axisLeft(this.yScale) .ticks(ticks) .tickFormat(this.tickValueFormatter(decimals, scaledDecimals)) @@ -232,8 +232,8 @@ export class HeatmapRenderer { .call(yAxis); // Calculate Y axis width first, then move axis into visible area - let posY = this.margin.top; - let posX = this.getYAxisWidth(this.heatmap) + Y_AXIS_TICK_PADDING; + const posY = this.margin.top; + const posX = this.getYAxisWidth(this.heatmap) + Y_AXIS_TICK_PADDING; this.heatmap.select('.axis-y').attr('transform', 'translate(' + posX + ',' + posY + ')'); // Remove vertical line in the right of axis labels (called domain in d3) @@ -245,7 +245,7 @@ export class HeatmapRenderer { // Wide Y values range and anjust to bucket size wideYAxisRange(min, max, tickInterval) { - let y_widing = (max * (this.dataRangeWidingFactor - 1) - min * (this.dataRangeWidingFactor - 1)) / 2; + const y_widing = (max * (this.dataRangeWidingFactor - 1) - min * (this.dataRangeWidingFactor - 1)) / 2; let y_min, y_max; if (tickInterval === 0) { @@ -266,7 +266,7 @@ export class HeatmapRenderer { } addLogYAxis() { - let log_base = this.panel.yAxis.logBase; + const log_base = this.panel.yAxis.logBase; let { y_min, y_max } = this.adjustLogRange(this.data.heatmapStats.minLog, this.data.heatmapStats.max, log_base); y_min = @@ -285,15 +285,15 @@ export class HeatmapRenderer { .domain([y_min, y_max]) .range([this.chartHeight, 0]); - let domain = this.yScale.domain(); - let tick_values = this.logScaleTickValues(domain, log_base); + const domain = this.yScale.domain(); + const tick_values = this.logScaleTickValues(domain, log_base); - let decimalsAuto = ticksUtils.getPrecision(y_min); - let decimals = this.panel.yAxis.decimals || decimalsAuto; + const decimalsAuto = ticksUtils.getPrecision(y_min); + const decimals = this.panel.yAxis.decimals || decimalsAuto; // Calculate scaledDecimals for log scales using tick size (as in jquery.flot.js) - let flot_tick_size = ticksUtils.getFlotTickSize(y_min, y_max, tick_values.length, decimalsAuto); - let scaledDecimals = ticksUtils.getScaledDecimals(decimals, flot_tick_size); + const flot_tick_size = ticksUtils.getFlotTickSize(y_min, y_max, tick_values.length, decimalsAuto); + const scaledDecimals = ticksUtils.getScaledDecimals(decimals, flot_tick_size); this.ctrl.decimals = decimals; this.ctrl.scaledDecimals = scaledDecimals; @@ -303,7 +303,7 @@ export class HeatmapRenderer { ticks: tick_values.length, }; - let yAxis = d3 + const yAxis = d3 .axisLeft(this.yScale) .tickValues(tick_values) .tickFormat(this.tickValueFormatter(decimals, scaledDecimals)) @@ -317,8 +317,8 @@ export class HeatmapRenderer { .call(yAxis); // Calculate Y axis width first, then move axis into visible area - let posY = this.margin.top; - let posX = this.getYAxisWidth(this.heatmap) + Y_AXIS_TICK_PADDING; + const posY = this.margin.top; + const posX = this.getYAxisWidth(this.heatmap) + Y_AXIS_TICK_PADDING; this.heatmap.select('.axis-y').attr('transform', 'translate(' + posX + ',' + posY + ')'); // Set first tick as pseudo 0 @@ -349,7 +349,7 @@ export class HeatmapRenderer { const decimals = this.panel.yAxis.decimals === null ? decimalsAuto : this.panel.yAxis.decimals; this.ctrl.decimals = decimals; - let tickValueFormatter = this.tickValueFormatter.bind(this); + const tickValueFormatter = this.tickValueFormatter.bind(this); function tickFormatter(valIndex) { let valueFormatted = tsBuckets[valIndex]; if (!_.isNaN(_.toNumber(valueFormatted)) && valueFormatted !== '') { @@ -362,7 +362,7 @@ export class HeatmapRenderer { const tsBucketsFormatted = _.map(tsBuckets, (v, i) => tickFormatter(i)); this.data.tsBucketsFormatted = tsBucketsFormatted; - let yAxis = d3 + const yAxis = d3 .axisLeft(this.yScale) .tickValues(tick_values) .tickFormat(tickFormatter) @@ -413,21 +413,21 @@ export class HeatmapRenderer { } logScaleTickValues(domain, base) { - let domainMin = domain[0]; - let domainMax = domain[1]; - let tickValues = []; + const domainMin = domain[0]; + const domainMax = domain[1]; + const tickValues = []; if (domainMin < 1) { - let under_one_ticks = Math.floor(ticksUtils.logp(domainMin, base)); + const under_one_ticks = Math.floor(ticksUtils.logp(domainMin, base)); for (let i = under_one_ticks; i < 0; i++) { - let tick_value = Math.pow(base, i); + const tick_value = Math.pow(base, i); tickValues.push(tick_value); } } - let ticks = Math.ceil(ticksUtils.logp(domainMax, base)); + const ticks = Math.ceil(ticksUtils.logp(domainMax, base)); for (let i = 0; i <= ticks; i++) { - let tick_value = Math.pow(base, i); + const tick_value = Math.pow(base, i); tickValues.push(tick_value); } @@ -435,7 +435,7 @@ export class HeatmapRenderer { } tickValueFormatter(decimals, scaledDecimals = null) { - let format = this.panel.yAxis.format; + const format = this.panel.yAxis.format; return function(value) { try { return format !== 'none' ? kbn.valueFormats[format](value, decimals, scaledDecimals) : value; @@ -490,7 +490,7 @@ export class HeatmapRenderer { } addHeatmapCanvas() { - let heatmap_elem = this.$heatmap[0]; + const heatmap_elem = this.$heatmap[0]; this.width = Math.floor(this.$heatmap.width()) - this.padding.right; this.height = Math.floor(this.$heatmap.height()) - this.padding.bottom; @@ -514,18 +514,18 @@ export class HeatmapRenderer { this.addAxes(); if (this.panel.yAxis.logBase !== 1 && this.panel.dataFormat !== 'tsbuckets') { - let log_base = this.panel.yAxis.logBase; - let domain = this.yScale.domain(); - let tick_values = this.logScaleTickValues(domain, log_base); + const log_base = this.panel.yAxis.logBase; + const domain = this.yScale.domain(); + const tick_values = this.logScaleTickValues(domain, log_base); this.data.buckets = mergeZeroBuckets(this.data.buckets, _.min(tick_values)); } - let cardsData = this.data.cards; - let maxValueAuto = this.data.cardStats.max; - let maxValue = this.panel.color.max || maxValueAuto; - let minValue = this.panel.color.min || 0; + const cardsData = this.data.cards; + const maxValueAuto = this.data.cardStats.max; + const maxValue = this.panel.color.max || maxValueAuto; + const minValue = this.panel.color.min || 0; - let colorScheme = _.find(this.ctrl.colorSchemes, { + const colorScheme = _.find(this.ctrl.colorSchemes, { value: this.panel.color.colorScheme, }); this.colorScale = getColorScale(colorScheme, contextSrv.user.lightTheme, maxValue, minValue); @@ -549,7 +549,7 @@ export class HeatmapRenderer { .style('stroke-width', 0) .style('opacity', this.getCardOpacity.bind(this)); - let $cards = this.$heatmap.find('.heatmap-card'); + const $cards = this.$heatmap.find('.heatmap-card'); $cards .on('mouseenter', event => { this.tooltip.mouseOverBucket = true; @@ -562,10 +562,10 @@ export class HeatmapRenderer { } highlightCard(event) { - let color = d3.select(event.target).style('fill'); - let highlightColor = d3.color(color).darker(2); - let strokeColor = d3.color(color).brighter(4); - let current_card = d3.select(event.target); + const color = d3.select(event.target).style('fill'); + const highlightColor = d3.color(color).darker(2); + const strokeColor = d3.color(color).brighter(4); + const current_card = d3.select(event.target); this.tooltip.originalFillColor = color; current_card .style('fill', highlightColor.toString()) @@ -582,12 +582,12 @@ export class HeatmapRenderer { } setCardSize() { - let xGridSize = Math.floor(this.xScale(this.data.xBucketSize) - this.xScale(0)); + const xGridSize = Math.floor(this.xScale(this.data.xBucketSize) - this.xScale(0)); let yGridSize = Math.floor(this.yScale(this.yScale.invert(0) - this.data.yBucketSize)); if (this.panel.yAxis.logBase !== 1) { - let base = this.panel.yAxis.logBase; - let splitFactor = this.data.yBucketSize || 1; + const base = this.panel.yAxis.logBase; + const splitFactor = this.data.yBucketSize || 1; yGridSize = Math.floor((this.yScale(1) - this.yScale(base)) / splitFactor); } @@ -611,7 +611,7 @@ export class HeatmapRenderer { let w; if (this.xScale(d.x) < 0) { // Cut card left to prevent overlay - let cutted_width = this.xScale(d.x) + this.cardWidth; + const cutted_width = this.xScale(d.x) + this.cardWidth; w = cutted_width > 0 ? cutted_width : 0; } else if (this.xScale(d.x) + this.cardWidth > this.chartWidth) { // Cut card right to prevent overlay @@ -639,7 +639,7 @@ export class HeatmapRenderer { } getCardHeight(d) { - let y = this.yScale(d.y) + this.chartTop - this.cardHeight - this.cardPadding; + const y = this.yScale(d.y) + this.chartTop - this.cardHeight - this.cardPadding; let h = this.cardHeight; if (this.panel.yAxis.logBase !== 1 && d.y === 0) { @@ -703,10 +703,10 @@ export class HeatmapRenderer { this.mouseUpHandler = null; this.selection.active = false; - let selectionRange = Math.abs(this.selection.x2 - this.selection.x1); + const selectionRange = Math.abs(this.selection.x2 - this.selection.x1); if (this.selection.x2 >= 0 && selectionRange > MIN_SELECTION_WIDTH) { - let timeFrom = this.xScale.invert(Math.min(this.selection.x1, this.selection.x2) - this.yAxisWidth); - let timeTo = this.xScale.invert(Math.max(this.selection.x1, this.selection.x2) - this.yAxisWidth); + const timeFrom = this.xScale.invert(Math.min(this.selection.x1, this.selection.x2) - this.yAxisWidth); + const timeTo = this.xScale.invert(Math.max(this.selection.x1, this.selection.x2) - this.yAxisWidth); this.ctrl.timeSrv.setTime({ from: moment.utc(timeFrom), @@ -744,9 +744,9 @@ export class HeatmapRenderer { } getEventPos(event, offset) { - let x = this.xScale.invert(offset.x - this.yAxisWidth).valueOf(); - let y = this.yScale.invert(offset.y - this.chartTop); - let pos = { + const x = this.xScale.invert(offset.x - this.yAxisWidth).valueOf(); + const y = this.yScale.invert(offset.y - this.chartTop); + const pos = { pageX: event.pageX, pageY: event.pageY, x: x, @@ -776,8 +776,8 @@ export class HeatmapRenderer { drawSelection(posX1, posX2) { if (this.heatmap) { this.heatmap.selectAll('.heatmap-selection').remove(); - let selectionX = Math.min(posX1, posX2); - let selectionWidth = Math.abs(posX1 - posX2); + const selectionX = Math.min(posX1, posX2); + const selectionWidth = Math.abs(posX1 - posX2); if (selectionWidth > MIN_SELECTION_WIDTH) { this.heatmap @@ -823,7 +823,7 @@ export class HeatmapRenderer { drawSharedCrosshair(pos) { if (this.heatmap && this.ctrl.dashboard.graphTooltip !== 0) { - let posX = this.xScale(pos.x) + this.yAxisWidth; + const posX = this.xScale(pos.x) + this.yAxisWidth; this.drawCrosshair(posX); } } diff --git a/public/app/plugins/panel/heatmap/specs/heatmap_ctrl.test.ts b/public/app/plugins/panel/heatmap/specs/heatmap_ctrl.test.ts index 800c2518f9a..d9d929a2697 100644 --- a/public/app/plugins/panel/heatmap/specs/heatmap_ctrl.test.ts +++ b/public/app/plugins/panel/heatmap/specs/heatmap_ctrl.test.ts @@ -2,13 +2,13 @@ import moment from 'moment'; import { HeatmapCtrl } from '../heatmap_ctrl'; describe('HeatmapCtrl', function() { - let ctx = {}; + const ctx = {}; - let $injector = { + const $injector = { get: () => {}, }; - let $scope = { + const $scope = { $on: () => {}, }; diff --git a/public/app/plugins/panel/heatmap/specs/heatmap_data_converter.test.ts b/public/app/plugins/panel/heatmap/specs/heatmap_data_converter.test.ts index b6a8713a3e9..1c8a7a32caf 100644 --- a/public/app/plugins/panel/heatmap/specs/heatmap_data_converter.test.ts +++ b/public/app/plugins/panel/heatmap/specs/heatmap_data_converter.test.ts @@ -10,7 +10,7 @@ import { } from '../heatmap_data_converter'; describe('isHeatmapDataEqual', () => { - let ctx: any = {}; + const ctx: any = {}; beforeEach(() => { ctx.heatmapA = { @@ -35,17 +35,17 @@ describe('isHeatmapDataEqual', () => { }); it('should proper compare objects', () => { - let heatmapC = _.cloneDeep(ctx.heatmapA); + const heatmapC = _.cloneDeep(ctx.heatmapA); heatmapC['1422774000000'].buckets['1'].values = [1, 1.5]; - let heatmapD = _.cloneDeep(ctx.heatmapA); + const heatmapD = _.cloneDeep(ctx.heatmapA); heatmapD['1422774000000'].buckets['1'].values = [1.5, 1, 1.6]; - let heatmapE = _.cloneDeep(ctx.heatmapA); + const heatmapE = _.cloneDeep(ctx.heatmapA); heatmapE['1422774000000'].buckets['1'].values = [1, 1.6]; - let empty = {}; - let emptyValues = _.cloneDeep(ctx.heatmapA); + const empty = {}; + const emptyValues = _.cloneDeep(ctx.heatmapA); emptyValues['1422774000000'].buckets['1'].values = []; expect(isHeatmapDataEqual(ctx.heatmapA, ctx.heatmapB)).toBe(true); @@ -69,7 +69,7 @@ describe('isHeatmapDataEqual', () => { }); describe('calculateBucketSize', () => { - let ctx: any = {}; + const ctx: any = {}; describe('when logBase is 1 (linear scale)', () => { beforeEach(() => { @@ -88,7 +88,7 @@ describe('calculateBucketSize', () => { it('should properly calculate bucket size', () => { _.each(ctx.bounds_set, b => { - let bucketSize = calculateBucketSize(b.bounds, ctx.logBase); + const bucketSize = calculateBucketSize(b.bounds, ctx.logBase); expect(bucketSize).toBe(b.size); }); }); @@ -108,7 +108,7 @@ describe('calculateBucketSize', () => { it('should properly calculate bucket size', () => { _.each(ctx.bounds_set, b => { - let bucketSize = calculateBucketSize(b.bounds, ctx.logBase); + const bucketSize = calculateBucketSize(b.bounds, ctx.logBase); expect(isEqual(bucketSize, b.size)).toBe(true); }); }); @@ -116,7 +116,7 @@ describe('calculateBucketSize', () => { }); describe('HeatmapDataConverter', () => { - let ctx: any = {}; + const ctx: any = {}; beforeEach(() => { ctx.series = []; @@ -150,7 +150,7 @@ describe('HeatmapDataConverter', () => { }); it('should build proper heatmap data', () => { - let expectedHeatmap = { + const expectedHeatmap = { '1422774000000': { x: 1422774000000, buckets: { @@ -183,7 +183,7 @@ describe('HeatmapDataConverter', () => { }, }; - let heatmap = convertToHeatMap(ctx.series, ctx.yBucketSize, ctx.xBucketSize, ctx.logBase); + const heatmap = convertToHeatMap(ctx.series, ctx.yBucketSize, ctx.xBucketSize, ctx.logBase); expect(isHeatmapDataEqual(heatmap, expectedHeatmap)).toBe(true); }); }); @@ -194,7 +194,7 @@ describe('HeatmapDataConverter', () => { }); it('should build proper heatmap data', () => { - let expectedHeatmap = { + const expectedHeatmap = { '1422774000000': { x: 1422774000000, buckets: { @@ -210,14 +210,14 @@ describe('HeatmapDataConverter', () => { }, }; - let heatmap = convertToHeatMap(ctx.series, ctx.yBucketSize, ctx.xBucketSize, ctx.logBase); + const heatmap = convertToHeatMap(ctx.series, ctx.yBucketSize, ctx.xBucketSize, ctx.logBase); expect(isHeatmapDataEqual(heatmap, expectedHeatmap)).toBe(true); }); }); }); describe('Histogram converter', () => { - let ctx: any = {}; + const ctx: any = {}; beforeEach(() => { ctx.series = []; @@ -248,7 +248,7 @@ describe('Histogram converter', () => { beforeEach(() => {}); it('should build proper heatmap data', () => { - let expectedHeatmap = { + const expectedHeatmap = { '1422774000000': { x: 1422774000000, buckets: { @@ -343,18 +343,18 @@ describe('convertToCards', () => { }); it('should build proper cards data', () => { - let expectedCards = [ + const expectedCards = [ { x: 1422774000000, y: 1, count: 1, values: [1], yBounds: {} }, { x: 1422774000000, y: 2, count: 1, values: [2], yBounds: {} }, { x: 1422774060000, y: 2, count: 2, values: [2, 3], yBounds: {} }, ]; - let res = convertToCards(buckets); + const res = convertToCards(buckets); expect(res.cards).toMatchObject(expectedCards); }); it('should build proper cards stats', () => { - let expectedStats = { min: 1, max: 2 }; - let res = convertToCards(buckets); + const expectedStats = { min: 1, max: 2 }; + const res = convertToCards(buckets); expect(res.cardStats).toMatchObject(expectedStats); }); }); diff --git a/public/app/plugins/panel/pluginlist/module.ts b/public/app/plugins/panel/pluginlist/module.ts index acfa69b171c..93bf258f50d 100644 --- a/public/app/plugins/panel/pluginlist/module.ts +++ b/public/app/plugins/panel/pluginlist/module.ts @@ -60,7 +60,7 @@ class PluginListCtrl extends PanelCtrl { this.viewModel[1].list = _.filter(plugins, { type: 'panel' }); this.viewModel[2].list = _.filter(plugins, { type: 'datasource' }); - for (let plugin of this.pluginList) { + for (const plugin of this.pluginList) { if (plugin.hasUpdate) { plugin.state = 'has-update'; } else if (!plugin.enabled) { diff --git a/public/app/plugins/panel/singlestat/module.ts b/public/app/plugins/panel/singlestat/module.ts index ebd2628b086..b858f77556f 100644 --- a/public/app/plugins/panel/singlestat/module.ts +++ b/public/app/plugins/panel/singlestat/module.ts @@ -293,8 +293,8 @@ class SingleStatCtrl extends MetricsPanelCtrl { } if (this.series && this.series.length > 0) { - let lastPoint = _.last(this.series[0].datapoints); - let lastValue = _.isArray(lastPoint) ? lastPoint[0] : null; + const lastPoint = _.last(this.series[0].datapoints); + const lastValue = _.isArray(lastPoint) ? lastPoint[0] : null; if (this.panel.valueName === 'name') { data.value = 0; @@ -305,7 +305,7 @@ class SingleStatCtrl extends MetricsPanelCtrl { data.valueFormatted = _.escape(lastValue); data.valueRounded = 0; } else if (this.panel.valueName === 'last_time') { - let formatFunc = kbn.valueFormats[this.panel.format]; + const formatFunc = kbn.valueFormats[this.panel.format]; data.value = lastPoint[1]; data.valueRounded = data.value; data.valueFormatted = formatFunc(data.value, this.dashboard.isTimezoneUtc()); @@ -313,8 +313,8 @@ class SingleStatCtrl extends MetricsPanelCtrl { data.value = this.series[0].stats[this.panel.valueName]; data.flotpairs = this.series[0].flotpairs; - let decimalInfo = this.getDecimalsForValue(data.value); - let formatFunc = kbn.valueFormats[this.panel.format]; + const decimalInfo = this.getDecimalsForValue(data.value); + const formatFunc = kbn.valueFormats[this.panel.format]; data.valueFormatted = formatFunc(data.value, decimalInfo.decimals, decimalInfo.scaledDecimals); data.valueRounded = kbn.roundValue(data.value, decimalInfo.decimals); } @@ -330,7 +330,7 @@ class SingleStatCtrl extends MetricsPanelCtrl { // check value to text mappings if its enabled if (this.panel.mappingType === 1) { for (let i = 0; i < this.panel.valueMaps.length; i++) { - let map = this.panel.valueMaps[i]; + const map = this.panel.valueMaps[i]; // special null case if (map.value === 'null') { if (data.value === null || data.value === void 0) { @@ -349,7 +349,7 @@ class SingleStatCtrl extends MetricsPanelCtrl { } } else if (this.panel.mappingType === 2) { for (let i = 0; i < this.panel.rangeMaps.length; i++) { - let map = this.panel.rangeMaps[i]; + const map = this.panel.rangeMaps[i]; // special null case if (map.from === 'null' && map.to === 'null') { if (data.value === null || data.value === void 0) { diff --git a/public/app/plugins/panel/singlestat/specs/singlestat.test.ts b/public/app/plugins/panel/singlestat/specs/singlestat.test.ts index 0480d0be5c3..9d204f19f5b 100644 --- a/public/app/plugins/panel/singlestat/specs/singlestat.test.ts +++ b/public/app/plugins/panel/singlestat/specs/singlestat.test.ts @@ -2,15 +2,15 @@ import { SingleStatCtrl } from '../module'; import moment from 'moment'; describe('SingleStatCtrl', function() { - let ctx = {}; - let epoch = 1505826363746; + const ctx = {}; + const epoch = 1505826363746; Date.now = () => epoch; - let $scope = { + const $scope = { $on: () => {}, }; - let $injector = { + const $injector = { get: () => {}, }; diff --git a/public/app/plugins/panel/table/module.ts b/public/app/plugins/panel/table/module.ts index 03d92f7e48f..4169a25dd43 100644 --- a/public/app/plugins/panel/table/module.ts +++ b/public/app/plugins/panel/table/module.ts @@ -243,7 +243,7 @@ class TablePanelCtrl extends MetricsPanelCtrl { }); function addFilterClicked(e) { - let filterData = $(e.currentTarget).data(); + const filterData = $(e.currentTarget).data(); var options = { datasource: panel.datasource, key: data.columns[filterData.column].text, diff --git a/public/app/plugins/panel/table/renderer.ts b/public/app/plugins/panel/table/renderer.ts index d85c20a87cc..d512c1335df 100644 --- a/public/app/plugins/panel/table/renderer.ts +++ b/public/app/plugins/panel/table/renderer.ts @@ -21,11 +21,11 @@ export class TableRenderer { this.colorState = {}; for (let colIndex = 0; colIndex < this.table.columns.length; colIndex++) { - let column = this.table.columns[colIndex]; + const column = this.table.columns[colIndex]; column.title = column.text; for (let i = 0; i < this.panel.styles.length; i++) { - let style = this.panel.styles[i]; + const style = this.panel.styles[i]; var regex = kbn.stringToJsRegex(style.pattern); if (column.text.match(regex)) { @@ -154,7 +154,7 @@ export class TableRenderer { } if (column.style.type === 'number') { - let valueFormatter = kbn.valueFormats[column.unit || column.style.unit]; + const valueFormatter = kbn.valueFormats[column.unit || column.style.unit]; return v => { if (v === null || v === void 0) { @@ -193,9 +193,9 @@ export class TableRenderer { } renderRowVariables(rowIndex) { - let scopedVars = {}; + const scopedVars = {}; let cell_variable; - let row = this.table.rows[rowIndex]; + const row = this.table.rows[rowIndex]; for (let i = 0; i < row.length; i++) { cell_variable = `__cell_${i}`; scopedVars[cell_variable] = { value: row[i] }; @@ -288,15 +288,15 @@ export class TableRenderer { } render(page) { - let pageSize = this.panel.pageSize || 100; - let startPos = page * pageSize; - let endPos = Math.min(startPos + pageSize, this.table.rows.length); + const pageSize = this.panel.pageSize || 100; + const startPos = page * pageSize; + const endPos = Math.min(startPos + pageSize, this.table.rows.length); var html = ''; - let rowClasses = []; + const rowClasses = []; let rowClass = ''; for (var y = startPos; y < endPos; y++) { - let row = this.table.rows[y]; + const row = this.table.rows[y]; let cellHtml = ''; let rowStyle = ''; for (var i = 0; i < this.table.columns.length; i++) { @@ -320,11 +320,11 @@ export class TableRenderer { } render_values() { - let rows = []; + const rows = []; for (var y = 0; y < this.table.rows.length; y++) { - let row = this.table.rows[y]; - let new_row = []; + const row = this.table.rows[y]; + const new_row = []; for (var i = 0; i < this.table.columns.length; i++) { new_row.push(this.formatColumnValue(i, row[i])); } diff --git a/public/app/plugins/panel/table/transformers.ts b/public/app/plugins/panel/table/transformers.ts index 1659ba3e3aa..840bfa83d5b 100644 --- a/public/app/plugins/panel/table/transformers.ts +++ b/public/app/plugins/panel/table/transformers.ts @@ -294,7 +294,7 @@ transformers['json'] = { transform: function(data, panel, model) { var i, y, z; - for (let column of panel.columns) { + for (const column of panel.columns) { var tableCol: any = { text: column.text }; // if filterable data then set columns to filterable diff --git a/public/app/stores/AlertListStore/AlertListStore.ts b/public/app/stores/AlertListStore/AlertListStore.ts index ec27565a1a1..c2b9f5e4962 100644 --- a/public/app/stores/AlertListStore/AlertListStore.ts +++ b/public/app/stores/AlertListStore/AlertListStore.ts @@ -13,7 +13,7 @@ export const AlertListStore = types }) .views(self => ({ get filteredRules() { - let regex = new RegExp(self.search, 'i'); + const regex = new RegExp(self.search, 'i'); return self.rules.filter(alert => { return regex.test(alert.name) || regex.test(alert.stateText) || regex.test(alert.info); }); @@ -26,7 +26,7 @@ export const AlertListStore = types const apiRules = yield backendSrv.get('/api/alerts', filters); self.rules.clear(); - for (let rule of apiRules) { + for (const rule of apiRules) { setStateFields(rule, rule.state); if (rule.state !== 'paused') { diff --git a/public/app/stores/NavStore/NavStore.ts b/public/app/stores/NavStore/NavStore.ts index bef53b828b6..d869b0f740d 100644 --- a/public/app/stores/NavStore/NavStore.ts +++ b/public/app/stores/NavStore/NavStore.ts @@ -12,9 +12,9 @@ export const NavStore = types load(...args) { let children = getEnv(self).navTree; let main, node; - let parents = []; + const parents = []; - for (let id of args) { + for (const id of args) { node = children.find(el => el.id === id); if (!node) { @@ -28,7 +28,7 @@ export const NavStore = types main = parents[parents.length - 2]; if (main.children) { - for (let item of main.children) { + for (const item of main.children) { item.active = false; if (item.url === node.url) { @@ -42,7 +42,7 @@ export const NavStore = types }, initFolderNav(folder: any, activeChildId: string) { - let main = { + const main = { icon: 'fa fa-folder-open', id: 'manage-folder', subTitle: 'Manage folder dashboards & permissions', @@ -79,13 +79,13 @@ export const NavStore = types initDatasourceEditNav(ds: any, plugin: any, currentPage: string) { let title = 'New'; - let subTitle = `Type: ${plugin.name}`; + const subTitle = `Type: ${plugin.name}`; if (ds.id) { title = ds.name; } - let main = { + const main = { img: plugin.info.logos.large, id: 'ds-edit-' + plugin.id, subTitle: subTitle, @@ -118,7 +118,7 @@ export const NavStore = types }, initTeamPage(team: Team, tab: string, isSyncEnabled: boolean) { - let main = { + const main = { img: team.avatarUrl, id: 'team-' + team.id, subTitle: 'Manage members & settings', diff --git a/public/app/stores/PermissionsStore/PermissionsStore.ts b/public/app/stores/PermissionsStore/PermissionsStore.ts index 95d63c8527a..d778a09443d 100644 --- a/public/app/stores/PermissionsStore/PermissionsStore.ts +++ b/public/app/stores/PermissionsStore/PermissionsStore.ts @@ -117,7 +117,7 @@ export const PermissionsStore = types }), addStoreItem: flow(function* addStoreItem() { - let item = { + const item = { type: self.newItem.type, permission: self.newItem.permission, dashboardId: self.dashboardId, @@ -155,7 +155,7 @@ export const PermissionsStore = types try { yield updateItems(self, updatedItems); self.items.push(newItem); - let sortedItems = self.items.sort((a, b) => b.sortRank - a.sortRank || a.name.localeCompare(b.name)); + const sortedItems = self.items.sort((a, b) => b.sortRank - a.sortRank || a.name.localeCompare(b.name)); self.items = sortedItems; resetNewTypeInternal(); } catch {} @@ -197,7 +197,7 @@ export const PermissionsStore = types const updateItems = (self, items) => { const backendSrv = getEnv(self).backendSrv; const updated = []; - for (let item of items) { + for (const item of items) { if (item.inherited) { continue; } diff --git a/public/app/stores/TeamsStore/TeamsStore.ts b/public/app/stores/TeamsStore/TeamsStore.ts index 1aec4a1433c..f8e101163a2 100644 --- a/public/app/stores/TeamsStore/TeamsStore.ts +++ b/public/app/stores/TeamsStore/TeamsStore.ts @@ -32,8 +32,8 @@ export const TeamModel = types }) .views(self => ({ get filteredMembers() { - let members = this.members.values(); - let regex = new RegExp(self.search, 'i'); + const members = this.members.values(); + const regex = new RegExp(self.search, 'i'); return members.filter(member => { return regex.test(member.login) || regex.test(member.email); }); @@ -66,7 +66,7 @@ export const TeamModel = types const rsp = yield backendSrv.get(`/api/teams/${self.id}/members`); self.members.clear(); - for (let member of rsp) { + for (const member of rsp) { self.members.set(member.userId.toString(), TeamMemberModel.create(member)); } }), @@ -88,7 +88,7 @@ export const TeamModel = types const rsp = yield backendSrv.get(`/api/teams/${self.id}/groups`); self.groups.clear(); - for (let group of rsp) { + for (const group of rsp) { self.groups.set(group.groupId, TeamGroupModel.create(group)); } }), @@ -122,8 +122,8 @@ export const TeamsStore = types }) .views(self => ({ get filteredTeams() { - let teams = this.map.values(); - let regex = new RegExp(self.search, 'i'); + const teams = this.map.values(); + const regex = new RegExp(self.search, 'i'); return teams.filter(team => { return regex.test(team.name); }); @@ -135,7 +135,7 @@ export const TeamsStore = types const rsp = yield backendSrv.get('/api/teams/search/', { perpage: 50, page: 1 }); self.map.clear(); - for (let team of rsp.teams) { + for (const team of rsp.teams) { self.map.set(team.id.toString(), TeamModel.create(team)); } }), diff --git a/public/app/stores/ViewStore/ViewStore.ts b/public/app/stores/ViewStore/ViewStore.ts index ba966a194d8..3af6737209c 100644 --- a/public/app/stores/ViewStore/ViewStore.ts +++ b/public/app/stores/ViewStore/ViewStore.ts @@ -25,7 +25,7 @@ export const ViewStore = types // querystring only function updateQuery(query: any) { self.query.clear(); - for (let key of Object.keys(query)) { + for (const key of Object.keys(query)) { if (query[key]) { self.query.set(key, query[key]); } @@ -35,7 +35,7 @@ export const ViewStore = types // needed to get route parameters like slug from the url function updateRouteParams(routeParams: any) { self.routeParams.clear(); - for (let key of Object.keys(routeParams)) { + for (const key of Object.keys(routeParams)) { if (routeParams[key]) { self.routeParams.set(key, routeParams[key]); } diff --git a/public/test/core/utils/version_test.ts b/public/test/core/utils/version_test.ts index 20983cb32ec..91330389e24 100644 --- a/public/test/core/utils/version_test.ts +++ b/public/test/core/utils/version_test.ts @@ -1,11 +1,11 @@ -import {SemVersion, isVersionGtOrEq} from 'app/core/utils/version'; +import { SemVersion, isVersionGtOrEq } from 'app/core/utils/version'; -describe("SemVersion", () => { +describe('SemVersion', () => { let version = '1.0.0-alpha.1'; describe('parsing', () => { it('should parse version properly', () => { - let semver = new SemVersion(version); + const semver = new SemVersion(version); expect(semver.major).toBe(1); expect(semver.minor).toBe(0); expect(semver.patch).toBe(0); @@ -19,15 +19,15 @@ describe("SemVersion", () => { }); it('should detect greater version properly', () => { - let semver = new SemVersion(version); - let cases = [ - {value: '3.4.5', expected: true}, - {value: '3.4.4', expected: true}, - {value: '3.4.6', expected: false}, - {value: '4', expected: false}, - {value: '3.5', expected: false}, + const semver = new SemVersion(version); + const cases = [ + { value: '3.4.5', expected: true }, + { value: '3.4.4', expected: true }, + { value: '3.4.6', expected: false }, + { value: '4', expected: false }, + { value: '3.5', expected: false }, ]; - cases.forEach((testCase) => { + cases.forEach(testCase => { expect(semver.isGtOrEq(testCase.value)).toBe(testCase.expected); }); }); @@ -35,17 +35,17 @@ describe("SemVersion", () => { describe('isVersionGtOrEq', () => { it('should compare versions properly (a >= b)', () => { - let cases = [ - {values: ['3.4.5', '3.4.5'], expected: true}, - {values: ['3.4.5', '3.4.4'] , expected: true}, - {values: ['3.4.5', '3.4.6'], expected: false}, - {values: ['3.4', '3.4.0'], expected: true}, - {values: ['3', '3.0.0'], expected: true}, - {values: ['3.1.1-beta1', '3.1'], expected: true}, - {values: ['3.4.5', '4'], expected: false}, - {values: ['3.4.5', '3.5'], expected: false}, + const cases = [ + { values: ['3.4.5', '3.4.5'], expected: true }, + { values: ['3.4.5', '3.4.4'], expected: true }, + { values: ['3.4.5', '3.4.6'], expected: false }, + { values: ['3.4', '3.4.0'], expected: true }, + { values: ['3', '3.0.0'], expected: true }, + { values: ['3.1.1-beta1', '3.1'], expected: true }, + { values: ['3.4.5', '4'], expected: false }, + { values: ['3.4.5', '3.5'], expected: false }, ]; - cases.forEach((testCase) => { + cases.forEach(testCase => { expect(isVersionGtOrEq(testCase.values[0], testCase.values[1])).toBe(testCase.expected); }); }); diff --git a/public/test/index.ts b/public/test/index.ts index 33f24331b67..05a47686775 100644 --- a/public/test/index.ts +++ b/public/test/index.ts @@ -22,10 +22,6 @@ angular.module('grafana.filters', []); angular.module('grafana.routes', ['ngRoute']); const context = (require).context('../', true, /specs\.(tsx?|js)/); -for (let key of context.keys()) { +for (const key of context.keys()) { context(key); } - - - - diff --git a/public/test/mocks/common.ts b/public/test/mocks/common.ts index 1531f2ed176..64d12fdf725 100644 --- a/public/test/mocks/common.ts +++ b/public/test/mocks/common.ts @@ -7,10 +7,10 @@ export const backendSrv = { }; export function createNavTree(...args) { - let root = []; + const root = []; let node = root; - for (let arg of args) { - let child = { id: arg, url: `/url/${arg}`, text: `${arg}-Text`, children: [] }; + for (const arg of args) { + const child = { id: arg, url: `/url/${arg}`, text: `${arg}-Text`, children: [] }; node.push(child); node = child.children; }