From d58986872c52ee6349f70e33d0d0f5c4947152a2 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Francisco=20Guimar=C3=A3es?= Date: Fri, 17 Aug 2018 11:04:32 -0300 Subject: [PATCH 01/10] Replacing variable interpolation in "All value" value --- public/app/features/templating/template_srv.ts | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/public/app/features/templating/template_srv.ts b/public/app/features/templating/template_srv.ts index fc79d12ff9e..5bbf5effa66 100644 --- a/public/app/features/templating/template_srv.ts +++ b/public/app/features/templating/template_srv.ts @@ -209,7 +209,7 @@ export class TemplateSrv { value = this.getAllValue(variable); // skip formatting of custom all values if (variable.allValue) { - return value; + return this.replace(value); } } From 8dc16755740df0fab2385cd123db21fbf4dd68ae Mon Sep 17 00:00:00 2001 From: Alexander Zobnin Date: Wed, 22 Aug 2018 15:29:09 +0300 Subject: [PATCH 02/10] heatmap: fix tooltip bug in firefox --- .../plugins/panel/heatmap/heatmap_tooltip.ts | 28 +++++---------- public/app/plugins/panel/heatmap/rendering.ts | 35 +++++++++++++------ 2 files changed, 34 insertions(+), 29 deletions(-) diff --git a/public/app/plugins/panel/heatmap/heatmap_tooltip.ts b/public/app/plugins/panel/heatmap/heatmap_tooltip.ts index 1caa9ae9c69..6cf9262f520 100644 --- a/public/app/plugins/panel/heatmap/heatmap_tooltip.ts +++ b/public/app/plugins/panel/heatmap/heatmap_tooltip.ts @@ -28,21 +28,9 @@ export class HeatmapTooltip { this.mouseOverBucket = false; this.originalFillColor = null; - elem.on('mouseover', this.onMouseOver.bind(this)); elem.on('mouseleave', this.onMouseLeave.bind(this)); } - onMouseOver(e) { - if (!this.panel.tooltip.show || !this.scope.ctrl.data || _.isEmpty(this.scope.ctrl.data.buckets)) { - return; - } - - if (!this.tooltip) { - this.add(); - this.move(e); - } - } - onMouseLeave() { this.destroy(); } @@ -81,11 +69,15 @@ export class HeatmapTooltip { let { xBucketIndex, yBucketIndex } = this.getBucketIndexes(pos, data); - if (!data.buckets[xBucketIndex] || !this.tooltip) { + if (!data.buckets[xBucketIndex]) { this.destroy(); return; } + if (!this.tooltip) { + this.add(); + } + let boundBottom, boundTop, valuesNumber; let xData = data.buckets[xBucketIndex]; // Search in special 'zero' bucket also @@ -158,13 +150,12 @@ export class HeatmapTooltip { } getBucketIndexes(pos, data) { - const xBucketIndex = this.getXBucketIndex(pos.offsetX, data); - const yBucketIndex = this.getYBucketIndex(pos.offsetY, data); + const xBucketIndex = this.getXBucketIndex(pos.x, data); + const yBucketIndex = this.getYBucketIndex(pos.y, data); return { xBucketIndex, yBucketIndex }; } - getXBucketIndex(offsetX, data) { - let x = this.scope.xScale.invert(offsetX - this.scope.yAxisWidth).valueOf(); + 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 => { @@ -173,8 +164,7 @@ export class HeatmapTooltip { return xBucket ? xBucket.x : getValueBucketBound(x, data.xBucketSize, 1); } - getYBucketIndex(offsetY, data) { - let y = this.scope.yScale.invert(offsetY - this.scope.chartTop); + getYBucketIndex(y, data) { if (data.tsBuckets) { return Math.floor(y); } diff --git a/public/app/plugins/panel/heatmap/rendering.ts b/public/app/plugins/panel/heatmap/rendering.ts index e3318ea7e23..8ea216be89d 100644 --- a/public/app/plugins/panel/heatmap/rendering.ts +++ b/public/app/plugins/panel/heatmap/rendering.ts @@ -69,6 +69,7 @@ export class HeatmapRenderer { this.ctrl.events.on('render', this.onRender.bind(this)); this.ctrl.tickValueFormatter = this.tickValueFormatter.bind(this); + ///////////////////////////// // Selection and crosshair // ///////////////////////////// @@ -678,9 +679,17 @@ export class HeatmapRenderer { } } + getEventOffset(event) { + const elemOffset = this.$heatmap.offset(); + const x = Math.floor(event.clientX - elemOffset.left); + const y = Math.floor(event.clientY - elemOffset.top); + return { x, y }; + } + onMouseDown(event) { + const offset = this.getEventOffset(event); this.selection.active = true; - this.selection.x1 = event.offsetX; + this.selection.x1 = offset.x; this.mouseUpHandler = () => { this.onMouseUp(); @@ -718,23 +727,25 @@ export class HeatmapRenderer { return; } + const offset = this.getEventOffset(event); if (this.selection.active) { // Clear crosshair and tooltip this.clearCrosshair(); this.tooltip.destroy(); - this.selection.x2 = this.limitSelection(event.offsetX); + this.selection.x2 = this.limitSelection(offset.x); this.drawSelection(this.selection.x1, this.selection.x2); } else { - this.emitGraphHoverEvent(event); - this.drawCrosshair(event.offsetX); - this.tooltip.show(event, this.data); + const pos = this.getEventPos(event, offset); + this.drawCrosshair(offset.x); + this.tooltip.show(pos, this.data); + this.emitGraphHoverEvent(pos); } } - emitGraphHoverEvent(event) { - let x = this.xScale.invert(event.offsetX - this.yAxisWidth).valueOf(); - let y = this.yScale.invert(event.offsetY); + getEventPos(event, offset) { + let x = this.xScale.invert(offset.x - this.yAxisWidth).valueOf(); + let y = this.yScale.invert(offset.y - this.chartTop); let pos = { pageX: event.pageX, pageY: event.pageY, @@ -743,11 +754,15 @@ export class HeatmapRenderer { y: y, y1: y, panelRelY: null, + offset, }; - // Set minimum offset to prevent showing legend from another panel - pos.panelRelY = Math.max(event.offsetY / this.height, 0.001); + return pos; + } + emitGraphHoverEvent(pos) { + // Set minimum offset to prevent showing legend from another panel + pos.panelRelY = Math.max(pos.offset.y / this.height, 0.001); // broadcast to other graph panels that we are hovering appEvents.emit('graph-hover', { pos: pos, panel: this.panel }); } From a9497f0a96278b64c2e7e1d888064238a2b64e0f Mon Sep 17 00:00:00 2001 From: Marcus Efraimsson Date: Thu, 23 Aug 2018 18:30:28 +0200 Subject: [PATCH 03/10] changelog: add notes about closing #12486 [skip ci] --- CHANGELOG.md | 1 + 1 file changed, 1 insertion(+) diff --git a/CHANGELOG.md b/CHANGELOG.md index 651b4dd22f6..7946530027f 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -54,6 +54,7 @@ om/grafana/grafana/issues/12668) * **Graphite**: Fix for quoting of int function parameters (when using variables) [#11927](https://github.com/grafana/grafana/pull/11927) * **InfluxDB**: Support timeFilter in query templating for InfluxDB [#12598](https://github.com/grafana/grafana/pull/12598), thx [kichristensen](https://github.com/kichristensen) * **Provisioning**: Should allow one default datasource per organisation [#12229](https://github.com/grafana/grafana/issues/12229) +* **Heatmap**: Fix broken tooltip and crosshair on Firefox [#12486](https://github.com/grafana/grafana/issues/12486) ### Breaking changes From 5bb0d2660464fd0ad70348351b6f2809d2350638 Mon Sep 17 00:00:00 2001 From: Leonard Gram Date: Tue, 21 Aug 2018 09:33:48 +0200 Subject: [PATCH 04/10] build: fixes rpm build when using defaults. Closes #12980 --- build.go | 33 +++++++++++++++------------------ 1 file changed, 15 insertions(+), 18 deletions(-) diff --git a/build.go b/build.go index bcb9b2ddf7d..561dd70df0e 100644 --- a/build.go +++ b/build.go @@ -64,6 +64,10 @@ func main() { readVersionFromPackageJson() + if pkgArch == "" { + pkgArch = goarch + } + log.Printf("Version: %s, Linux Version: %s, Package Iteration: %s\n", version, linuxPackageVersion, linuxPackageIteration) if flag.NArg() == 0 { @@ -105,10 +109,17 @@ func main() { case "package": grunt(gruntBuildArg("build")...) - packageGrafana() + grunt(gruntBuildArg("package")...) + if goos == "linux" { + createLinuxPackages() + } case "package-only": - packageGrafana() + grunt(gruntBuildArg("package")...) + if goos == "linux" { + createLinuxPackages() + } + case "pkg-rpm": grunt(gruntBuildArg("release")...) @@ -133,22 +144,6 @@ func main() { } } -func packageGrafana() { - platformArg := fmt.Sprintf("--platform=%v", goos) - previousPkgArch := pkgArch - if pkgArch == "" { - pkgArch = goarch - } - postProcessArgs := gruntBuildArg("package") - postProcessArgs = append(postProcessArgs, platformArg) - grunt(postProcessArgs...) - pkgArch = previousPkgArch - - if goos == "linux" { - createLinuxPackages() - } -} - func makeLatestDistCopies() { files, err := ioutil.ReadDir("dist") if err != nil { @@ -404,6 +399,8 @@ func gruntBuildArg(task string) []string { if phjsToRelease != "" { args = append(args, fmt.Sprintf("--phjsToRelease=%v", phjsToRelease)) } + args = append(args, fmt.Sprintf("--platform=%v", goos)) + return args } From e906d4bdba8524fcc7dc759dac74d9cf7faf563c Mon Sep 17 00:00:00 2001 From: Marcus Efraimsson Date: Fri, 24 Aug 2018 15:55:20 +0200 Subject: [PATCH 05/10] changelog: add notes about closing #12952 #12965 [skip ci] --- CHANGELOG.md | 2 ++ 1 file changed, 2 insertions(+) diff --git a/CHANGELOG.md b/CHANGELOG.md index 7946530027f..3befbc40eb8 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -21,6 +21,8 @@ * **Prometheus**: Add $__interval, $__interval_ms, $__range, $__range_s & $__range_ms support for dashboard and template queries [#12597](https://github.com/grafana/grafana/issues/12597) [#12882](https://github.com/grafana/grafana/issues/12882), thx [@roidelapluie](https://github.com/roidelapluie) * **Variables**: Skip unneeded extra query request when de-selecting variable values used for repeated panels [#8186](https://github.com/grafana/grafana/issues/8186), thx [@mtanda](https://github.com/mtanda) * **Variables**: Limit amount of queries executed when updating variable that other variable(s) are dependent on [#11890](https://github.com/grafana/grafana/issues/11890) +* **Variables**: Support query variable refresh when another variable referenced in `Regex` field change its value [#12952](https://github.com/grafana/grafana/issues/12952), thx [@franciscocpg](https://github.com/franciscocpg) +* **Variables**: Support variables in query variable `Custom all value` field [#12965](https://github.com/grafana/grafana/issues/12965), thx [@franciscocpg](https://github.com/franciscocpg) * **Postgres/MySQL/MSSQL**: New $__unixEpochGroup and $__unixEpochGroupAlias macros [#12892](https://github.com/grafana/grafana/issues/12892), thx [@svenklemm](https://github.com/svenklemm) * **Postgres/MySQL/MSSQL**: Add previous fill mode to $__timeGroup macro which will fill in previously seen value when point is missing [#12756](https://github.com/grafana/grafana/issues/12756), thx [@svenklemm](https://github.com/svenklemm) * **Postgres/MySQL/MSSQL**: Use floor rounding in $__timeGroup macro function [#12460](https://github.com/grafana/grafana/issues/12460), thx [@svenklemm](https://github.com/svenklemm) From 8a99fa269d08252ed5708b89ce0a3e3086326d45 Mon Sep 17 00:00:00 2001 From: Tobias Skarhed Date: Fri, 24 Aug 2018 16:48:47 +0200 Subject: [PATCH 06/10] WIP Update tslint (#12922) * Interface linting rule * fix: changed model names in store files so that the interface names do not conflict with the model names --- package.json | 3 +- .../AlertRuleList/AlertRuleList.tsx | 8 +-- .../{IContainerProps.ts => ContainerProps.ts} | 4 +- public/app/containers/Explore/Explore.tsx | 6 +- .../ManageDashboards/FolderPermissions.tsx | 4 +- .../ManageDashboards/FolderSettings.tsx | 4 +- .../containers/ServerStats/ServerStats.tsx | 4 +- public/app/containers/Teams/TeamGroupSync.tsx | 8 +-- public/app/containers/Teams/TeamList.tsx | 6 +- public/app/containers/Teams/TeamMembers.tsx | 10 ++-- public/app/containers/Teams/TeamPages.tsx | 4 +- public/app/containers/Teams/TeamSettings.tsx | 4 +- .../components/EmptyListCTA/EmptyListCTA.tsx | 57 ++++++++++--------- .../core/components/PageHeader/PageHeader.tsx | 4 +- .../app/core/components/PasswordStrength.tsx | 19 +++---- .../DisabledPermissionsListItem.tsx | 4 +- .../components/Permissions/Permissions.tsx | 4 +- .../Permissions/PermissionsList.tsx | 4 +- .../components/Picker/DescriptionOption.tsx | 4 +- .../core/components/Picker/PickerOption.tsx | 4 +- .../core/components/TagFilter/TagBadge.tsx | 4 +- .../core/components/TagFilter/TagFilter.tsx | 4 +- .../core/components/TagFilter/TagOption.tsx | 4 +- .../core/components/TagFilter/TagValue.tsx | 4 +- .../app/core/components/Tooltip/Popover.tsx | 4 +- .../app/core/components/Tooltip/Tooltip.tsx | 4 +- .../components/colorpicker/ColorPalette.tsx | 8 +-- .../components/colorpicker/ColorPicker.tsx | 4 +- .../colorpicker/ColorPickerPopover.tsx | 35 +++++++----- .../colorpicker/SeriesColorPicker.tsx | 4 +- .../components/colorpicker/SpectrumPicker.tsx | 28 ++++----- .../stores/AlertListStore/AlertListStore.ts | 10 ++-- public/app/stores/NavStore/NavStore.ts | 4 +- public/app/stores/RootStore/RootStore.ts | 4 +- public/app/stores/TeamsStore/TeamsStore.ts | 36 ++++++------ public/app/stores/store.ts | 4 +- tslint.json | 1 + yarn.lock | 12 ++++ 38 files changed, 179 insertions(+), 160 deletions(-) rename public/app/containers/{IContainerProps.ts => ContainerProps.ts} (92%) diff --git a/package.json b/package.json index 8520def5db8..9cc47ff71b8 100644 --- a/package.json +++ b/package.json @@ -169,7 +169,8 @@ "slate-react": "^0.12.4", "tether": "^1.4.0", "tether-drop": "https://github.com/torkelo/drop/tarball/master", - "tinycolor2": "^1.4.1" + "tinycolor2": "^1.4.1", + "tslint-react": "^3.6.0" }, "resolutions": { "caniuse-db": "1.0.30000772" diff --git a/public/app/containers/AlertRuleList/AlertRuleList.tsx b/public/app/containers/AlertRuleList/AlertRuleList.tsx index b61c7fbaac3..3c2da77c2a7 100644 --- a/public/app/containers/AlertRuleList/AlertRuleList.tsx +++ b/public/app/containers/AlertRuleList/AlertRuleList.tsx @@ -3,14 +3,14 @@ import { hot } from 'react-hot-loader'; import classNames from 'classnames'; import { inject, observer } from 'mobx-react'; import PageHeader from 'app/core/components/PageHeader/PageHeader'; -import { IAlertRule } from 'app/stores/AlertListStore/AlertListStore'; +import { AlertRule } from 'app/stores/AlertListStore/AlertListStore'; import appEvents from 'app/core/app_events'; -import IContainerProps from 'app/containers/IContainerProps'; +import ContainerProps from 'app/containers/ContainerProps'; import Highlighter from 'react-highlight-words'; @inject('view', 'nav', 'alertList') @observer -export class AlertRuleList extends React.Component { +export class AlertRuleList extends React.Component { stateFilters = [ { text: 'All', value: 'all' }, { text: 'OK', value: 'ok' }, @@ -109,7 +109,7 @@ function AlertStateFilterOption({ text, value }) { } export interface AlertRuleItemProps { - rule: IAlertRule; + rule: AlertRule; search: string; } diff --git a/public/app/containers/IContainerProps.ts b/public/app/containers/ContainerProps.ts similarity index 92% rename from public/app/containers/IContainerProps.ts rename to public/app/containers/ContainerProps.ts index 6e790cee06d..97889278fdc 100644 --- a/public/app/containers/IContainerProps.ts +++ b/public/app/containers/ContainerProps.ts @@ -6,7 +6,7 @@ import { AlertListStore } from './../stores/AlertListStore/AlertListStore'; import { ViewStore } from './../stores/ViewStore/ViewStore'; import { FolderStore } from './../stores/FolderStore/FolderStore'; -interface IContainerProps { +interface ContainerProps { search: typeof SearchStore.Type; serverStats: typeof ServerStatsStore.Type; nav: typeof NavStore.Type; @@ -17,4 +17,4 @@ interface IContainerProps { backendSrv: any; } -export default IContainerProps; +export default ContainerProps; diff --git a/public/app/containers/Explore/Explore.tsx b/public/app/containers/Explore/Explore.tsx index d161e7689cf..e06f4e7042e 100644 --- a/public/app/containers/Explore/Explore.tsx +++ b/public/app/containers/Explore/Explore.tsx @@ -63,7 +63,7 @@ function parseUrlState(initial: string | undefined) { return { datasource: null, queries: [], range: DEFAULT_RANGE }; } -interface IExploreState { +interface ExploreState { datasource: any; datasourceError: any; datasourceLoading: boolean | null; @@ -88,12 +88,12 @@ interface IExploreState { tableResult: any; } -export class Explore extends React.Component { +export class Explore extends React.Component { el: any; constructor(props) { super(props); - const initialState: IExploreState = props.initialState; + const initialState: ExploreState = props.initialState; const { datasource, queries, range } = parseUrlState(props.routeParams.state); this.state = { datasource: null, diff --git a/public/app/containers/ManageDashboards/FolderPermissions.tsx b/public/app/containers/ManageDashboards/FolderPermissions.tsx index aac5d32750a..072908d2b8e 100644 --- a/public/app/containers/ManageDashboards/FolderPermissions.tsx +++ b/public/app/containers/ManageDashboards/FolderPermissions.tsx @@ -2,7 +2,7 @@ import React, { Component } from 'react'; import { hot } from 'react-hot-loader'; import { inject, observer } from 'mobx-react'; import { toJS } from 'mobx'; -import IContainerProps from 'app/containers/IContainerProps'; +import ContainerProps from 'app/containers/ContainerProps'; import PageHeader from 'app/core/components/PageHeader/PageHeader'; import Permissions from 'app/core/components/Permissions/Permissions'; import Tooltip from 'app/core/components/Tooltip/Tooltip'; @@ -12,7 +12,7 @@ import SlideDown from 'app/core/components/Animations/SlideDown'; @inject('nav', 'folder', 'view', 'permissions') @observer -export class FolderPermissions extends Component { +export class FolderPermissions extends Component { constructor(props) { super(props); this.handleAddPermission = this.handleAddPermission.bind(this); diff --git a/public/app/containers/ManageDashboards/FolderSettings.tsx b/public/app/containers/ManageDashboards/FolderSettings.tsx index d25a7dc6c06..88830356563 100644 --- a/public/app/containers/ManageDashboards/FolderSettings.tsx +++ b/public/app/containers/ManageDashboards/FolderSettings.tsx @@ -3,13 +3,13 @@ import { hot } from 'react-hot-loader'; import { inject, observer } from 'mobx-react'; import { toJS } from 'mobx'; import PageHeader from 'app/core/components/PageHeader/PageHeader'; -import IContainerProps from 'app/containers/IContainerProps'; +import ContainerProps from 'app/containers/ContainerProps'; import { getSnapshot } from 'mobx-state-tree'; import appEvents from 'app/core/app_events'; @inject('nav', 'folder', 'view') @observer -export class FolderSettings extends React.Component { +export class FolderSettings extends React.Component { formSnapshot: any; componentDidMount() { diff --git a/public/app/containers/ServerStats/ServerStats.tsx b/public/app/containers/ServerStats/ServerStats.tsx index 761b296855f..63e78996041 100644 --- a/public/app/containers/ServerStats/ServerStats.tsx +++ b/public/app/containers/ServerStats/ServerStats.tsx @@ -2,11 +2,11 @@ import React from 'react'; import { hot } from 'react-hot-loader'; import { inject, observer } from 'mobx-react'; import PageHeader from 'app/core/components/PageHeader/PageHeader'; -import IContainerProps from 'app/containers/IContainerProps'; +import ContainerProps from 'app/containers/ContainerProps'; @inject('nav', 'serverStats') @observer -export class ServerStats extends React.Component { +export class ServerStats extends React.Component { constructor(props) { super(props); const { nav, serverStats } = this.props; diff --git a/public/app/containers/Teams/TeamGroupSync.tsx b/public/app/containers/Teams/TeamGroupSync.tsx index 323dceae0d8..a3b2e4aed14 100644 --- a/public/app/containers/Teams/TeamGroupSync.tsx +++ b/public/app/containers/Teams/TeamGroupSync.tsx @@ -1,12 +1,12 @@ import React from 'react'; import { hot } from 'react-hot-loader'; import { observer } from 'mobx-react'; -import { ITeam, ITeamGroup } from 'app/stores/TeamsStore/TeamsStore'; +import { Team, TeamGroup } from 'app/stores/TeamsStore/TeamsStore'; import SlideDown from 'app/core/components/Animations/SlideDown'; import Tooltip from 'app/core/components/Tooltip/Tooltip'; interface Props { - team: ITeam; + team: Team; } interface State { @@ -27,7 +27,7 @@ export class TeamGroupSync extends React.Component { this.props.team.loadGroups(); } - renderGroup(group: ITeamGroup) { + renderGroup(group: TeamGroup) { return ( {group.groupId} @@ -53,7 +53,7 @@ export class TeamGroupSync extends React.Component { this.setState({ isAdding: false, newGroupId: '' }); }; - onRemoveGroup = (group: ITeamGroup) => { + onRemoveGroup = (group: TeamGroup) => { this.props.team.removeGroup(group.groupId); }; diff --git a/public/app/containers/Teams/TeamList.tsx b/public/app/containers/Teams/TeamList.tsx index 31406250cb3..2d037eed642 100644 --- a/public/app/containers/Teams/TeamList.tsx +++ b/public/app/containers/Teams/TeamList.tsx @@ -3,7 +3,7 @@ import { hot } from 'react-hot-loader'; import { inject, observer } from 'mobx-react'; import PageHeader from 'app/core/components/PageHeader/PageHeader'; import { NavStore } from 'app/stores/NavStore/NavStore'; -import { TeamsStore, ITeam } from 'app/stores/TeamsStore/TeamsStore'; +import { TeamsStore, Team } from 'app/stores/TeamsStore/TeamsStore'; import { BackendSrv } from 'app/core/services/backend_srv'; import DeleteButton from 'app/core/components/DeleteButton/DeleteButton'; @@ -27,7 +27,7 @@ export class TeamList extends React.Component { this.props.teams.loadTeams(); } - deleteTeam(team: ITeam) { + deleteTeam(team: Team) { this.props.backendSrv.delete('/api/teams/' + team.id).then(this.fetchTeams.bind(this)); } @@ -35,7 +35,7 @@ export class TeamList extends React.Component { this.props.teams.setSearchQuery(evt.target.value); }; - renderTeamMember(team: ITeam): JSX.Element { + renderTeamMember(team: Team): JSX.Element { let teamUrl = `org/teams/edit/${team.id}`; return ( diff --git a/public/app/containers/Teams/TeamMembers.tsx b/public/app/containers/Teams/TeamMembers.tsx index a6b0b04f19d..b06a547063a 100644 --- a/public/app/containers/Teams/TeamMembers.tsx +++ b/public/app/containers/Teams/TeamMembers.tsx @@ -1,13 +1,13 @@ import React from 'react'; import { hot } from 'react-hot-loader'; import { observer } from 'mobx-react'; -import { ITeam, ITeamMember } from 'app/stores/TeamsStore/TeamsStore'; +import { Team, TeamMember } from 'app/stores/TeamsStore/TeamsStore'; import SlideDown from 'app/core/components/Animations/SlideDown'; import { UserPicker, User } from 'app/core/components/Picker/UserPicker'; import DeleteButton from 'app/core/components/DeleteButton/DeleteButton'; interface Props { - team: ITeam; + team: Team; } interface State { @@ -30,15 +30,15 @@ export class TeamMembers extends React.Component { this.props.team.setSearchQuery(evt.target.value); }; - removeMember(member: ITeamMember) { + removeMember(member: TeamMember) { this.props.team.removeMember(member); } - removeMemberConfirmed(member: ITeamMember) { + removeMemberConfirmed(member: TeamMember) { this.props.team.removeMember(member); } - renderMember(member: ITeamMember) { + renderMember(member: TeamMember) { return ( diff --git a/public/app/containers/Teams/TeamPages.tsx b/public/app/containers/Teams/TeamPages.tsx index 500a7cbe5e8..2abc9c51535 100644 --- a/public/app/containers/Teams/TeamPages.tsx +++ b/public/app/containers/Teams/TeamPages.tsx @@ -5,7 +5,7 @@ import { inject, observer } from 'mobx-react'; import config from 'app/core/config'; import PageHeader from 'app/core/components/PageHeader/PageHeader'; import { NavStore } from 'app/stores/NavStore/NavStore'; -import { TeamsStore, ITeam } from 'app/stores/TeamsStore/TeamsStore'; +import { TeamsStore, Team } from 'app/stores/TeamsStore/TeamsStore'; import { ViewStore } from 'app/stores/ViewStore/ViewStore'; import TeamMembers from './TeamMembers'; import TeamSettings from './TeamSettings'; @@ -40,7 +40,7 @@ export class TeamPages extends React.Component { nav.initTeamPage(this.getCurrentTeam(), this.currentPage, this.isSyncEnabled); } - getCurrentTeam(): ITeam { + getCurrentTeam(): Team { const { teams, view } = this.props; return teams.map.get(view.routeParams.get('id')); } diff --git a/public/app/containers/Teams/TeamSettings.tsx b/public/app/containers/Teams/TeamSettings.tsx index 142088a5d1e..0de60a0b16c 100644 --- a/public/app/containers/Teams/TeamSettings.tsx +++ b/public/app/containers/Teams/TeamSettings.tsx @@ -1,11 +1,11 @@ import React from 'react'; import { hot } from 'react-hot-loader'; import { observer } from 'mobx-react'; -import { ITeam } from 'app/stores/TeamsStore/TeamsStore'; +import { Team } from 'app/stores/TeamsStore/TeamsStore'; import { Label } from 'app/core/components/Forms/Forms'; interface Props { - team: ITeam; + team: Team; } @observer diff --git a/public/app/core/components/EmptyListCTA/EmptyListCTA.tsx b/public/app/core/components/EmptyListCTA/EmptyListCTA.tsx index 1583303dfa1..5ece360e36a 100644 --- a/public/app/core/components/EmptyListCTA/EmptyListCTA.tsx +++ b/public/app/core/components/EmptyListCTA/EmptyListCTA.tsx @@ -1,34 +1,37 @@ import React, { Component } from 'react'; -export interface IProps { - model: any; +export interface Props { + model: any; } -class EmptyListCTA extends Component { - render() { - const { - title, - buttonIcon, - buttonLink, - buttonTitle, - proTip, - proTipLink, - proTipLinkTitle, - proTipTarget - } = this.props.model; - return ( -
-
{title}
- {buttonTitle} -
- ProTip: {proTip} - {proTipLinkTitle} -
-
- ); - } +class EmptyListCTA extends Component { + render() { + const { + title, + buttonIcon, + buttonLink, + buttonTitle, + proTip, + proTipLink, + proTipLinkTitle, + proTipTarget, + } = this.props.model; + return ( +
+
{title}
+ + + {buttonTitle} + +
+ ProTip: {proTip} + + {proTipLinkTitle} + +
+
+ ); + } } export default EmptyListCTA; diff --git a/public/app/core/components/PageHeader/PageHeader.tsx b/public/app/core/components/PageHeader/PageHeader.tsx index f998cb9981f..1d744b7e609 100644 --- a/public/app/core/components/PageHeader/PageHeader.tsx +++ b/public/app/core/components/PageHeader/PageHeader.tsx @@ -5,7 +5,7 @@ import classNames from 'classnames'; import appEvents from 'app/core/app_events'; import { toJS } from 'mobx'; -export interface IProps { +export interface Props { model: NavModel; } @@ -82,7 +82,7 @@ const Navigation = ({ main }: { main: NavModelItem }) => { }; @observer -export default class PageHeader extends React.Component { +export default class PageHeader extends React.Component { constructor(props) { super(props); } diff --git a/public/app/core/components/PasswordStrength.tsx b/public/app/core/components/PasswordStrength.tsx index 8f92b18445c..1d676a00a37 100644 --- a/public/app/core/components/PasswordStrength.tsx +++ b/public/app/core/components/PasswordStrength.tsx @@ -1,32 +1,31 @@ import React from 'react'; -export interface IProps { +export interface Props { password: string; } -export class PasswordStrength extends React.Component { - +export class PasswordStrength extends React.Component { constructor(props) { super(props); } render() { const { password } = this.props; - let strengthText = "strength: strong like a bull."; - let strengthClass = "password-strength-good"; + let strengthText = 'strength: strong like a bull.'; + let strengthClass = 'password-strength-good'; if (!password) { return null; } if (password.length <= 8) { - strengthText = "strength: you can do better."; - strengthClass = "password-strength-ok"; + strengthText = 'strength: you can do better.'; + strengthClass = 'password-strength-ok'; } if (password.length < 4) { - strengthText = "strength: weak sauce."; - strengthClass = "password-strength-bad"; + strengthText = 'strength: weak sauce.'; + strengthClass = 'password-strength-bad'; } return ( @@ -36,5 +35,3 @@ export class PasswordStrength extends React.Component { ); } } - - diff --git a/public/app/core/components/Permissions/DisabledPermissionsListItem.tsx b/public/app/core/components/Permissions/DisabledPermissionsListItem.tsx index bbb9754fe0d..d65595dae66 100644 --- a/public/app/core/components/Permissions/DisabledPermissionsListItem.tsx +++ b/public/app/core/components/Permissions/DisabledPermissionsListItem.tsx @@ -2,11 +2,11 @@ import React, { Component } from 'react'; import DescriptionPicker from 'app/core/components/Picker/DescriptionPicker'; import { permissionOptions } from 'app/stores/PermissionsStore/PermissionsStore'; -export interface IProps { +export interface Props { item: any; } -export default class DisabledPermissionListItem extends Component { +export default class DisabledPermissionListItem extends Component { render() { const { item } = this.props; diff --git a/public/app/core/components/Permissions/Permissions.tsx b/public/app/core/components/Permissions/Permissions.tsx index dbdc1682f6b..d17899c891f 100644 --- a/public/app/core/components/Permissions/Permissions.tsx +++ b/public/app/core/components/Permissions/Permissions.tsx @@ -20,7 +20,7 @@ export interface DashboardAcl { sortRank?: number; } -export interface IProps { +export interface Props { dashboardId: number; folderInfo?: FolderInfo; permissions?: any; @@ -29,7 +29,7 @@ export interface IProps { } @observer -class Permissions extends Component { +class Permissions extends Component { constructor(props) { super(props); const { dashboardId, isFolder, folderInfo } = this.props; diff --git a/public/app/core/components/Permissions/PermissionsList.tsx b/public/app/core/components/Permissions/PermissionsList.tsx index a77235ecc30..7e64de012e4 100644 --- a/public/app/core/components/Permissions/PermissionsList.tsx +++ b/public/app/core/components/Permissions/PermissionsList.tsx @@ -4,7 +4,7 @@ import DisabledPermissionsListItem from './DisabledPermissionsListItem'; import { observer } from 'mobx-react'; import { FolderInfo } from './FolderInfo'; -export interface IProps { +export interface Props { permissions: any[]; removeItem: any; permissionChanged: any; @@ -13,7 +13,7 @@ export interface IProps { } @observer -class PermissionsList extends Component { +class PermissionsList extends Component { render() { const { permissions, removeItem, permissionChanged, fetching, folderInfo } = this.props; diff --git a/public/app/core/components/Picker/DescriptionOption.tsx b/public/app/core/components/Picker/DescriptionOption.tsx index 12a1fdd9163..1bcb7100489 100644 --- a/public/app/core/components/Picker/DescriptionOption.tsx +++ b/public/app/core/components/Picker/DescriptionOption.tsx @@ -1,6 +1,6 @@ import React, { Component } from 'react'; -export interface IProps { +export interface Props { onSelect: any; onFocus: any; option: any; @@ -8,7 +8,7 @@ export interface IProps { className: any; } -class DescriptionOption extends Component { +class DescriptionOption extends Component { constructor(props) { super(props); this.handleMouseDown = this.handleMouseDown.bind(this); diff --git a/public/app/core/components/Picker/PickerOption.tsx b/public/app/core/components/Picker/PickerOption.tsx index 1b32adac572..f30a7c06d10 100644 --- a/public/app/core/components/Picker/PickerOption.tsx +++ b/public/app/core/components/Picker/PickerOption.tsx @@ -1,6 +1,6 @@ import React, { Component } from 'react'; -export interface IProps { +export interface Props { onSelect: any; onFocus: any; option: any; @@ -8,7 +8,7 @@ export interface IProps { className: any; } -class UserPickerOption extends Component { +class UserPickerOption extends Component { constructor(props) { super(props); this.handleMouseDown = this.handleMouseDown.bind(this); diff --git a/public/app/core/components/TagFilter/TagBadge.tsx b/public/app/core/components/TagFilter/TagBadge.tsx index e5c2e357a58..d93b5fd1e74 100644 --- a/public/app/core/components/TagFilter/TagBadge.tsx +++ b/public/app/core/components/TagFilter/TagBadge.tsx @@ -1,14 +1,14 @@ import React from 'react'; import tags from 'app/core/utils/tags'; -export interface IProps { +export interface Props { label: string; removeIcon: boolean; count: number; onClick: any; } -export class TagBadge extends React.Component { +export class TagBadge extends React.Component { constructor(props) { super(props); this.onClick = this.onClick.bind(this); diff --git a/public/app/core/components/TagFilter/TagFilter.tsx b/public/app/core/components/TagFilter/TagFilter.tsx index 0b6058f3dd2..84f3e1819cd 100644 --- a/public/app/core/components/TagFilter/TagFilter.tsx +++ b/public/app/core/components/TagFilter/TagFilter.tsx @@ -4,13 +4,13 @@ import { Async } from 'react-select'; import { TagValue } from './TagValue'; import { TagOption } from './TagOption'; -export interface IProps { +export interface Props { tags: string[]; tagOptions: () => any; onSelect: (tag: string) => void; } -export class TagFilter extends React.Component { +export class TagFilter extends React.Component { inlineTags: boolean; constructor(props) { diff --git a/public/app/core/components/TagFilter/TagOption.tsx b/public/app/core/components/TagFilter/TagOption.tsx index 402544dd5f3..5938c98f870 100644 --- a/public/app/core/components/TagFilter/TagOption.tsx +++ b/public/app/core/components/TagFilter/TagOption.tsx @@ -1,7 +1,7 @@ import React from 'react'; import { TagBadge } from './TagBadge'; -export interface IProps { +export interface Props { onSelect: any; onFocus: any; option: any; @@ -9,7 +9,7 @@ export interface IProps { className: any; } -export class TagOption extends React.Component { +export class TagOption extends React.Component { constructor(props) { super(props); this.handleMouseDown = this.handleMouseDown.bind(this); diff --git a/public/app/core/components/TagFilter/TagValue.tsx b/public/app/core/components/TagFilter/TagValue.tsx index 2e7819951f2..ca8ca9e4fba 100644 --- a/public/app/core/components/TagFilter/TagValue.tsx +++ b/public/app/core/components/TagFilter/TagValue.tsx @@ -1,14 +1,14 @@ import React from 'react'; import { TagBadge } from './TagBadge'; -export interface IProps { +export interface Props { value: any; className: any; onClick: any; onRemove: any; } -export class TagValue extends React.Component { +export class TagValue extends React.Component { constructor(props) { super(props); this.onClick = this.onClick.bind(this); diff --git a/public/app/core/components/Tooltip/Popover.tsx b/public/app/core/components/Tooltip/Popover.tsx index 4dc25d34130..ee86d07fb53 100644 --- a/public/app/core/components/Tooltip/Popover.tsx +++ b/public/app/core/components/Tooltip/Popover.tsx @@ -2,11 +2,11 @@ import withTooltip from './withTooltip'; import { Target } from 'react-popper'; -interface IPopoverProps { +interface PopoverProps { tooltipSetState: (prevState: object) => void; } -class Popover extends React.Component { +class Popover extends React.Component { constructor(props) { super(props); this.toggleTooltip = this.toggleTooltip.bind(this); diff --git a/public/app/core/components/Tooltip/Tooltip.tsx b/public/app/core/components/Tooltip/Tooltip.tsx index ae4093ea3f1..a265c8487d3 100644 --- a/public/app/core/components/Tooltip/Tooltip.tsx +++ b/public/app/core/components/Tooltip/Tooltip.tsx @@ -2,11 +2,11 @@ import withTooltip from './withTooltip'; import { Target } from 'react-popper'; -interface ITooltipProps { +interface TooltipProps { tooltipSetState: (prevState: object) => void; } -class Tooltip extends React.Component { +class Tooltip extends React.Component { constructor(props) { super(props); this.showTooltip = this.showTooltip.bind(this); diff --git a/public/app/core/components/colorpicker/ColorPalette.tsx b/public/app/core/components/colorpicker/ColorPalette.tsx index 07b25a32046..edb2629d16d 100644 --- a/public/app/core/components/colorpicker/ColorPalette.tsx +++ b/public/app/core/components/colorpicker/ColorPalette.tsx @@ -1,12 +1,12 @@ import React from 'react'; import { sortedColors } from 'app/core/utils/colors'; -export interface IProps { +export interface Props { color: string; onColorSelect: (c: string) => void; } -export class ColorPalette extends React.Component { +export class ColorPalette extends React.Component { paletteColors: string[]; constructor(props) { @@ -29,7 +29,8 @@ export class ColorPalette extends React.Component { key={paletteColor} className={'pointer fa ' + cssClass} style={{ color: paletteColor }} - onClick={this.onColorSelect(paletteColor)}> + onClick={this.onColorSelect(paletteColor)} + >   ); @@ -41,4 +42,3 @@ export class ColorPalette extends React.Component { ); } } - diff --git a/public/app/core/components/colorpicker/ColorPicker.tsx b/public/app/core/components/colorpicker/ColorPicker.tsx index dbba75636d0..c492d3829ca 100644 --- a/public/app/core/components/colorpicker/ColorPicker.tsx +++ b/public/app/core/components/colorpicker/ColorPicker.tsx @@ -5,12 +5,12 @@ import Drop from 'tether-drop'; import { ColorPickerPopover } from './ColorPickerPopover'; import { react2AngularDirective } from 'app/core/utils/react2angular'; -export interface IProps { +export interface Props { color: string; onChange: (c: string) => void; } -export class ColorPicker extends React.Component { +export class ColorPicker extends React.Component { pickerElem: any; colorPickerDrop: any; diff --git a/public/app/core/components/colorpicker/ColorPickerPopover.tsx b/public/app/core/components/colorpicker/ColorPickerPopover.tsx index 360c3fdd5c4..ac7dd6a2738 100644 --- a/public/app/core/components/colorpicker/ColorPickerPopover.tsx +++ b/public/app/core/components/colorpicker/ColorPickerPopover.tsx @@ -6,12 +6,12 @@ import { SpectrumPicker } from './SpectrumPicker'; const DEFAULT_COLOR = '#000000'; -export interface IProps { +export interface Props { color: string; onColorSelect: (c: string) => void; } -export class ColorPickerPopover extends React.Component { +export class ColorPickerPopover extends React.Component { pickerNavElem: any; constructor(props) { @@ -19,7 +19,7 @@ export class ColorPickerPopover extends React.Component { this.state = { tab: 'palette', color: this.props.color || DEFAULT_COLOR, - colorString: this.props.color || DEFAULT_COLOR + colorString: this.props.color || DEFAULT_COLOR, }; } @@ -32,7 +32,7 @@ export class ColorPickerPopover extends React.Component { if (newColor.isValid()) { this.setState({ color: newColor.toString(), - colorString: newColor.toString() + colorString: newColor.toString(), }); this.props.onColorSelect(color); } @@ -50,7 +50,7 @@ export class ColorPickerPopover extends React.Component { onColorStringChange(e) { let colorString = e.target.value; this.setState({ - colorString: colorString + colorString: colorString, }); let newColor = tinycolor(colorString); @@ -71,11 +71,11 @@ export class ColorPickerPopover extends React.Component { componentDidMount() { this.pickerNavElem.find('li:first').addClass('active'); - this.pickerNavElem.on('show', (e) => { + this.pickerNavElem.on('show', e => { // use href attr (#name => name) let tab = e.target.hash.slice(1); this.setState({ - tab: tab + tab: tab, }); }); } @@ -97,19 +97,24 @@ export class ColorPickerPopover extends React.Component {
-
- {currentTab} -
+
{currentTab}
- - +
); diff --git a/public/app/core/components/colorpicker/SeriesColorPicker.tsx b/public/app/core/components/colorpicker/SeriesColorPicker.tsx index 3b24b9a4661..b514899e2e2 100644 --- a/public/app/core/components/colorpicker/SeriesColorPicker.tsx +++ b/public/app/core/components/colorpicker/SeriesColorPicker.tsx @@ -2,13 +2,13 @@ import React from 'react'; import { ColorPickerPopover } from './ColorPickerPopover'; import { react2AngularDirective } from 'app/core/utils/react2angular'; -export interface IProps { +export interface Props { series: any; onColorChange: (color: string) => void; onToggleAxis: () => void; } -export class SeriesColorPicker extends React.Component { +export class SeriesColorPicker extends React.Component { constructor(props) { super(props); this.onColorChange = this.onColorChange.bind(this); diff --git a/public/app/core/components/colorpicker/SpectrumPicker.tsx b/public/app/core/components/colorpicker/SpectrumPicker.tsx index eef04545308..e8a30e8c460 100644 --- a/public/app/core/components/colorpicker/SpectrumPicker.tsx +++ b/public/app/core/components/colorpicker/SpectrumPicker.tsx @@ -3,13 +3,13 @@ import _ from 'lodash'; import $ from 'jquery'; import 'vendor/spectrum'; -export interface IProps { +export interface Props { color: string; options: object; onColorSelect: (c: string) => void; } -export class SpectrumPicker extends React.Component { +export class SpectrumPicker extends React.Component { elem: any; isMoving: boolean; @@ -29,14 +29,17 @@ export class SpectrumPicker extends React.Component { } componentDidMount() { - let spectrumOptions = _.assignIn({ - flat: true, - showAlpha: true, - showButtons: false, - color: this.props.color, - appendTo: this.elem, - move: this.onSpectrumMove, - }, this.props.options); + let spectrumOptions = _.assignIn( + { + flat: true, + showAlpha: true, + showButtons: false, + color: this.props.color, + appendTo: this.elem, + move: this.onSpectrumMove, + }, + this.props.options + ); this.elem.spectrum(spectrumOptions); this.elem.spectrum('show'); @@ -64,9 +67,6 @@ export class SpectrumPicker extends React.Component { } render() { - return ( -
- ); + return
; } } - diff --git a/public/app/stores/AlertListStore/AlertListStore.ts b/public/app/stores/AlertListStore/AlertListStore.ts index 7d60ce04180..ec27565a1a1 100644 --- a/public/app/stores/AlertListStore/AlertListStore.ts +++ b/public/app/stores/AlertListStore/AlertListStore.ts @@ -1,13 +1,13 @@ import { types, getEnv, flow } from 'mobx-state-tree'; -import { AlertRule } from './AlertRule'; +import { AlertRule as AlertRuleModel } from './AlertRule'; import { setStateFields } from './helpers'; -type IAlertRuleType = typeof AlertRule.Type; -export interface IAlertRule extends IAlertRuleType {} +type AlertRuleType = typeof AlertRuleModel.Type; +export interface AlertRule extends AlertRuleType {} export const AlertListStore = types .model('AlertListStore', { - rules: types.array(AlertRule), + rules: types.array(AlertRuleModel), stateFilter: types.optional(types.string, 'all'), search: types.optional(types.string, ''), }) @@ -38,7 +38,7 @@ export const AlertListStore = types } } - self.rules.push(AlertRule.create(rule)); + self.rules.push(AlertRuleModel.create(rule)); } }), setSearchQuery(query: string) { diff --git a/public/app/stores/NavStore/NavStore.ts b/public/app/stores/NavStore/NavStore.ts index c69c32befa8..bef53b828b6 100644 --- a/public/app/stores/NavStore/NavStore.ts +++ b/public/app/stores/NavStore/NavStore.ts @@ -1,7 +1,7 @@ import _ from 'lodash'; import { types, getEnv } from 'mobx-state-tree'; import { NavItem } from './NavItem'; -import { ITeam } from '../TeamsStore/TeamsStore'; +import { Team } from '../TeamsStore/TeamsStore'; export const NavStore = types .model('NavStore', { @@ -117,7 +117,7 @@ export const NavStore = types self.main = NavItem.create(main); }, - initTeamPage(team: ITeam, tab: string, isSyncEnabled: boolean) { + initTeamPage(team: Team, tab: string, isSyncEnabled: boolean) { let main = { img: team.avatarUrl, id: 'team-' + team.id, diff --git a/public/app/stores/RootStore/RootStore.ts b/public/app/stores/RootStore/RootStore.ts index 8a915d20ef1..bb85a85d9dd 100644 --- a/public/app/stores/RootStore/RootStore.ts +++ b/public/app/stores/RootStore/RootStore.ts @@ -34,5 +34,5 @@ export const RootStore = types.model({ }), }); -type IRootStoreType = typeof RootStore.Type; -export interface IRootStore extends IRootStoreType {} +type RootStoreType = typeof RootStore.Type; +export interface RootStoreInterface extends RootStoreType {} diff --git a/public/app/stores/TeamsStore/TeamsStore.ts b/public/app/stores/TeamsStore/TeamsStore.ts index 01cdca895d4..1aec4a1433c 100644 --- a/public/app/stores/TeamsStore/TeamsStore.ts +++ b/public/app/stores/TeamsStore/TeamsStore.ts @@ -1,6 +1,6 @@ import { types, getEnv, flow } from 'mobx-state-tree'; -export const TeamMember = types.model('TeamMember', { +export const TeamMemberModel = types.model('TeamMember', { userId: types.identifier(types.number), teamId: types.number, avatarUrl: types.string, @@ -8,18 +8,18 @@ export const TeamMember = types.model('TeamMember', { login: types.string, }); -type TeamMemberType = typeof TeamMember.Type; -export interface ITeamMember extends TeamMemberType {} +type TeamMemberType = typeof TeamMemberModel.Type; +export interface TeamMember extends TeamMemberType {} -export const TeamGroup = types.model('TeamGroup', { +export const TeamGroupModel = types.model('TeamGroup', { groupId: types.identifier(types.string), teamId: types.number, }); -type TeamGroupType = typeof TeamGroup.Type; -export interface ITeamGroup extends TeamGroupType {} +type TeamGroupType = typeof TeamGroupModel.Type; +export interface TeamGroup extends TeamGroupType {} -export const Team = types +export const TeamModel = types .model('Team', { id: types.identifier(types.number), name: types.string, @@ -27,8 +27,8 @@ export const Team = types email: types.string, memberCount: types.number, search: types.optional(types.string, ''), - members: types.optional(types.map(TeamMember), {}), - groups: types.optional(types.map(TeamGroup), {}), + members: types.optional(types.map(TeamMemberModel), {}), + groups: types.optional(types.map(TeamGroupModel), {}), }) .views(self => ({ get filteredMembers() { @@ -67,11 +67,11 @@ export const Team = types self.members.clear(); for (let member of rsp) { - self.members.set(member.userId.toString(), TeamMember.create(member)); + self.members.set(member.userId.toString(), TeamMemberModel.create(member)); } }), - removeMember: flow(function* load(member: ITeamMember) { + removeMember: flow(function* load(member: TeamMember) { const backendSrv = getEnv(self).backendSrv; yield backendSrv.delete(`/api/teams/${self.id}/members/${member.userId}`); // remove from store map @@ -89,7 +89,7 @@ export const Team = types self.groups.clear(); for (let group of rsp) { - self.groups.set(group.groupId, TeamGroup.create(group)); + self.groups.set(group.groupId, TeamGroupModel.create(group)); } }), @@ -98,7 +98,7 @@ export const Team = types yield backendSrv.post(`/api/teams/${self.id}/groups`, { groupId: groupId }); self.groups.set( groupId, - TeamGroup.create({ + TeamGroupModel.create({ teamId: self.id, groupId: groupId, }) @@ -112,12 +112,12 @@ export const Team = types }), })); -type TeamType = typeof Team.Type; -export interface ITeam extends TeamType {} +type TeamType = typeof TeamModel.Type; +export interface Team extends TeamType {} export const TeamsStore = types .model('TeamsStore', { - map: types.map(Team), + map: types.map(TeamModel), search: types.optional(types.string, ''), }) .views(self => ({ @@ -136,7 +136,7 @@ export const TeamsStore = types self.map.clear(); for (let team of rsp.teams) { - self.map.set(team.id.toString(), Team.create(team)); + self.map.set(team.id.toString(), TeamModel.create(team)); } }), @@ -151,6 +151,6 @@ export const TeamsStore = types const backendSrv = getEnv(self).backendSrv; const team = yield backendSrv.get(`/api/teams/${id}`); - self.map.set(id, Team.create(team)); + self.map.set(id, TeamModel.create(team)); }), })); diff --git a/public/app/stores/store.ts b/public/app/stores/store.ts index dfbd8141198..10acbfe4907 100644 --- a/public/app/stores/store.ts +++ b/public/app/stores/store.ts @@ -1,7 +1,7 @@ -import { RootStore, IRootStore } from './RootStore/RootStore'; +import { RootStore, RootStoreInterface } from './RootStore/RootStore'; import config from 'app/core/config'; -export let store: IRootStore; +export let store: RootStoreInterface; export function createStore(services) { store = RootStore.create( diff --git a/tslint.json b/tslint.json index 22e123e0364..9a72f9ccebc 100644 --- a/tslint.json +++ b/tslint.json @@ -1,5 +1,6 @@ { "rules": { + "interface-name": [true, "never-prefix"], "no-string-throw": true, "no-unused-expression": true, "no-unused-variable": false, diff --git a/yarn.lock b/yarn.lock index dd1cde4e698..fb593043288 100644 --- a/yarn.lock +++ b/yarn.lock @@ -11454,6 +11454,12 @@ tslint-loader@^3.5.3: rimraf "^2.4.4" semver "^5.3.0" +tslint-react@^3.6.0: + version "3.6.0" + resolved "https://registry.yarnpkg.com/tslint-react/-/tslint-react-3.6.0.tgz#7f462c95c4a0afaae82507f06517ff02942196a1" + dependencies: + tsutils "^2.13.1" + tslint@^5.8.0: version "5.10.0" resolved "https://registry.yarnpkg.com/tslint/-/tslint-5.10.0.tgz#11e26bccb88afa02dd0d9956cae3d4540b5f54c3" @@ -11477,6 +11483,12 @@ tsutils@^2.12.1: dependencies: tslib "^1.8.1" +tsutils@^2.13.1: + version "2.29.0" + resolved "https://registry.yarnpkg.com/tsutils/-/tsutils-2.29.0.tgz#32b488501467acbedd4b85498673a0812aca0b99" + dependencies: + tslib "^1.8.1" + tty-browserify@0.0.0: version "0.0.0" resolved "https://registry.yarnpkg.com/tty-browserify/-/tty-browserify-0.0.0.tgz#a157ba402da24e9bf957f9aa69d524eed42901a6" From 9b978b7203afdde901fa0d4324719b2aa64db271 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Torkel=20=C3=96degaard?= Date: Sun, 26 Aug 2018 17:14:40 +0200 Subject: [PATCH 07/10] tslint: autofix of let -> const (#13033) --- .../AlertRuleList/AlertRuleList.test.tsx | 2 +- .../AlertRuleList/AlertRuleList.tsx | 4 +- public/app/containers/Explore/Table.tsx | 2 +- .../containers/Explore/utils/prometheus.ts | 2 +- public/app/containers/Teams/TeamList.tsx | 2 +- .../Permissions/AddPermissions.test.tsx | 2 +- .../core/components/TagFilter/TagFilter.tsx | 2 +- .../components/code_editor/code_editor.ts | 30 ++-- .../components/colorpicker/ColorPicker.tsx | 4 +- .../colorpicker/ColorPickerPopover.tsx | 14 +- .../components/colorpicker/SpectrumPicker.tsx | 2 +- .../components/form_dropdown/form_dropdown.ts | 2 +- public/app/core/components/grafana_app.ts | 2 +- public/app/core/components/info_popover.ts | 14 +- .../manage_dashboards/manage_dashboards.ts | 14 +- public/app/core/components/scroll/scroll.ts | 6 +- .../core/components/search/SearchResult.tsx | 2 +- .../app/core/components/sidemenu/sidemenu.ts | 4 +- public/app/core/controllers/login_ctrl.ts | 4 +- .../app/core/directives/dropdown_typeahead.ts | 32 ++--- public/app/core/directives/metric_segment.ts | 28 ++-- public/app/core/directives/misc.ts | 2 +- .../core/directives/value_select_dropdown.ts | 18 +-- public/app/core/nav_model_srv.ts | 6 +- public/app/core/services/backend_srv.ts | 10 +- public/app/core/services/bridge_srv.ts | 4 +- .../core/services/dynamic_directive_srv.ts | 2 +- public/app/core/services/keybindingSrv.ts | 2 +- public/app/core/services/ng_react.ts | 2 +- public/app/core/services/search_srv.ts | 14 +- public/app/core/services/segment_srv.ts | 4 +- public/app/core/specs/backend_srv.test.ts | 4 +- public/app/core/specs/file_export.test.ts | 6 +- public/app/core/specs/search.test.ts | 2 +- public/app/core/specs/search_results.test.ts | 8 +- public/app/core/specs/ticks.test.ts | 2 +- public/app/core/specs/time_series.test.ts | 10 +- .../core/specs/value_select_dropdown.test.ts | 2 +- public/app/core/time_series2.ts | 8 +- public/app/core/utils/colors.ts | 4 +- public/app/core/utils/dag.test.ts | 20 +-- public/app/core/utils/dag.ts | 18 +-- public/app/core/utils/file_export.ts | 16 +-- public/app/core/utils/outline.ts | 2 +- public/app/core/utils/rangeutil.ts | 10 +- public/app/core/utils/sort_by_keys.ts | 2 +- public/app/core/utils/tags.ts | 6 +- public/app/core/utils/ticks.ts | 22 +-- public/app/core/utils/url.ts | 10 +- public/app/core/utils/version.ts | 6 +- .../app/features/alerting/alert_tab_ctrl.ts | 4 +- .../alerting/notification_edit_ctrl.ts | 2 +- .../app/features/alerting/threshold_mapper.ts | 14 +- .../features/annotations/annotations_srv.ts | 2 +- .../app/features/annotations/event_editor.ts | 4 +- .../app/features/annotations/event_manager.ts | 12 +- .../features/annotations/events_processing.ts | 12 +- .../annotations/specs/annotations_srv.test.ts | 4 +- .../specs/annotations_srv_specs.test.ts | 8 +- .../app/features/dashboard/ad_hoc_filters.ts | 2 +- .../app/features/dashboard/change_tracker.ts | 8 +- .../dashboard/dashboard_import_ctrl.ts | 4 +- .../features/dashboard/dashboard_migration.ts | 14 +- .../app/features/dashboard/dashboard_model.ts | 88 ++++++------ .../dashboard/dashgrid/AddPanelPanel.tsx | 20 +-- .../dashboard/dashgrid/DashboardGrid.tsx | 8 +- .../app/features/dashboard/dashnav/dashnav.ts | 4 +- .../features/dashboard/export/export_modal.ts | 2 +- .../app/features/dashboard/export/exporter.ts | 14 +- .../app/features/dashboard/history/history.ts | 4 +- .../features/dashboard/settings/settings.ts | 2 +- .../app/features/dashboard/shareModalCtrl.ts | 2 +- .../specs/dashboard_migration.test.ts | 84 +++++------ .../dashboard/specs/dashboard_model.test.ts | 32 ++--- .../dashboard/specs/history_ctrl.test.ts | 4 +- .../dashboard/specs/history_srv.test.ts | 6 +- .../features/dashboard/specs/repeat.test.ts | 2 +- .../dashboard/specs/viewstate_srv.test.ts | 6 +- .../app/features/dashboard/validation_srv.ts | 4 +- .../app/features/dashboard/view_state_srv.ts | 4 +- public/app/features/org/org_users_ctrl.ts | 2 +- public/app/features/panel/metrics_tab.ts | 2 +- public/app/features/panel/panel_ctrl.ts | 16 +-- public/app/features/panel/panel_directive.ts | 4 +- public/app/features/panel/panel_header.ts | 12 +- public/app/features/panel/solo_panel_ctrl.ts | 2 +- .../panellinks/specs/link_srv.test.ts | 2 +- .../app/features/playlist/playlist_routes.ts | 2 +- .../playlist/specs/playlist_edit_ctrl.test.ts | 2 +- public/app/features/plugins/ds_list_ctrl.ts | 2 +- .../app/features/plugins/plugin_component.ts | 8 +- .../app/features/plugins/plugin_edit_ctrl.ts | 6 +- .../app/features/plugins/plugin_list_ctrl.ts | 2 +- public/app/features/plugins/plugin_loader.ts | 4 +- .../app/features/plugins/plugin_page_ctrl.ts | 2 +- .../plugins/specs/datasource_srv.test.ts | 4 +- .../templating/specs/editor_ctrl.test.ts | 2 +- .../specs/variable_srv_init.test.ts | 6 +- .../app/features/templating/variable_srv.ts | 12 +- .../datasource/cloudwatch/datasource.ts | 4 +- .../cloudwatch/specs/datasource.test.ts | 26 ++-- .../datasource/elasticsearch/datasource.ts | 8 +- .../elasticsearch/elastic_response.ts | 14 +- .../elasticsearch/specs/datasource.test.ts | 10 +- .../plugins/datasource/grafana/datasource.ts | 2 +- .../plugins/datasource/graphite/datasource.ts | 32 ++--- .../datasource/graphite/graphite_query.ts | 18 +-- .../plugins/datasource/graphite/query_ctrl.ts | 30 ++-- .../graphite/specs/datasource.test.ts | 30 ++-- .../graphite/specs/graphite_query.test.ts | 2 +- .../graphite/specs/query_ctrl.test.ts | 2 +- .../plugins/datasource/influxdb/datasource.ts | 12 +- .../datasource/influxdb/influx_query.ts | 4 +- .../plugins/datasource/influxdb/query_ctrl.ts | 6 +- .../influxdb/specs/datasource.test.ts | 6 +- .../influxdb/specs/query_ctrl.test.ts | 2 +- .../plugins/datasource/mssql/query_ctrl.ts | 4 +- .../datasource/mssql/response_parser.ts | 8 +- .../plugins/datasource/mysql/query_ctrl.ts | 4 +- .../datasource/mysql/response_parser.ts | 8 +- .../datasource/mysql/specs/datasource.test.ts | 8 +- .../opentsdb/specs/datasource.test.ts | 4 +- .../plugins/datasource/postgres/query_ctrl.ts | 4 +- .../datasource/postgres/response_parser.ts | 10 +- .../postgres/specs/datasource.test.ts | 8 +- .../datasource/prometheus/completer.ts | 20 +-- .../datasource/prometheus/datasource.ts | 18 +-- .../prometheus/result_transformer.ts | 16 +-- .../prometheus/specs/completer.test.ts | 10 +- .../prometheus/specs/datasource.test.ts | 84 +++++------ .../specs/metric_find_query.test.ts | 4 +- .../specs/result_transformer.test.ts | 10 +- .../plugins/datasource/testdata/datasource.ts | 2 +- public/app/plugins/panel/alertlist/module.ts | 4 +- .../app/plugins/panel/graph/data_processor.ts | 12 +- public/app/plugins/panel/graph/graph.ts | 24 ++-- .../app/plugins/panel/graph/graph_tooltip.ts | 32 ++--- public/app/plugins/panel/graph/histogram.ts | 20 +-- .../plugins/panel/graph/jquery.flot.events.ts | 90 ++++++------ public/app/plugins/panel/graph/legend.ts | 14 +- public/app/plugins/panel/graph/module.ts | 4 +- .../plugins/panel/graph/specs/graph.test.ts | 4 +- .../panel/graph/specs/graph_ctrl.test.ts | 6 +- .../panel/graph/specs/histogram.test.ts | 16 +-- .../graph/specs/series_override_ctrl.test.ts | 2 +- .../app/plugins/panel/heatmap/color_legend.ts | 118 +++++++-------- .../app/plugins/panel/heatmap/color_scale.ts | 8 +- .../app/plugins/panel/heatmap/heatmap_ctrl.ts | 50 +++---- .../panel/heatmap/heatmap_data_converter.ts | 78 +++++----- .../plugins/panel/heatmap/heatmap_tooltip.ts | 52 +++---- public/app/plugins/panel/heatmap/rendering.ts | 134 +++++++++--------- .../panel/heatmap/specs/heatmap_ctrl.test.ts | 6 +- .../specs/heatmap_data_converter.test.ts | 40 +++--- public/app/plugins/panel/pluginlist/module.ts | 2 +- public/app/plugins/panel/singlestat/module.ts | 14 +- .../panel/singlestat/specs/singlestat.test.ts | 8 +- public/app/plugins/panel/table/module.ts | 2 +- public/app/plugins/panel/table/renderer.ts | 26 ++-- .../app/plugins/panel/table/transformers.ts | 2 +- .../stores/AlertListStore/AlertListStore.ts | 4 +- public/app/stores/NavStore/NavStore.ts | 14 +- .../PermissionsStore/PermissionsStore.ts | 6 +- public/app/stores/TeamsStore/TeamsStore.ts | 14 +- public/app/stores/ViewStore/ViewStore.ts | 4 +- public/test/core/utils/version_test.ts | 42 +++--- public/test/index.ts | 6 +- public/test/mocks/common.ts | 6 +- 167 files changed, 1077 insertions(+), 1081 deletions(-) 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; } From 314b645857bf82f6fef66e9d4c1af18dd6854567 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Torkel=20=C3=96degaard?= Date: Sun, 26 Aug 2018 18:43:07 +0200 Subject: [PATCH 08/10] tslint: changing vars -> const (#13034) --- .../alerting/specs/threshold_mapper.test.ts | 12 +- .../dashboard/specs/dashboard_model.test.ts | 48 +++---- .../features/dashboard/specs/exporter.test.ts | 30 ++--- .../dashboard/specs/save_as_modal.test.ts | 12 +- .../specs/save_provisioned_modal.test.ts | 6 +- .../dashboard/specs/share_modal_ctrl.test.ts | 10 +- .../features/dashboard/specs/time_srv.test.ts | 22 ++-- .../dashboard/specs/viewstate_srv.test.ts | 2 +- .../panellinks/specs/link_srv.test.ts | 18 +-- .../templating/specs/adhoc_variable.test.ts | 6 +- .../templating/specs/query_variable.test.ts | 14 +-- .../templating/specs/template_srv.test.ts | 100 +++++++-------- .../templating/specs/variable.test.ts | 22 ++-- .../templating/specs/variable_srv.test.ts | 26 ++-- .../specs/variable_srv_init.test.ts | 16 +-- .../cloudwatch/specs/datasource.test.ts | 32 ++--- .../elasticsearch/specs/datasource.test.ts | 24 ++-- .../elasticsearch/specs/index_pattern.test.ts | 18 +-- .../elasticsearch/specs/query_builder.test.ts | 52 ++++---- .../elasticsearch/specs/query_def.test.ts | 18 +-- .../datasource/grafana-live/datasource.ts | 6 +- .../graphite/specs/datasource.test.ts | 2 +- .../datasource/graphite/specs/gfunc.test.ts | 42 +++---- .../datasource/graphite/specs/lexer.test.ts | 56 ++++----- .../datasource/graphite/specs/parser.test.ts | 80 ++++++------ .../influxdb/specs/influx_query.test.ts | 66 +++++----- .../influxdb/specs/influx_series.test.ts | 64 +++++----- .../influxdb/specs/query_builder.test.ts | 68 +++++----- .../influxdb/specs/query_part.test.ts | 32 ++--- .../influxdb/specs/response_parser.test.ts | 32 ++--- .../opentsdb/specs/datasource.test.ts | 4 +- .../opentsdb/specs/query_ctrl.test.ts | 2 +- .../prometheus/specs/datasource.test.ts | 118 +++++++++--------- .../specs/result_transformer.test.ts | 12 +- .../panel/graph/specs/data_processor.test.ts | 10 +- .../plugins/panel/graph/specs/graph.test.ts | 16 +-- .../panel/graph/specs/graph_ctrl.test.ts | 8 +- .../panel/graph/specs/graph_tooltip.test.ts | 24 ++-- .../graph/specs/threshold_manager.test.ts | 28 ++--- .../panel/heatmap/specs/heatmap_ctrl.test.ts | 8 +- .../singlestat/specs/singlestat_panel.test.ts | 6 +- .../panel/table/specs/renderer.test.ts | 76 +++++------ .../panel/table/specs/transformers.test.ts | 40 +++--- public/test/jest-setup.ts | 2 +- public/test/specs/helpers.ts | 10 +- 45 files changed, 650 insertions(+), 650 deletions(-) diff --git a/public/app/features/alerting/specs/threshold_mapper.test.ts b/public/app/features/alerting/specs/threshold_mapper.test.ts index b9fa45a6e49..922d9c8787e 100644 --- a/public/app/features/alerting/specs/threshold_mapper.test.ts +++ b/public/app/features/alerting/specs/threshold_mapper.test.ts @@ -5,7 +5,7 @@ import { ThresholdMapper } from '../threshold_mapper'; describe('ThresholdMapper', () => { describe('with greater than evaluator', () => { it('can map query conditions to thresholds', () => { - var panel: any = { + const panel: any = { type: 'graph', alert: { conditions: [ @@ -17,7 +17,7 @@ describe('ThresholdMapper', () => { }, }; - var updated = ThresholdMapper.alertToGraphThresholds(panel); + const updated = ThresholdMapper.alertToGraphThresholds(panel); expect(updated).toBe(true); expect(panel.thresholds[0].op).toBe('gt'); expect(panel.thresholds[0].value).toBe(100); @@ -26,7 +26,7 @@ describe('ThresholdMapper', () => { describe('with outside range evaluator', () => { it('can map query conditions to thresholds', () => { - var panel: any = { + const panel: any = { type: 'graph', alert: { conditions: [ @@ -38,7 +38,7 @@ describe('ThresholdMapper', () => { }, }; - var updated = ThresholdMapper.alertToGraphThresholds(panel); + const updated = ThresholdMapper.alertToGraphThresholds(panel); expect(updated).toBe(true); expect(panel.thresholds[0].op).toBe('lt'); expect(panel.thresholds[0].value).toBe(100); @@ -50,7 +50,7 @@ describe('ThresholdMapper', () => { describe('with inside range evaluator', () => { it('can map query conditions to thresholds', () => { - var panel: any = { + const panel: any = { type: 'graph', alert: { conditions: [ @@ -62,7 +62,7 @@ describe('ThresholdMapper', () => { }, }; - var updated = ThresholdMapper.alertToGraphThresholds(panel); + const updated = ThresholdMapper.alertToGraphThresholds(panel); expect(updated).toBe(true); expect(panel.thresholds[0].op).toBe('gt'); expect(panel.thresholds[0].value).toBe(100); diff --git a/public/app/features/dashboard/specs/dashboard_model.test.ts b/public/app/features/dashboard/specs/dashboard_model.test.ts index 28029653a6c..24d036a8233 100644 --- a/public/app/features/dashboard/specs/dashboard_model.test.ts +++ b/public/app/features/dashboard/specs/dashboard_model.test.ts @@ -6,7 +6,7 @@ jest.mock('app/core/services/context_srv', () => ({})); describe('DashboardModel', function() { describe('when creating new dashboard model defaults only', function() { - var model; + let model; beforeEach(function() { model = new DashboardModel({}, {}); @@ -27,7 +27,7 @@ describe('DashboardModel', function() { }); describe('when getting next panel id', function() { - var model; + let model; beforeEach(function() { model = new DashboardModel({ @@ -42,16 +42,16 @@ describe('DashboardModel', function() { describe('getSaveModelClone', function() { it('should sort keys', () => { - var model = new DashboardModel({}); - var saveModel = model.getSaveModelClone(); - var keys = _.keys(saveModel); + const model = new DashboardModel({}); + const saveModel = model.getSaveModelClone(); + const keys = _.keys(saveModel); expect(keys[0]).toBe('annotations'); expect(keys[1]).toBe('autoUpdate'); }); it('should remove add panel panels', () => { - var model = new DashboardModel({}); + const model = new DashboardModel({}); model.addPanel({ type: 'add-panel', }); @@ -61,15 +61,15 @@ describe('DashboardModel', function() { model.addPanel({ type: 'add-panel', }); - var saveModel = model.getSaveModelClone(); - var panels = saveModel.panels; + const saveModel = model.getSaveModelClone(); + const panels = saveModel.panels; expect(panels.length).toBe(1); }); }); describe('row and panel manipulation', function() { - var dashboard; + let dashboard; beforeEach(function() { dashboard = new DashboardModel({}); @@ -82,7 +82,7 @@ describe('DashboardModel', function() { }); it('duplicate panel should try to add to the right if there is space', function() { - var panel = { id: 10, gridPos: { x: 0, y: 0, w: 6, h: 2 } }; + const panel = { id: 10, gridPos: { x: 0, y: 0, w: 6, h: 2 } }; dashboard.addPanel(panel); dashboard.duplicatePanel(dashboard.panels[0]); @@ -96,7 +96,7 @@ describe('DashboardModel', function() { }); it('duplicate panel should remove repeat data', function() { - var panel = { + const panel = { id: 10, gridPos: { x: 0, y: 0, w: 6, h: 2 }, repeat: 'asd', @@ -112,7 +112,7 @@ describe('DashboardModel', function() { }); describe('Given editable false dashboard', function() { - var model; + let model; beforeEach(function() { model = new DashboardModel({ editable: false }); @@ -124,14 +124,14 @@ describe('DashboardModel', function() { }); it('getSaveModelClone should remove meta', function() { - var clone = model.getSaveModelClone(); + const clone = model.getSaveModelClone(); expect(clone.meta).toBe(undefined); }); }); describe('when loading dashboard with old influxdb query schema', function() { - var model; - var target; + let model; + let target; beforeEach(function() { model = new DashboardModel({ @@ -197,7 +197,7 @@ describe('DashboardModel', function() { }); describe('when creating dashboard model with missing list for annoations or templating', function() { - var model; + let model; beforeEach(function() { model = new DashboardModel({ @@ -222,7 +222,7 @@ describe('DashboardModel', function() { }); describe('Formatting epoch timestamp when timezone is set as utc', function() { - var dashboard; + let dashboard; beforeEach(function() { dashboard = new DashboardModel({ timezone: 'utc' }); @@ -242,7 +242,7 @@ describe('DashboardModel', function() { }); describe('updateSubmenuVisibility with empty lists', function() { - var model; + let model; beforeEach(function() { model = new DashboardModel({}); @@ -255,7 +255,7 @@ describe('DashboardModel', function() { }); describe('updateSubmenuVisibility with annotation', function() { - var model; + let model; beforeEach(function() { model = new DashboardModel({ @@ -272,7 +272,7 @@ describe('DashboardModel', function() { }); describe('updateSubmenuVisibility with template var', function() { - var model; + let model; beforeEach(function() { model = new DashboardModel({ @@ -289,7 +289,7 @@ describe('DashboardModel', function() { }); describe('updateSubmenuVisibility with hidden template var', function() { - var model; + let model; beforeEach(function() { model = new DashboardModel({ @@ -306,7 +306,7 @@ describe('DashboardModel', function() { }); describe('updateSubmenuVisibility with hidden annotation toggle', function() { - var dashboard; + let dashboard; beforeEach(function() { dashboard = new DashboardModel({ @@ -323,7 +323,7 @@ describe('DashboardModel', function() { }); describe('When collapsing row', function() { - var dashboard; + let dashboard; beforeEach(function() { dashboard = new DashboardModel({ @@ -365,7 +365,7 @@ describe('DashboardModel', function() { }); describe('When expanding row', function() { - var dashboard; + let dashboard; beforeEach(function() { dashboard = new DashboardModel({ diff --git a/public/app/features/dashboard/specs/exporter.test.ts b/public/app/features/dashboard/specs/exporter.test.ts index c7727a4af4d..c7a232f925b 100644 --- a/public/app/features/dashboard/specs/exporter.test.ts +++ b/public/app/features/dashboard/specs/exporter.test.ts @@ -10,7 +10,7 @@ import { DashboardExporter } from '../export/exporter'; import { DashboardModel } from '../dashboard_model'; describe('given dashboard with repeated panels', () => { - var dash, exported; + let dash, exported; beforeEach(done => { dash = { @@ -89,7 +89,7 @@ describe('given dashboard with repeated panels', () => { config.buildInfo.version = '3.0.2'; //Stubs test function calls - var datasourceSrvStub = { get: jest.fn(arg => getStub(arg)) }; + const datasourceSrvStub = { get: jest.fn(arg => getStub(arg)) }; config.panels['graph'] = { id: 'graph', @@ -110,7 +110,7 @@ describe('given dashboard with repeated panels', () => { }; dash = new DashboardModel(dash, {}); - var exporter = new DashboardExporter(datasourceSrvStub); + const exporter = new DashboardExporter(datasourceSrvStub); exporter.makeExportable(dash).then(clean => { exported = clean; done(); @@ -118,12 +118,12 @@ describe('given dashboard with repeated panels', () => { }); it('should replace datasource refs', () => { - var panel = exported.panels[0]; + const panel = exported.panels[0]; expect(panel.datasource).toBe('${DS_GFDB}'); }); it('should replace datasource refs in collapsed row', () => { - var panel = exported.panels[5].panels[0]; + const panel = exported.panels[5].panels[0]; expect(panel.datasource).toBe('${DS_GFDB}'); }); @@ -145,7 +145,7 @@ describe('given dashboard with repeated panels', () => { }); it('should add datasource to required', () => { - var require = _.find(exported.__requires, { name: 'TestDB' }); + const require = _.find(exported.__requires, { name: 'TestDB' }); expect(require.name).toBe('TestDB'); expect(require.id).toBe('testdb'); expect(require.type).toBe('datasource'); @@ -153,52 +153,52 @@ describe('given dashboard with repeated panels', () => { }); it('should not add built in datasources to required', () => { - var require = _.find(exported.__requires, { name: 'Mixed' }); + const require = _.find(exported.__requires, { name: 'Mixed' }); expect(require).toBe(undefined); }); it('should add datasources used in mixed mode', () => { - var require = _.find(exported.__requires, { name: 'OtherDB' }); + const require = _.find(exported.__requires, { name: 'OtherDB' }); expect(require).not.toBe(undefined); }); it('should add graph panel to required', () => { - var require = _.find(exported.__requires, { name: 'Graph' }); + const require = _.find(exported.__requires, { name: 'Graph' }); expect(require.name).toBe('Graph'); expect(require.id).toBe('graph'); expect(require.version).toBe('1.1.0'); }); it('should add table panel to required', () => { - var require = _.find(exported.__requires, { name: 'Table' }); + const require = _.find(exported.__requires, { name: 'Table' }); expect(require.name).toBe('Table'); expect(require.id).toBe('table'); expect(require.version).toBe('1.1.1'); }); it('should add heatmap panel to required', () => { - var require = _.find(exported.__requires, { name: 'Heatmap' }); + const require = _.find(exported.__requires, { name: 'Heatmap' }); expect(require.name).toBe('Heatmap'); expect(require.id).toBe('heatmap'); expect(require.version).toBe('1.1.2'); }); it('should add grafana version', () => { - var require = _.find(exported.__requires, { name: 'Grafana' }); + const require = _.find(exported.__requires, { name: 'Grafana' }); expect(require.type).toBe('grafana'); expect(require.id).toBe('grafana'); expect(require.version).toBe('3.0.2'); }); it('should add constant template variables as inputs', () => { - var input = _.find(exported.__inputs, { name: 'VAR_PREFIX' }); + const input = _.find(exported.__inputs, { name: 'VAR_PREFIX' }); expect(input.type).toBe('constant'); expect(input.label).toBe('prefix'); expect(input.value).toBe('collectd'); }); it('should templatize constant variables', () => { - var variable = _.find(exported.templating.list, { name: 'prefix' }); + const variable = _.find(exported.templating.list, { name: 'prefix' }); expect(variable.query).toBe('${VAR_PREFIX}'); expect(variable.current.text).toBe('${VAR_PREFIX}'); expect(variable.current.value).toBe('${VAR_PREFIX}'); @@ -208,7 +208,7 @@ describe('given dashboard with repeated panels', () => { }); // Stub responses -var stubs = []; +const stubs = []; stubs['gfdb'] = { name: 'gfdb', meta: { id: 'testdb', info: { version: '1.2.1' }, name: 'TestDB' }, diff --git a/public/app/features/dashboard/specs/save_as_modal.test.ts b/public/app/features/dashboard/specs/save_as_modal.test.ts index bb16d1bcc1c..29ed694474b 100644 --- a/public/app/features/dashboard/specs/save_as_modal.test.ts +++ b/public/app/features/dashboard/specs/save_as_modal.test.ts @@ -4,12 +4,12 @@ import { describe, it, expect } from 'test/lib/common'; describe('saving dashboard as', () => { function scenario(name, panel, verify) { describe(name, () => { - var json = { + const json = { title: 'name', panels: [panel], }; - var mockDashboardSrv = { + const mockDashboardSrv = { getCurrent: function() { return { id: 5, @@ -21,8 +21,8 @@ describe('saving dashboard as', () => { }, }; - var ctrl = new SaveDashboardAsModalCtrl(mockDashboardSrv); - var ctx: any = { + const ctrl = new SaveDashboardAsModalCtrl(mockDashboardSrv); + const ctx: any = { clone: ctrl.clone, ctrl: ctrl, panel: panel, @@ -35,14 +35,14 @@ describe('saving dashboard as', () => { } scenario('default values', {}, ctx => { - var clone = ctx.clone; + const clone = ctx.clone; expect(clone.id).toBe(null); expect(clone.title).toBe('name Copy'); expect(clone.editable).toBe(true); expect(clone.hideControls).toBe(false); }); - var graphPanel = { + const graphPanel = { id: 1, type: 'graph', alert: { rule: 1 }, diff --git a/public/app/features/dashboard/specs/save_provisioned_modal.test.ts b/public/app/features/dashboard/specs/save_provisioned_modal.test.ts index ce921cee8c8..fb1a652a03c 100644 --- a/public/app/features/dashboard/specs/save_provisioned_modal.test.ts +++ b/public/app/features/dashboard/specs/save_provisioned_modal.test.ts @@ -1,12 +1,12 @@ import { SaveProvisionedDashboardModalCtrl } from '../save_provisioned_modal'; describe('SaveProvisionedDashboardModalCtrl', () => { - var json = { + const json = { title: 'name', id: 5, }; - var mockDashboardSrv = { + const mockDashboardSrv = { getCurrent: function() { return { id: 5, @@ -18,7 +18,7 @@ describe('SaveProvisionedDashboardModalCtrl', () => { }, }; - var ctrl = new SaveProvisionedDashboardModalCtrl(mockDashboardSrv); + const ctrl = new SaveProvisionedDashboardModalCtrl(mockDashboardSrv); it('should remove id from dashboard model', () => { expect(ctrl.dash.id).toBeUndefined(); diff --git a/public/app/features/dashboard/specs/share_modal_ctrl.test.ts b/public/app/features/dashboard/specs/share_modal_ctrl.test.ts index 35261256566..796baf7f522 100644 --- a/public/app/features/dashboard/specs/share_modal_ctrl.test.ts +++ b/public/app/features/dashboard/specs/share_modal_ctrl.test.ts @@ -4,7 +4,7 @@ import config from 'app/core/config'; import { LinkSrv } from 'app/features/panellinks/link_srv'; describe('ShareModalCtrl', () => { - var ctx = { + const ctx = { timeSrv: { timeRange: () => { return { from: new Date(1000), to: new Date(2000) }; @@ -68,8 +68,8 @@ describe('ShareModalCtrl', () => { ctx.scope.panel = { id: 22 }; ctx.scope.init(); - var base = 'http://dashboards.grafana.com/render/d-solo/abcdefghi/my-dash'; - var params = '?from=1000&to=2000&orgId=1&panelId=22&width=1000&height=500&tz=UTC'; + const base = 'http://dashboards.grafana.com/render/d-solo/abcdefghi/my-dash'; + const params = '?from=1000&to=2000&orgId=1&panelId=22&width=1000&height=500&tz=UTC'; expect(ctx.scope.imageUrl).toContain(base + params); }); @@ -79,8 +79,8 @@ describe('ShareModalCtrl', () => { ctx.scope.panel = { id: 22 }; ctx.scope.init(); - var base = 'http://dashboards.grafana.com/render/dashboard-solo/script/my-dash.js'; - var params = '?from=1000&to=2000&orgId=1&panelId=22&width=1000&height=500&tz=UTC'; + const base = 'http://dashboards.grafana.com/render/dashboard-solo/script/my-dash.js'; + const params = '?from=1000&to=2000&orgId=1&panelId=22&width=1000&height=500&tz=UTC'; expect(ctx.scope.imageUrl).toContain(base + params); }); diff --git a/public/app/features/dashboard/specs/time_srv.test.ts b/public/app/features/dashboard/specs/time_srv.test.ts index f8d9e42cfd4..046ac52c9bf 100644 --- a/public/app/features/dashboard/specs/time_srv.test.ts +++ b/public/app/features/dashboard/specs/time_srv.test.ts @@ -3,25 +3,25 @@ import '../time_srv'; import moment from 'moment'; describe('timeSrv', function() { - var rootScope = { + const rootScope = { $on: jest.fn(), onAppEvent: jest.fn(), appEvent: jest.fn(), }; - var timer = { + const timer = { register: jest.fn(), cancel: jest.fn(), cancelAll: jest.fn(), }; - var location = { + let location = { search: jest.fn(() => ({})), }; - var timeSrv; + let timeSrv; - var _dashboard: any = { + const _dashboard: any = { time: { from: 'now-6h', to: 'now' }, getTimezone: jest.fn(() => 'browser'), }; @@ -34,14 +34,14 @@ describe('timeSrv', function() { describe('timeRange', function() { it('should return unparsed when parse is false', function() { timeSrv.setTime({ from: 'now', to: 'now-1h' }); - var time = timeSrv.timeRange(); + const time = timeSrv.timeRange(); expect(time.raw.from).toBe('now'); expect(time.raw.to).toBe('now-1h'); }); it('should return parsed when parse is true', function() { timeSrv.setTime({ from: 'now', to: 'now-1h' }); - var time = timeSrv.timeRange(); + const time = timeSrv.timeRange(); expect(moment.isMoment(time.from)).toBe(true); expect(moment.isMoment(time.to)).toBe(true); }); @@ -58,7 +58,7 @@ describe('timeSrv', function() { timeSrv = new TimeSrv(rootScope, jest.fn(), location, timer, { isGrafanaVisibile: jest.fn() }); timeSrv.init(_dashboard); - var time = timeSrv.timeRange(); + const time = timeSrv.timeRange(); expect(time.raw.from).toBe('now-2d'); expect(time.raw.to).toBe('now'); }); @@ -74,7 +74,7 @@ describe('timeSrv', function() { timeSrv = new TimeSrv(rootScope, jest.fn(), location, timer, { isGrafanaVisibile: jest.fn() }); timeSrv.init(_dashboard); - var time = timeSrv.timeRange(); + const time = timeSrv.timeRange(); expect(time.from.valueOf()).toEqual(new Date('2014-04-10T05:20:10Z').getTime()); expect(time.to.valueOf()).toEqual(new Date('2014-05-20T03:10:22Z').getTime()); }); @@ -90,7 +90,7 @@ describe('timeSrv', function() { timeSrv = new TimeSrv(rootScope, jest.fn(), location, timer, { isGrafanaVisibile: jest.fn() }); timeSrv.init(_dashboard); - var time = timeSrv.timeRange(); + const time = timeSrv.timeRange(); expect(time.from.valueOf()).toEqual(new Date('2014-04-10T00:00:00Z').getTime()); expect(time.to.valueOf()).toEqual(new Date('2014-05-20T00:00:00Z').getTime()); }); @@ -106,7 +106,7 @@ describe('timeSrv', function() { timeSrv = new TimeSrv(rootScope, jest.fn(), location, timer, { isGrafanaVisibile: jest.fn() }); timeSrv.init(_dashboard); - var time = timeSrv.timeRange(); + const time = timeSrv.timeRange(); expect(time.from.valueOf()).toEqual(1410337646373); expect(time.to.valueOf()).toEqual(1410337665699); }); diff --git a/public/app/features/dashboard/specs/viewstate_srv.test.ts b/public/app/features/dashboard/specs/viewstate_srv.test.ts index 740e3c3b9a8..905ffb8b355 100644 --- a/public/app/features/dashboard/specs/viewstate_srv.test.ts +++ b/public/app/features/dashboard/specs/viewstate_srv.test.ts @@ -37,7 +37,7 @@ describe('when updating view state', () => { }); it('should update querystring and view state', () => { - var updateState = { fullscreen: true, edit: true, panelId: 1 }; + const updateState = { fullscreen: true, edit: true, panelId: 1 }; viewState.update(updateState); diff --git a/public/app/features/panellinks/specs/link_srv.test.ts b/public/app/features/panellinks/specs/link_srv.test.ts index 521a4edef15..9c6b62d4b69 100644 --- a/public/app/features/panellinks/specs/link_srv.test.ts +++ b/public/app/features/panellinks/specs/link_srv.test.ts @@ -7,9 +7,9 @@ jest.mock('angular', () => { }); describe('linkSrv', function() { - var linkSrv; - var templateSrvMock = {}; - var timeSrvMock = {}; + let linkSrv; + const templateSrvMock = {}; + const timeSrvMock = {}; beforeEach(() => { linkSrv = new LinkSrv(templateSrvMock, timeSrvMock); @@ -17,29 +17,29 @@ describe('linkSrv', function() { describe('when appending query strings', function() { it('add ? to URL if not present', function() { - var url = linkSrv.appendToQueryString('http://example.com', 'foo=bar'); + const url = linkSrv.appendToQueryString('http://example.com', 'foo=bar'); expect(url).toBe('http://example.com?foo=bar'); }); it('do not add & to URL if ? is present but query string is empty', function() { - var url = linkSrv.appendToQueryString('http://example.com?', 'foo=bar'); + const url = linkSrv.appendToQueryString('http://example.com?', 'foo=bar'); expect(url).toBe('http://example.com?foo=bar'); }); it('add & to URL if query string is present', function() { - var url = linkSrv.appendToQueryString('http://example.com?foo=bar', 'hello=world'); + const url = linkSrv.appendToQueryString('http://example.com?foo=bar', 'hello=world'); expect(url).toBe('http://example.com?foo=bar&hello=world'); }); it('do not change the URL if there is nothing to append', function() { _.each(['', undefined, null], function(toAppend) { - var url1 = linkSrv.appendToQueryString('http://example.com', toAppend); + const url1 = linkSrv.appendToQueryString('http://example.com', toAppend); expect(url1).toBe('http://example.com'); - var url2 = linkSrv.appendToQueryString('http://example.com?', toAppend); + const url2 = linkSrv.appendToQueryString('http://example.com?', toAppend); expect(url2).toBe('http://example.com?'); - var url3 = linkSrv.appendToQueryString('http://example.com?foo=bar', toAppend); + const url3 = linkSrv.appendToQueryString('http://example.com?foo=bar', toAppend); expect(url3).toBe('http://example.com?foo=bar'); }); }); diff --git a/public/app/features/templating/specs/adhoc_variable.test.ts b/public/app/features/templating/specs/adhoc_variable.test.ts index a7b20e8d029..f85c49e73d5 100644 --- a/public/app/features/templating/specs/adhoc_variable.test.ts +++ b/public/app/features/templating/specs/adhoc_variable.test.ts @@ -3,21 +3,21 @@ import { AdhocVariable } from '../adhoc_variable'; describe('AdhocVariable', function() { describe('when serializing to url', function() { it('should set return key value and op separated by pipe', function() { - var variable = new AdhocVariable({ + const variable = new AdhocVariable({ filters: [ { key: 'key1', operator: '=', value: 'value1' }, { key: 'key2', operator: '!=', value: 'value2' }, { key: 'key3', operator: '=', value: 'value3a|value3b|value3c' }, ], }); - var urlValue = variable.getValueForUrl(); + const urlValue = variable.getValueForUrl(); expect(urlValue).toMatchObject(['key1|=|value1', 'key2|!=|value2', 'key3|=|value3a__gfp__value3b__gfp__value3c']); }); }); describe('when deserializing from url', function() { it('should restore filters', function() { - var variable = new AdhocVariable({}); + const variable = new AdhocVariable({}); variable.setValueFromUrl(['key1|=|value1', 'key2|!=|value2', 'key3|=|value3a__gfp__value3b__gfp__value3c']); expect(variable.filters[0].key).toBe('key1'); diff --git a/public/app/features/templating/specs/query_variable.test.ts b/public/app/features/templating/specs/query_variable.test.ts index 39c51874586..85a36702d3c 100644 --- a/public/app/features/templating/specs/query_variable.test.ts +++ b/public/app/features/templating/specs/query_variable.test.ts @@ -3,7 +3,7 @@ import { QueryVariable } from '../query_variable'; describe('QueryVariable', () => { describe('when creating from model', () => { it('should set defaults', () => { - var variable = new QueryVariable({}, null, null, null, null); + const variable = new QueryVariable({}, null, null, null, null); expect(variable.datasource).toBe(null); expect(variable.refresh).toBe(0); expect(variable.sort).toBe(0); @@ -15,13 +15,13 @@ describe('QueryVariable', () => { }); it('get model should copy changes back to model', () => { - var variable = new QueryVariable({}, null, null, null, null); + const variable = new QueryVariable({}, null, null, null, null); variable.options = [{ text: 'test' }]; variable.datasource = 'google'; variable.regex = 'asd'; variable.sort = 50; - var model = variable.getSaveModel(); + const model = variable.getSaveModel(); expect(model.options.length).toBe(1); expect(model.options[0].text).toBe('test'); expect(model.datasource).toBe('google'); @@ -30,11 +30,11 @@ describe('QueryVariable', () => { }); it('if refresh != 0 then remove options in presisted mode', () => { - var variable = new QueryVariable({}, null, null, null, null); + const variable = new QueryVariable({}, null, null, null, null); variable.options = [{ text: 'test' }]; variable.refresh = 1; - var model = variable.getSaveModel(); + const model = variable.getSaveModel(); expect(model.options.length).toBe(0); }); }); @@ -69,7 +69,7 @@ describe('QueryVariable', () => { }); it('should return in same order', () => { - var i = 0; + let i = 0; expect(result.length).toBe(11); expect(result[i++].text).toBe(''); expect(result[i++].text).toBe('0'); @@ -90,7 +90,7 @@ describe('QueryVariable', () => { }); it('should return in same order', () => { - var i = 0; + let i = 0; expect(result.length).toBe(11); expect(result[i++].text).toBe(''); expect(result[i++].text).toBe('0'); diff --git a/public/app/features/templating/specs/template_srv.test.ts b/public/app/features/templating/specs/template_srv.test.ts index 86b6aa7ec99..984d62cb729 100644 --- a/public/app/features/templating/specs/template_srv.test.ts +++ b/public/app/features/templating/specs/template_srv.test.ts @@ -1,7 +1,7 @@ import { TemplateSrv } from '../template_srv'; describe('templateSrv', function() { - var _templateSrv; + let _templateSrv; function initTemplateSrv(variables) { _templateSrv = new TemplateSrv(); @@ -14,7 +14,7 @@ describe('templateSrv', function() { }); it('should initialize template data', function() { - var target = _templateSrv.replace('this.[[test]].filters'); + const target = _templateSrv.replace('this.[[test]].filters'); expect(target).toBe('this.oogle.filters'); }); }); @@ -25,42 +25,42 @@ describe('templateSrv', function() { }); it('should replace $test with scoped value', function() { - var target = _templateSrv.replace('this.$test.filters', { + const target = _templateSrv.replace('this.$test.filters', { test: { value: 'mupp', text: 'asd' }, }); expect(target).toBe('this.mupp.filters'); }); it('should replace ${test} with scoped value', function() { - var target = _templateSrv.replace('this.${test}.filters', { + const target = _templateSrv.replace('this.${test}.filters', { test: { value: 'mupp', text: 'asd' }, }); expect(target).toBe('this.mupp.filters'); }); it('should replace ${test:glob} with scoped value', function() { - var target = _templateSrv.replace('this.${test:glob}.filters', { + const target = _templateSrv.replace('this.${test:glob}.filters', { test: { value: 'mupp', text: 'asd' }, }); expect(target).toBe('this.mupp.filters'); }); it('should replace $test with scoped text', function() { - var target = _templateSrv.replaceWithText('this.$test.filters', { + const target = _templateSrv.replaceWithText('this.$test.filters', { test: { value: 'mupp', text: 'asd' }, }); expect(target).toBe('this.asd.filters'); }); it('should replace ${test} with scoped text', function() { - var target = _templateSrv.replaceWithText('this.${test}.filters', { + const target = _templateSrv.replaceWithText('this.${test}.filters', { test: { value: 'mupp', text: 'asd' }, }); expect(target).toBe('this.asd.filters'); }); it('should replace ${test:glob} with scoped text', function() { - var target = _templateSrv.replaceWithText('this.${test:glob}.filters', { + const target = _templateSrv.replaceWithText('this.${test:glob}.filters', { test: { value: 'mupp', text: 'asd' }, }); expect(target).toBe('this.asd.filters'); @@ -81,17 +81,17 @@ describe('templateSrv', function() { }); it('should return filters if datasourceName match', function() { - var filters = _templateSrv.getAdhocFilters('oogle'); + const filters = _templateSrv.getAdhocFilters('oogle'); expect(filters).toMatchObject([1]); }); it('should return empty array if datasourceName does not match', function() { - var filters = _templateSrv.getAdhocFilters('oogleasdasd'); + const filters = _templateSrv.getAdhocFilters('oogleasdasd'); expect(filters).toMatchObject([]); }); it('should return filters when datasourceName match via data source variable', function() { - var filters = _templateSrv.getAdhocFilters('logstash'); + const filters = _templateSrv.getAdhocFilters('logstash'); expect(filters).toMatchObject([2]); }); }); @@ -108,37 +108,37 @@ describe('templateSrv', function() { }); it('should replace $test with globbed value', function() { - var target = _templateSrv.replace('this.$test.filters', {}, 'glob'); + const target = _templateSrv.replace('this.$test.filters', {}, 'glob'); expect(target).toBe('this.{value1,value2}.filters'); }); it('should replace ${test} with globbed value', function() { - var target = _templateSrv.replace('this.${test}.filters', {}, 'glob'); + const target = _templateSrv.replace('this.${test}.filters', {}, 'glob'); expect(target).toBe('this.{value1,value2}.filters'); }); it('should replace ${test:glob} with globbed value', function() { - var target = _templateSrv.replace('this.${test:glob}.filters', {}); + const target = _templateSrv.replace('this.${test:glob}.filters', {}); expect(target).toBe('this.{value1,value2}.filters'); }); it('should replace $test with piped value', function() { - var target = _templateSrv.replace('this=$test', {}, 'pipe'); + const target = _templateSrv.replace('this=$test', {}, 'pipe'); expect(target).toBe('this=value1|value2'); }); it('should replace ${test} with piped value', function() { - var target = _templateSrv.replace('this=${test}', {}, 'pipe'); + const target = _templateSrv.replace('this=${test}', {}, 'pipe'); expect(target).toBe('this=value1|value2'); }); it('should replace ${test:pipe} with piped value', function() { - var target = _templateSrv.replace('this=${test:pipe}', {}); + const target = _templateSrv.replace('this=${test:pipe}', {}); expect(target).toBe('this=value1|value2'); }); it('should replace ${test:pipe} with piped value and $test with globbed value', function() { - var target = _templateSrv.replace('${test:pipe},$test', {}, 'glob'); + const target = _templateSrv.replace('${test:pipe},$test', {}, 'glob'); expect(target).toBe('value1|value2,{value1,value2}'); }); }); @@ -156,22 +156,22 @@ describe('templateSrv', function() { }); it('should replace $test with formatted all value', function() { - var target = _templateSrv.replace('this.$test.filters', {}, 'glob'); + const target = _templateSrv.replace('this.$test.filters', {}, 'glob'); expect(target).toBe('this.{value1,value2}.filters'); }); it('should replace ${test} with formatted all value', function() { - var target = _templateSrv.replace('this.${test}.filters', {}, 'glob'); + const target = _templateSrv.replace('this.${test}.filters', {}, 'glob'); expect(target).toBe('this.{value1,value2}.filters'); }); it('should replace ${test:glob} with formatted all value', function() { - var target = _templateSrv.replace('this.${test:glob}.filters', {}); + const target = _templateSrv.replace('this.${test:glob}.filters', {}); expect(target).toBe('this.{value1,value2}.filters'); }); it('should replace ${test:pipe} with piped value and $test with globbed value', function() { - var target = _templateSrv.replace('${test:pipe},$test', {}, 'glob'); + const target = _templateSrv.replace('${test:pipe},$test', {}, 'glob'); expect(target).toBe('value1|value2,{value1,value2}'); }); }); @@ -190,22 +190,22 @@ describe('templateSrv', function() { }); it('should replace $test with formatted all value', function() { - var target = _templateSrv.replace('this.$test.filters', {}, 'glob'); + const target = _templateSrv.replace('this.$test.filters', {}, 'glob'); expect(target).toBe('this.*.filters'); }); it('should replace ${test} with formatted all value', function() { - var target = _templateSrv.replace('this.${test}.filters', {}, 'glob'); + const target = _templateSrv.replace('this.${test}.filters', {}, 'glob'); expect(target).toBe('this.*.filters'); }); it('should replace ${test:glob} with formatted all value', function() { - var target = _templateSrv.replace('this.${test:glob}.filters', {}); + const target = _templateSrv.replace('this.${test:glob}.filters', {}); expect(target).toBe('this.*.filters'); }); it('should not escape custom all value', function() { - var target = _templateSrv.replace('this.$test', {}, 'regex'); + const target = _templateSrv.replace('this.$test', {}, 'regex'); expect(target).toBe('this.*'); }); }); @@ -213,70 +213,70 @@ describe('templateSrv', function() { describe('lucene format', function() { it('should properly escape $test with lucene escape sequences', function() { initTemplateSrv([{ type: 'query', name: 'test', current: { value: 'value/4' } }]); - var target = _templateSrv.replace('this:$test', {}, 'lucene'); + const target = _templateSrv.replace('this:$test', {}, 'lucene'); expect(target).toBe('this:value\\/4'); }); it('should properly escape ${test} with lucene escape sequences', function() { initTemplateSrv([{ type: 'query', name: 'test', current: { value: 'value/4' } }]); - var target = _templateSrv.replace('this:${test}', {}, 'lucene'); + const target = _templateSrv.replace('this:${test}', {}, 'lucene'); expect(target).toBe('this:value\\/4'); }); it('should properly escape ${test:lucene} with lucene escape sequences', function() { initTemplateSrv([{ type: 'query', name: 'test', current: { value: 'value/4' } }]); - var target = _templateSrv.replace('this:${test:lucene}', {}); + const target = _templateSrv.replace('this:${test:lucene}', {}); expect(target).toBe('this:value\\/4'); }); }); describe('format variable to string values', function() { it('single value should return value', function() { - var result = _templateSrv.formatValue('test'); + const result = _templateSrv.formatValue('test'); expect(result).toBe('test'); }); it('multi value and glob format should render glob string', function() { - var result = _templateSrv.formatValue(['test', 'test2'], 'glob'); + const result = _templateSrv.formatValue(['test', 'test2'], 'glob'); expect(result).toBe('{test,test2}'); }); it('multi value and lucene should render as lucene expr', function() { - var result = _templateSrv.formatValue(['test', 'test2'], 'lucene'); + const result = _templateSrv.formatValue(['test', 'test2'], 'lucene'); expect(result).toBe('("test" OR "test2")'); }); it('multi value and regex format should render regex string', function() { - var result = _templateSrv.formatValue(['test.', 'test2'], 'regex'); + const result = _templateSrv.formatValue(['test.', 'test2'], 'regex'); expect(result).toBe('(test\\.|test2)'); }); it('multi value and pipe should render pipe string', function() { - var result = _templateSrv.formatValue(['test', 'test2'], 'pipe'); + const result = _templateSrv.formatValue(['test', 'test2'], 'pipe'); expect(result).toBe('test|test2'); }); it('multi value and distributed should render distributed string', function() { - var result = _templateSrv.formatValue(['test', 'test2'], 'distributed', { + const result = _templateSrv.formatValue(['test', 'test2'], 'distributed', { name: 'build', }); expect(result).toBe('test,build=test2'); }); it('multi value and distributed should render when not string', function() { - var result = _templateSrv.formatValue(['test'], 'distributed', { + const result = _templateSrv.formatValue(['test'], 'distributed', { name: 'build', }); expect(result).toBe('test'); }); it('multi value and csv format should render csv string', function() { - var result = _templateSrv.formatValue(['test', 'test2'], 'csv'); + const result = _templateSrv.formatValue(['test', 'test2'], 'csv'); expect(result).toBe('test,test2'); }); it('slash should be properly escaped in regex format', function() { - var result = _templateSrv.formatValue('Gi3/14', 'regex'); + const result = _templateSrv.formatValue('Gi3/14', 'regex'); expect(result).toBe('Gi3\\/14'); }); }); @@ -287,7 +287,7 @@ describe('templateSrv', function() { }); it('should return true if exists', function() { - var result = _templateSrv.variableExists('$test'); + const result = _templateSrv.variableExists('$test'); expect(result).toBe(true); }); }); @@ -298,17 +298,17 @@ describe('templateSrv', function() { }); it('should insert html', function() { - var result = _templateSrv.highlightVariablesAsHtml('$test'); + const result = _templateSrv.highlightVariablesAsHtml('$test'); expect(result).toBe('$test'); }); it('should insert html anywhere in string', function() { - var result = _templateSrv.highlightVariablesAsHtml('this $test ok'); + const result = _templateSrv.highlightVariablesAsHtml('this $test ok'); expect(result).toBe('this $test ok'); }); it('should ignore if variables does not exist', function() { - var result = _templateSrv.highlightVariablesAsHtml('this $google ok'); + const result = _templateSrv.highlightVariablesAsHtml('this $google ok'); expect(result).toBe('this $google ok'); }); }); @@ -319,7 +319,7 @@ describe('templateSrv', function() { }); it('should set current value and update template data', function() { - var target = _templateSrv.replace('this.[[test]].filters'); + const target = _templateSrv.replace('this.[[test]].filters'); expect(target).toBe('this.muuuu.filters'); }); }); @@ -339,7 +339,7 @@ describe('templateSrv', function() { }); it('should set multiple url params', function() { - var params = {}; + const params = {}; _templateSrv.fillVariableValuesForUrl(params); expect(params['var-test']).toMatchObject(['val1', 'val2']); }); @@ -360,7 +360,7 @@ describe('templateSrv', function() { }); it('should not include template variable value in url', function() { - var params = {}; + const params = {}; _templateSrv.fillVariableValuesForUrl(params); expect(params['var-test']).toBe(undefined); }); @@ -382,7 +382,7 @@ describe('templateSrv', function() { }); it('should not include template variable value in url', function() { - var params = {}; + const params = {}; _templateSrv.fillVariableValuesForUrl(params); expect(params['var-test']).toBe(undefined); }); @@ -394,7 +394,7 @@ describe('templateSrv', function() { }); it('should set scoped value as url params', function() { - var params = {}; + const params = {}; _templateSrv.fillVariableValuesForUrl(params, { test: { value: 'val1' }, }); @@ -408,7 +408,7 @@ describe('templateSrv', function() { }); it('should not set scoped value as url params', function() { - var params = {}; + const params = {}; _templateSrv.fillVariableValuesForUrl(params, { test: { name: 'test', value: 'val1', skipUrlSync: true }, }); @@ -435,7 +435,7 @@ describe('templateSrv', function() { }); it('should replace with text except for grafanaVariables', function() { - var target = _templateSrv.replaceWithText('Server: $server, period: $period'); + const target = _templateSrv.replaceWithText('Server: $server, period: $period'); expect(target).toBe('Server: All, period: 13m'); }); }); @@ -446,7 +446,7 @@ describe('templateSrv', function() { }); it('should replace $__interval_ms with interval milliseconds', function() { - var target = _templateSrv.replace('10 * $__interval_ms', { + const target = _templateSrv.replace('10 * $__interval_ms', { __interval_ms: { text: '100', value: '100' }, }); expect(target).toBe('10 * 100'); diff --git a/public/app/features/templating/specs/variable.test.ts b/public/app/features/templating/specs/variable.test.ts index cfe084957ec..814c5fbe003 100644 --- a/public/app/features/templating/specs/variable.test.ts +++ b/public/app/features/templating/specs/variable.test.ts @@ -2,38 +2,38 @@ import { containsVariable, assignModelProperties } from '../variable'; describe('containsVariable', function() { describe('when checking if a string contains a variable', function() { - it('should find it with $var syntax', function() { - var contains = containsVariable('this.$test.filters', 'test'); + it('should find it with $const syntax', function() { + const contains = containsVariable('this.$test.filters', 'test'); expect(contains).toBe(true); }); - it('should not find it if only part matches with $var syntax', function() { - var contains = containsVariable('this.$serverDomain.filters', 'server'); + it('should not find it if only part matches with $const syntax', function() { + const contains = containsVariable('this.$serverDomain.filters', 'server'); expect(contains).toBe(false); }); it('should find it if it ends with variable and passing multiple test strings', function() { - var contains = containsVariable('show field keys from $pgmetric', 'test string2', 'pgmetric'); + const contains = containsVariable('show field keys from $pgmetric', 'test string2', 'pgmetric'); expect(contains).toBe(true); }); it('should find it with [[var]] syntax', function() { - var contains = containsVariable('this.[[test]].filters', 'test'); + const contains = containsVariable('this.[[test]].filters', 'test'); expect(contains).toBe(true); }); it('should find it when part of segment', function() { - var contains = containsVariable('metrics.$env.$group-*', 'group'); + const contains = containsVariable('metrics.$env.$group-*', 'group'); expect(contains).toBe(true); }); it('should find it its the only thing', function() { - var contains = containsVariable('$env', 'env'); + const contains = containsVariable('$env', 'env'); expect(contains).toBe(true); }); it('should be able to pass in multiple test strings', function() { - var contains = containsVariable('asd', 'asd2.$env', 'env'); + const contains = containsVariable('asd', 'asd2.$env', 'env'); expect(contains).toBe(true); }); }); @@ -41,14 +41,14 @@ describe('containsVariable', function() { describe('assignModelProperties', function() { it('only set properties defined in defaults', function() { - var target: any = { test: 'asd' }; + const target: any = { test: 'asd' }; assignModelProperties(target, { propA: 1, propB: 2 }, { propB: 0 }); expect(target.propB).toBe(2); expect(target.test).toBe('asd'); }); it('use default value if not found on source', function() { - var target: any = { test: 'asd' }; + const target: any = { test: 'asd' }; assignModelProperties(target, { propA: 1, propB: 2 }, { propC: 10 }); expect(target.propC).toBe(10); }); diff --git a/public/app/features/templating/specs/variable_srv.test.ts b/public/app/features/templating/specs/variable_srv.test.ts index f7796434b5e..28fd3860ed3 100644 --- a/public/app/features/templating/specs/variable_srv.test.ts +++ b/public/app/features/templating/specs/variable_srv.test.ts @@ -4,7 +4,7 @@ import moment from 'moment'; import $q from 'q'; describe('VariableSrv', function() { - var ctx = { + const ctx = { datasourceSrv: {}, timeSrv: { timeRange: () => {}, @@ -33,7 +33,7 @@ describe('VariableSrv', function() { function describeUpdateVariable(desc, fn) { describe(desc, () => { - var scenario: any = {}; + const scenario: any = {}; scenario.setup = function(setupFn) { scenario.setupFn = setupFn; }; @@ -41,7 +41,7 @@ describe('VariableSrv', function() { beforeEach(async () => { scenario.setupFn(); - var ds: any = {}; + const ds: any = {}; ds.metricFindQuery = () => Promise.resolve(scenario.queryResult); ctx.variableSrv = new VariableSrv(ctx.$rootScope, $q, ctx.$location, ctx.$injector, ctx.templateSrv); @@ -100,7 +100,7 @@ describe('VariableSrv', function() { auto_count: 10, }; - var range = { + const range = { from: moment(new Date()) .subtract(7, 'days') .toDate(), @@ -118,7 +118,7 @@ describe('VariableSrv', function() { }); it('should set $__auto_interval_test', () => { - var call = ctx.templateSrv.setGrafanaVariable.mock.calls[0]; + const call = ctx.templateSrv.setGrafanaVariable.mock.calls[0]; expect(call[0]).toBe('$__auto_interval_test'); expect(call[1]).toBe('12h'); }); @@ -126,7 +126,7 @@ describe('VariableSrv', function() { // updateAutoValue() gets called twice: once directly once via VariableSrv.validateVariableSelectionState() // So use lastCall instead of a specific call number it('should set $__auto_interval', () => { - var call = ctx.templateSrv.setGrafanaVariable.mock.calls.pop(); + const call = ctx.templateSrv.setGrafanaVariable.mock.calls.pop(); expect(call[0]).toBe('$__auto_interval'); expect(call[1]).toBe('12h'); }); @@ -503,10 +503,10 @@ describe('VariableSrv', function() { }); describe('multiple interval variables with auto', () => { - var variable1, variable2; + let variable1, variable2; beforeEach(() => { - var range = { + const range = { from: moment(new Date()) .subtract(7, 'days') .toDate(), @@ -515,7 +515,7 @@ describe('VariableSrv', function() { ctx.timeSrv.timeRange = () => range; ctx.templateSrv.setGrafanaVariable = jest.fn(); - var variableModel1 = { + const variableModel1 = { type: 'interval', query: '1s,2h,5h,1d', name: 'variable1', @@ -525,7 +525,7 @@ describe('VariableSrv', function() { variable1 = ctx.variableSrv.createVariableFromModel(variableModel1); ctx.variableSrv.addVariable(variable1); - var variableModel2 = { + const variableModel2 = { type: 'interval', query: '1s,2h,5h', name: 'variable2', @@ -550,14 +550,14 @@ describe('VariableSrv', function() { }); it('should correctly set $__auto_interval_variableX', () => { - var variable1Set, + let variable1Set, variable2Set, legacySet, unknownSet = false; // updateAutoValue() gets called repeatedly: once directly once via VariableSrv.validateVariableSelectionState() // So check that all calls are valid rather than expect a specific number and/or ordering of calls - for (var i = 0; i < ctx.templateSrv.setGrafanaVariable.mock.calls.length; i++) { - var call = ctx.templateSrv.setGrafanaVariable.mock.calls[i]; + for (let i = 0; i < ctx.templateSrv.setGrafanaVariable.mock.calls.length; i++) { + const call = ctx.templateSrv.setGrafanaVariable.mock.calls[i]; switch (call[0]) { case '$__auto_interval_variable1': expect(call[1]).toBe('12h'); 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 e011d4d0d15..f06f533e429 100644 --- a/public/app/features/templating/specs/variable_srv_init.test.ts +++ b/public/app/features/templating/specs/variable_srv_init.test.ts @@ -26,7 +26,7 @@ describe('VariableSrv init', function() { function describeInitScenario(desc, fn) { describe(desc, () => { - var scenario: any = { + const scenario: any = { urlParams: {}, setup: setupFn => { scenario.setupFn = setupFn; @@ -92,7 +92,7 @@ describe('VariableSrv init', function() { }); describe('given dependent variables', () => { - var variableList = [ + const variableList = [ { name: 'app', type: 'query', @@ -110,7 +110,7 @@ describe('VariableSrv init', function() { }, ]; - describeInitScenario('when setting parent var from url', scenario => { + describeInitScenario('when setting parent const from url', scenario => { scenario.setup(() => { scenario.variables = _.cloneDeep(variableList); scenario.urlParams['var-app'] = 'google'; @@ -148,7 +148,7 @@ describe('VariableSrv init', function() { }); it('should update current value', () => { - var variable = ctx.variableSrv.variables[0]; + const variable = ctx.variableSrv.variables[0]; expect(variable.options.length).toBe(2); }); }); @@ -172,7 +172,7 @@ describe('VariableSrv init', function() { }); it('should update current value', () => { - var variable = ctx.variableSrv.variables[0]; + const variable = ctx.variableSrv.variables[0]; expect(variable.current.value.length).toBe(2); expect(variable.current.value[0]).toBe('val2'); expect(variable.current.value[1]).toBe('val1'); @@ -182,7 +182,7 @@ describe('VariableSrv init', function() { }); it('should set options that are not in value to selected false', () => { - var variable = ctx.variableSrv.variables[0]; + const variable = ctx.variableSrv.variables[0]; expect(variable.options[2].selected).toBe(false); }); }); @@ -206,7 +206,7 @@ describe('VariableSrv init', function() { }); it('should update current value', () => { - var variable = ctx.variableSrv.variables[0]; + const variable = ctx.variableSrv.variables[0]; expect(variable.current.value.length).toBe(2); expect(variable.current.value[0]).toBe('val2'); expect(variable.current.value[1]).toBe('val1'); @@ -216,7 +216,7 @@ describe('VariableSrv init', function() { }); it('should set options that are not in value to selected false', () => { - var variable = ctx.variableSrv.variables[0]; + const variable = ctx.variableSrv.variables[0]; expect(variable.options[2].selected).toBe(false); }); }); diff --git a/public/app/plugins/datasource/cloudwatch/specs/datasource.test.ts b/public/app/plugins/datasource/cloudwatch/specs/datasource.test.ts index eae3e91d37d..08329ba4e73 100644 --- a/public/app/plugins/datasource/cloudwatch/specs/datasource.test.ts +++ b/public/app/plugins/datasource/cloudwatch/specs/datasource.test.ts @@ -35,9 +35,9 @@ describe('CloudWatchDatasource', function() { }); describe('When performing CloudWatch query', function() { - var requestParams; + let requestParams; - var query = { + const query = { range: { from: 'now-1h', to: 'now' }, rangeRaw: { from: 1483228800, to: 1483232400 }, targets: [ @@ -54,7 +54,7 @@ describe('CloudWatchDatasource', function() { ], }; - var response = { + const response = { timings: [null], results: { A: { @@ -82,7 +82,7 @@ describe('CloudWatchDatasource', function() { it('should generate the correct query', function(done) { ctx.ds.query(query).then(function() { - var params = requestParams.queries[0]; + const params = requestParams.queries[0]; expect(params.namespace).toBe(query.targets[0].namespace); expect(params.metricName).toBe(query.targets[0].metricName); expect(params.dimensions['InstanceId']).toBe('i-12345678'); @@ -97,7 +97,7 @@ describe('CloudWatchDatasource', function() { period: '10m', }; - var query = { + const query = { range: { from: 'now-1h', to: 'now' }, rangeRaw: { from: 1483228800, to: 1483232400 }, targets: [ @@ -115,14 +115,14 @@ describe('CloudWatchDatasource', function() { }; ctx.ds.query(query).then(function() { - var params = requestParams.queries[0]; + const params = requestParams.queries[0]; expect(params.period).toBe('600'); done(); }); }); it('should cancel query for invalid extended statistics', function() { - var query = { + const query = { range: { from: 'now-1h', to: 'now' }, rangeRaw: { from: 1483228800, to: 1483232400 }, targets: [ @@ -152,7 +152,7 @@ describe('CloudWatchDatasource', function() { describe('When query region is "default"', function() { it('should return the datasource region if empty or "default"', function() { - var defaultRegion = instanceSettings.jsonData.defaultRegion; + const defaultRegion = instanceSettings.jsonData.defaultRegion; expect(ctx.ds.getActualRegion()).toBe(defaultRegion); expect(ctx.ds.getActualRegion('')).toBe(defaultRegion); @@ -163,7 +163,7 @@ describe('CloudWatchDatasource', function() { expect(ctx.ds.getActualRegion('some-fake-region-1')).toBe('some-fake-region-1'); }); - var requestParams; + let requestParams; beforeEach(function() { ctx.ds.performTimeSeriesQuery = jest.fn(request => { requestParams = request; @@ -172,7 +172,7 @@ describe('CloudWatchDatasource', function() { }); it('should query for the datasource region if empty or "default"', function(done) { - var query = { + const query = { range: { from: 'now-1h', to: 'now' }, rangeRaw: { from: 1483228800, to: 1483232400 }, targets: [ @@ -197,7 +197,7 @@ describe('CloudWatchDatasource', function() { }); describe('When performing CloudWatch query for extended statistics', function() { - var query = { + const query = { range: { from: 'now-1h', to: 'now' }, rangeRaw: { from: 1483228800, to: 1483232400 }, targets: [ @@ -215,7 +215,7 @@ describe('CloudWatchDatasource', function() { ], }; - var response = { + const response = { timings: [null], results: { A: { @@ -379,10 +379,10 @@ describe('CloudWatchDatasource', function() { }); it('should caclculate the correct period', function() { - var hourSec = 60 * 60; - var daySec = hourSec * 24; - var start = 1483196400 * 1000; - var testData: any[] = [ + const hourSec = 60 * 60; + const daySec = hourSec * 24; + const start = 1483196400 * 1000; + const testData: any[] = [ [ { period: 60, namespace: 'AWS/EC2' }, { range: { from: new Date(start), to: new Date(start + 3600 * 1000) } }, diff --git a/public/app/plugins/datasource/elasticsearch/specs/datasource.test.ts b/public/app/plugins/datasource/elasticsearch/specs/datasource.test.ts index d1e2e3ba835..d37d1d86d54 100644 --- a/public/app/plugins/datasource/elasticsearch/specs/datasource.test.ts +++ b/public/app/plugins/datasource/elasticsearch/specs/datasource.test.ts @@ -53,7 +53,7 @@ describe('ElasticDatasource', function() { }); it('should translate index pattern to current day', function() { - var requestOptions; + let requestOptions; ctx.backendSrv.datasourceRequest = jest.fn(options => { requestOptions = options; return Promise.resolve({ data: {} }); @@ -61,13 +61,13 @@ describe('ElasticDatasource', function() { ctx.ds.testDatasource(); - var today = moment.utc().format('YYYY.MM.DD'); + const today = moment.utc().format('YYYY.MM.DD'); expect(requestOptions.url).toBe('http://es.com/asd-' + today + '/_mapping'); }); }); describe('When issuing metric query with interval pattern', function() { - var requestOptions, parts, header; + let requestOptions, parts, header; beforeEach(() => { createDatasource({ @@ -104,13 +104,13 @@ describe('ElasticDatasource', function() { }); it('should json escape lucene query', function() { - var body = angular.fromJson(parts[1]); + const body = angular.fromJson(parts[1]); expect(body.query.bool.filter[1].query_string.query).toBe('escape\\:test'); }); }); describe('When issuing document query', function() { - var requestOptions, parts, header; + let requestOptions, parts, header; beforeEach(function() { createDatasource({ @@ -147,7 +147,7 @@ describe('ElasticDatasource', function() { }); it('should set size', function() { - var body = angular.fromJson(parts[1]); + const body = angular.fromJson(parts[1]); expect(body.size).toBe(500); }); }); @@ -210,7 +210,7 @@ describe('ElasticDatasource', function() { query: '*', }) .then(fieldObjects => { - var fields = _.map(fieldObjects, 'text'); + const fields = _.map(fieldObjects, 'text'); expect(fields).toEqual([ '@timestamp', 'beat.name.raw', @@ -232,7 +232,7 @@ describe('ElasticDatasource', function() { type: 'number', }) .then(fieldObjects => { - var fields = _.map(fieldObjects, 'text'); + const fields = _.map(fieldObjects, 'text'); expect(fields).toEqual(['system.cpu.system', 'system.cpu.user', 'system.process.cpu.total']); }); @@ -243,14 +243,14 @@ describe('ElasticDatasource', function() { type: 'date', }) .then(fieldObjects => { - var fields = _.map(fieldObjects, 'text'); + const fields = _.map(fieldObjects, 'text'); expect(fields).toEqual(['@timestamp']); }); }); }); describe('When issuing aggregation query on es5.x', function() { - var requestOptions, parts, header; + let requestOptions, parts, header; beforeEach(function() { createDatasource({ @@ -287,13 +287,13 @@ describe('ElasticDatasource', function() { }); it('should set size to 0', function() { - var body = angular.fromJson(parts[1]); + const body = angular.fromJson(parts[1]); expect(body.size).toBe(0); }); }); describe('When issuing metricFind query on es5.x', function() { - var requestOptions, parts, header, body, results; + let requestOptions, parts, header, body, results; beforeEach(() => { createDatasource({ diff --git a/public/app/plugins/datasource/elasticsearch/specs/index_pattern.test.ts b/public/app/plugins/datasource/elasticsearch/specs/index_pattern.test.ts index 2f921e10425..c5cf4c9dee0 100644 --- a/public/app/plugins/datasource/elasticsearch/specs/index_pattern.test.ts +++ b/public/app/plugins/datasource/elasticsearch/specs/index_pattern.test.ts @@ -6,8 +6,8 @@ import { IndexPattern } from '../index_pattern'; describe('IndexPattern', () => { describe('when getting index for today', () => { test('should return correct index name', () => { - var pattern = new IndexPattern('[asd-]YYYY.MM.DD', 'Daily'); - var expected = 'asd-' + moment.utc().format('YYYY.MM.DD'); + const pattern = new IndexPattern('[asd-]YYYY.MM.DD', 'Daily'); + const expected = 'asd-' + moment.utc().format('YYYY.MM.DD'); expect(pattern.getIndexForToday()).toBe(expected); }); @@ -16,20 +16,20 @@ describe('IndexPattern', () => { describe('when getting index list for time range', () => { describe('no interval', () => { test('should return correct index', () => { - var pattern = new IndexPattern('my-metrics', null); - var from = new Date(2015, 4, 30, 1, 2, 3); - var to = new Date(2015, 5, 1, 12, 5, 6); + const pattern = new IndexPattern('my-metrics', null); + const from = new Date(2015, 4, 30, 1, 2, 3); + const to = new Date(2015, 5, 1, 12, 5, 6); expect(pattern.getIndexList(from, to)).toEqual('my-metrics'); }); }); describe('daily', () => { test('should return correct index list', () => { - var pattern = new IndexPattern('[asd-]YYYY.MM.DD', 'Daily'); - var from = new Date(1432940523000); - var to = new Date(1433153106000); + const pattern = new IndexPattern('[asd-]YYYY.MM.DD', 'Daily'); + const from = new Date(1432940523000); + const to = new Date(1433153106000); - var expected = ['asd-2015.05.29', 'asd-2015.05.30', 'asd-2015.05.31', 'asd-2015.06.01']; + const expected = ['asd-2015.05.29', 'asd-2015.05.30', 'asd-2015.05.31', 'asd-2015.06.01']; expect(pattern.getIndexList(from, to)).toEqual(expected); }); diff --git a/public/app/plugins/datasource/elasticsearch/specs/query_builder.test.ts b/public/app/plugins/datasource/elasticsearch/specs/query_builder.test.ts index 1dde47915d9..e4c9404e667 100644 --- a/public/app/plugins/datasource/elasticsearch/specs/query_builder.test.ts +++ b/public/app/plugins/datasource/elasticsearch/specs/query_builder.test.ts @@ -1,14 +1,14 @@ import { ElasticQueryBuilder } from '../query_builder'; describe('ElasticQueryBuilder', () => { - var builder; + let builder; beforeEach(() => { builder = new ElasticQueryBuilder({ timeField: '@timestamp' }); }); it('with defaults', () => { - var query = builder.build({ + const query = builder.build({ metrics: [{ type: 'Count', id: '0' }], timeField: '@timestamp', bucketAggs: [{ type: 'date_histogram', field: '@timestamp', id: '1' }], @@ -19,12 +19,12 @@ describe('ElasticQueryBuilder', () => { }); it('with defaults on es5.x', () => { - var builder_5x = new ElasticQueryBuilder({ + const builder_5x = new ElasticQueryBuilder({ timeField: '@timestamp', esVersion: 5, }); - var query = builder_5x.build({ + const query = builder_5x.build({ metrics: [{ type: 'Count', id: '0' }], timeField: '@timestamp', bucketAggs: [{ type: 'date_histogram', field: '@timestamp', id: '1' }], @@ -35,7 +35,7 @@ describe('ElasticQueryBuilder', () => { }); it('with multiple bucket aggs', () => { - var query = builder.build({ + const query = builder.build({ metrics: [{ type: 'count', id: '1' }], timeField: '@timestamp', bucketAggs: [ @@ -49,7 +49,7 @@ describe('ElasticQueryBuilder', () => { }); it('with select field', () => { - var query = builder.build( + const query = builder.build( { metrics: [{ type: 'avg', field: '@value', id: '1' }], bucketAggs: [{ type: 'date_histogram', field: '@timestamp', id: '2' }], @@ -58,12 +58,12 @@ describe('ElasticQueryBuilder', () => { 1000 ); - var aggs = query.aggs['2'].aggs; + const aggs = query.aggs['2'].aggs; expect(aggs['1'].avg.field).toBe('@value'); }); it('with term agg and order by metric agg', () => { - var query = builder.build( + const query = builder.build( { metrics: [{ type: 'count', id: '1' }, { type: 'avg', field: '@value', id: '5' }], bucketAggs: [ @@ -80,15 +80,15 @@ describe('ElasticQueryBuilder', () => { 1000 ); - var firstLevel = query.aggs['2']; - var secondLevel = firstLevel.aggs['3']; + const firstLevel = query.aggs['2']; + const secondLevel = firstLevel.aggs['3']; expect(firstLevel.aggs['5'].avg.field).toBe('@value'); expect(secondLevel.aggs['5'].avg.field).toBe('@value'); }); it('with metric percentiles', () => { - var query = builder.build( + const query = builder.build( { metrics: [ { @@ -106,14 +106,14 @@ describe('ElasticQueryBuilder', () => { 1000 ); - var firstLevel = query.aggs['3']; + const firstLevel = query.aggs['3']; expect(firstLevel.aggs['1'].percentiles.field).toBe('@load_time'); expect(firstLevel.aggs['1'].percentiles.percents).toEqual([1, 2, 3, 4]); }); it('with filters aggs', () => { - var query = builder.build({ + const query = builder.build({ metrics: [{ type: 'count', id: '1' }], timeField: '@timestamp', bucketAggs: [ @@ -134,11 +134,11 @@ describe('ElasticQueryBuilder', () => { }); it('with filters aggs on es5.x', () => { - var builder_5x = new ElasticQueryBuilder({ + const builder_5x = new ElasticQueryBuilder({ timeField: '@timestamp', esVersion: 5, }); - var query = builder_5x.build({ + const query = builder_5x.build({ metrics: [{ type: 'count', id: '1' }], timeField: '@timestamp', bucketAggs: [ @@ -159,7 +159,7 @@ describe('ElasticQueryBuilder', () => { }); it('with raw_document metric', () => { - var query = builder.build({ + const query = builder.build({ metrics: [{ type: 'raw_document', id: '1', settings: {} }], timeField: '@timestamp', bucketAggs: [], @@ -168,7 +168,7 @@ describe('ElasticQueryBuilder', () => { expect(query.size).toBe(500); }); it('with raw_document metric size set', () => { - var query = builder.build({ + const query = builder.build({ metrics: [{ type: 'raw_document', id: '1', settings: { size: 1337 } }], timeField: '@timestamp', bucketAggs: [], @@ -178,7 +178,7 @@ describe('ElasticQueryBuilder', () => { }); it('with moving average', () => { - var query = builder.build({ + const query = builder.build({ metrics: [ { id: '3', @@ -195,7 +195,7 @@ describe('ElasticQueryBuilder', () => { bucketAggs: [{ type: 'date_histogram', field: '@timestamp', id: '3' }], }); - var firstLevel = query.aggs['3']; + const firstLevel = query.aggs['3']; expect(firstLevel.aggs['2']).not.toBe(undefined); expect(firstLevel.aggs['2'].moving_avg).not.toBe(undefined); @@ -203,7 +203,7 @@ describe('ElasticQueryBuilder', () => { }); it('with broken moving average', () => { - var query = builder.build({ + const query = builder.build({ metrics: [ { id: '3', @@ -224,7 +224,7 @@ describe('ElasticQueryBuilder', () => { bucketAggs: [{ type: 'date_histogram', field: '@timestamp', id: '3' }], }); - var firstLevel = query.aggs['3']; + const firstLevel = query.aggs['3']; expect(firstLevel.aggs['2']).not.toBe(undefined); expect(firstLevel.aggs['2'].moving_avg).not.toBe(undefined); @@ -233,7 +233,7 @@ describe('ElasticQueryBuilder', () => { }); it('with derivative', () => { - var query = builder.build({ + const query = builder.build({ metrics: [ { id: '3', @@ -249,7 +249,7 @@ describe('ElasticQueryBuilder', () => { bucketAggs: [{ type: 'date_histogram', field: '@timestamp', id: '3' }], }); - var firstLevel = query.aggs['3']; + const firstLevel = query.aggs['3']; expect(firstLevel.aggs['2']).not.toBe(undefined); expect(firstLevel.aggs['2'].derivative).not.toBe(undefined); @@ -257,7 +257,7 @@ describe('ElasticQueryBuilder', () => { }); it('with histogram', () => { - var query = builder.build({ + const query = builder.build({ metrics: [{ id: '1', type: 'count' }], bucketAggs: [ { @@ -269,7 +269,7 @@ describe('ElasticQueryBuilder', () => { ], }); - var firstLevel = query.aggs['3']; + const firstLevel = query.aggs['3']; expect(firstLevel.histogram.field).toBe('bytes'); expect(firstLevel.histogram.interval).toBe(10); expect(firstLevel.histogram.min_doc_count).toBe(2); @@ -277,7 +277,7 @@ describe('ElasticQueryBuilder', () => { }); it('with adhoc filters', () => { - var query = builder.build( + const query = builder.build( { metrics: [{ type: 'Count', id: '0' }], timeField: '@timestamp', diff --git a/public/app/plugins/datasource/elasticsearch/specs/query_def.test.ts b/public/app/plugins/datasource/elasticsearch/specs/query_def.test.ts index 0102e5febfb..471d400037c 100644 --- a/public/app/plugins/datasource/elasticsearch/specs/query_def.test.ts +++ b/public/app/plugins/datasource/elasticsearch/specs/query_def.test.ts @@ -3,7 +3,7 @@ import * as queryDef from '../query_def'; describe('ElasticQueryDef', () => { describe('getPipelineAggOptions', () => { describe('with zero targets', () => { - var response = queryDef.getPipelineAggOptions([]); + const response = queryDef.getPipelineAggOptions([]); test('should return zero', () => { expect(response.length).toBe(0); @@ -11,11 +11,11 @@ describe('ElasticQueryDef', () => { }); describe('with count and sum targets', () => { - var targets = { + const targets = { metrics: [{ type: 'count', field: '@value' }, { type: 'sum', field: '@value' }], }; - var response = queryDef.getPipelineAggOptions(targets); + const response = queryDef.getPipelineAggOptions(targets); test('should return zero', () => { expect(response.length).toBe(2); @@ -23,11 +23,11 @@ describe('ElasticQueryDef', () => { }); describe('with count and moving average targets', () => { - var targets = { + const targets = { metrics: [{ type: 'count', field: '@value' }, { type: 'moving_avg', field: '@value' }], }; - var response = queryDef.getPipelineAggOptions(targets); + const response = queryDef.getPipelineAggOptions(targets); test('should return one', () => { expect(response.length).toBe(1); @@ -35,11 +35,11 @@ describe('ElasticQueryDef', () => { }); describe('with derivatives targets', () => { - var targets = { + const targets = { metrics: [{ type: 'derivative', field: '@value' }], }; - var response = queryDef.getPipelineAggOptions(targets); + const response = queryDef.getPipelineAggOptions(targets); test('should return zero', () => { expect(response.length).toBe(0); @@ -49,7 +49,7 @@ describe('ElasticQueryDef', () => { describe('isPipelineMetric', () => { describe('moving_avg', () => { - var result = queryDef.isPipelineAgg('moving_avg'); + const result = queryDef.isPipelineAgg('moving_avg'); test('is pipe line metric', () => { expect(result).toBe(true); @@ -57,7 +57,7 @@ describe('ElasticQueryDef', () => { }); describe('count', () => { - var result = queryDef.isPipelineAgg('count'); + const result = queryDef.isPipelineAgg('count'); test('is not pipe line metric', () => { expect(result).toBe(false); diff --git a/public/app/plugins/datasource/grafana-live/datasource.ts b/public/app/plugins/datasource/grafana-live/datasource.ts index 5cba43dd2f9..d861400b2c8 100644 --- a/public/app/plugins/datasource/grafana-live/datasource.ts +++ b/public/app/plugins/datasource/grafana-live/datasource.ts @@ -8,7 +8,7 @@ class DataObservable { } subscribe(options) { - var observable = liveSrv.subscribe(this.target.stream); + const observable = liveSrv.subscribe(this.target.stream); return observable.subscribe(data => { console.log('grafana stream ds data!', data); }); @@ -26,8 +26,8 @@ export class GrafanaStreamDS { return Promise.resolve({ data: [] }); } - var target = options.targets[0]; - var observable = new DataObservable(target); + const target = options.targets[0]; + const observable = new DataObservable(target); return Promise.resolve(observable); } diff --git a/public/app/plugins/datasource/graphite/specs/datasource.test.ts b/public/app/plugins/datasource/graphite/specs/datasource.test.ts index 826f2fed344..563f1047cdb 100644 --- a/public/app/plugins/datasource/graphite/specs/datasource.test.ts +++ b/public/app/plugins/datasource/graphite/specs/datasource.test.ts @@ -324,7 +324,7 @@ function accessScenario(name, url, fn) { it('tracing headers should be added', () => { ctx.instanceSettings.url = url; - var ds = new GraphiteDatasource(ctx.instanceSettings, ctx.$q, ctx.backendSrv, ctx.templateSrv); + const ds = new GraphiteDatasource(ctx.instanceSettings, ctx.$q, ctx.backendSrv, ctx.templateSrv); ds.addTracingHeaders(httpOptions, options); fn(httpOptions); }); diff --git a/public/app/plugins/datasource/graphite/specs/gfunc.test.ts b/public/app/plugins/datasource/graphite/specs/gfunc.test.ts index 08373582e73..61a0e896b0f 100644 --- a/public/app/plugins/datasource/graphite/specs/gfunc.test.ts +++ b/public/app/plugins/datasource/graphite/specs/gfunc.test.ts @@ -2,7 +2,7 @@ import gfunc from '../gfunc'; describe('when creating func instance from func names', function() { it('should return func instance', function() { - var func = gfunc.createFuncInstance('sumSeries'); + const func = gfunc.createFuncInstance('sumSeries'); expect(func).toBeTruthy(); expect(func.def.name).toEqual('sumSeries'); expect(func.def.params.length).toEqual(1); @@ -11,18 +11,18 @@ describe('when creating func instance from func names', function() { }); it('should return func instance with shortName', function() { - var func = gfunc.createFuncInstance('sum'); + const func = gfunc.createFuncInstance('sum'); expect(func).toBeTruthy(); }); it('should return func instance from funcDef', function() { - var func = gfunc.createFuncInstance('sum'); - var func2 = gfunc.createFuncInstance(func.def); + const func = gfunc.createFuncInstance('sum'); + const func2 = gfunc.createFuncInstance(func.def); expect(func2).toBeTruthy(); }); it('func instance should have text representation', function() { - var func = gfunc.createFuncInstance('groupByNode'); + const func = gfunc.createFuncInstance('groupByNode'); func.params[0] = 5; func.params[1] = 'avg'; func.updateText(); @@ -32,62 +32,62 @@ describe('when creating func instance from func names', function() { describe('when rendering func instance', function() { it('should handle single metric param', function() { - var func = gfunc.createFuncInstance('sumSeries'); + const func = gfunc.createFuncInstance('sumSeries'); expect(func.render('hello.metric')).toEqual('sumSeries(hello.metric)'); }); it('should include default params if options enable it', function() { - var func = gfunc.createFuncInstance('scaleToSeconds', { + const func = gfunc.createFuncInstance('scaleToSeconds', { withDefaultParams: true, }); expect(func.render('hello')).toEqual('scaleToSeconds(hello, 1)'); }); it('should handle int or interval params with number', function() { - var func = gfunc.createFuncInstance('movingMedian'); + const func = gfunc.createFuncInstance('movingMedian'); func.params[0] = '5'; expect(func.render('hello')).toEqual('movingMedian(hello, 5)'); }); it('should handle int or interval params with interval string', function() { - var func = gfunc.createFuncInstance('movingMedian'); + const func = gfunc.createFuncInstance('movingMedian'); func.params[0] = '5min'; expect(func.render('hello')).toEqual("movingMedian(hello, '5min')"); }); it('should never quote boolean paramater', function() { - var func = gfunc.createFuncInstance('sortByName'); + const func = gfunc.createFuncInstance('sortByName'); func.params[0] = '$natural'; expect(func.render('hello')).toEqual('sortByName(hello, $natural)'); }); it('should never quote int paramater', function() { - var func = gfunc.createFuncInstance('maximumAbove'); + const func = gfunc.createFuncInstance('maximumAbove'); func.params[0] = '$value'; expect(func.render('hello')).toEqual('maximumAbove(hello, $value)'); }); it('should never quote node paramater', function() { - var func = gfunc.createFuncInstance('aliasByNode'); + const func = gfunc.createFuncInstance('aliasByNode'); func.params[0] = '$node'; expect(func.render('hello')).toEqual('aliasByNode(hello, $node)'); }); it('should handle metric param and int param and string param', function() { - var func = gfunc.createFuncInstance('groupByNode'); + const func = gfunc.createFuncInstance('groupByNode'); func.params[0] = 5; func.params[1] = 'avg'; expect(func.render('hello.metric')).toEqual("groupByNode(hello.metric, 5, 'avg')"); }); it('should handle function with no metric param', function() { - var func = gfunc.createFuncInstance('randomWalk'); + const func = gfunc.createFuncInstance('randomWalk'); func.params[0] = 'test'; expect(func.render(undefined)).toEqual("randomWalk('test')"); }); it('should handle function multiple series params', function() { - var func = gfunc.createFuncInstance('asPercent'); + const func = gfunc.createFuncInstance('asPercent'); func.params[0] = '#B'; expect(func.render('#A')).toEqual('asPercent(#A, #B)'); }); @@ -95,14 +95,14 @@ describe('when rendering func instance', function() { describe('when requesting function definitions', function() { it('should return function definitions', function() { - var funcIndex = gfunc.getFuncDefs('1.0'); + const funcIndex = gfunc.getFuncDefs('1.0'); expect(Object.keys(funcIndex).length).toBeGreaterThan(8); }); }); describe('when updating func param', function() { it('should update param value and update text representation', function() { - var func = gfunc.createFuncInstance('summarize', { + const func = gfunc.createFuncInstance('summarize', { withDefaultParams: true, }); func.updateParam('1h', 0); @@ -111,7 +111,7 @@ describe('when updating func param', function() { }); it('should parse numbers as float', function() { - var func = gfunc.createFuncInstance('scale'); + const func = gfunc.createFuncInstance('scale'); func.updateParam('0.001', 0); expect(func.params[0]).toBe('0.001'); }); @@ -119,13 +119,13 @@ describe('when updating func param', function() { describe('when updating func param with optional second parameter', function() { it('should update value and text', function() { - var func = gfunc.createFuncInstance('aliasByNode'); + const func = gfunc.createFuncInstance('aliasByNode'); func.updateParam('1', 0); expect(func.params[0]).toBe('1'); }); it('should slit text and put value in second param', function() { - var func = gfunc.createFuncInstance('aliasByNode'); + const func = gfunc.createFuncInstance('aliasByNode'); func.updateParam('4,-5', 0); expect(func.params[0]).toBe('4'); expect(func.params[1]).toBe('-5'); @@ -133,7 +133,7 @@ describe('when updating func param with optional second parameter', function() { }); it('should remove second param when empty string is set', function() { - var func = gfunc.createFuncInstance('aliasByNode'); + const func = gfunc.createFuncInstance('aliasByNode'); func.updateParam('4,-5', 0); func.updateParam('', 1); expect(func.params[0]).toBe('4'); diff --git a/public/app/plugins/datasource/graphite/specs/lexer.test.ts b/public/app/plugins/datasource/graphite/specs/lexer.test.ts index c925e5cdaba..f00df17a725 100644 --- a/public/app/plugins/datasource/graphite/specs/lexer.test.ts +++ b/public/app/plugins/datasource/graphite/specs/lexer.test.ts @@ -2,8 +2,8 @@ import { Lexer } from '../lexer'; describe('when lexing graphite expression', function() { it('should tokenize metric expression', function() { - var lexer = new Lexer('metric.test.*.asd.count'); - var tokens = lexer.tokenize(); + const lexer = new Lexer('metric.test.*.asd.count'); + const tokens = lexer.tokenize(); expect(tokens[0].value).toBe('metric'); expect(tokens[1].value).toBe('.'); expect(tokens[2].type).toBe('identifier'); @@ -12,36 +12,36 @@ describe('when lexing graphite expression', function() { }); it('should tokenize metric expression with dash', function() { - var lexer = new Lexer('metric.test.se1-server-*.asd.count'); - var tokens = lexer.tokenize(); + const lexer = new Lexer('metric.test.se1-server-*.asd.count'); + const tokens = lexer.tokenize(); expect(tokens[4].type).toBe('identifier'); expect(tokens[4].value).toBe('se1-server-*'); }); it('should tokenize metric expression with dash2', function() { - var lexer = new Lexer('net.192-168-1-1.192-168-1-9.ping_value.*'); - var tokens = lexer.tokenize(); + const lexer = new Lexer('net.192-168-1-1.192-168-1-9.ping_value.*'); + const tokens = lexer.tokenize(); expect(tokens[0].value).toBe('net'); expect(tokens[2].value).toBe('192-168-1-1'); }); it('should tokenize metric expression with equal sign', function() { - var lexer = new Lexer('apps=test'); - var tokens = lexer.tokenize(); + const lexer = new Lexer('apps=test'); + const tokens = lexer.tokenize(); expect(tokens[0].value).toBe('apps=test'); }); it('simple function2', function() { - var lexer = new Lexer('offset(test.metric, -100)'); - var tokens = lexer.tokenize(); + const lexer = new Lexer('offset(test.metric, -100)'); + const tokens = lexer.tokenize(); expect(tokens[2].type).toBe('identifier'); expect(tokens[4].type).toBe('identifier'); expect(tokens[6].type).toBe('number'); }); it('should tokenize metric expression with curly braces', function() { - var lexer = new Lexer('metric.se1-{first, second}.count'); - var tokens = lexer.tokenize(); + const lexer = new Lexer('metric.se1-{first, second}.count'); + const tokens = lexer.tokenize(); expect(tokens.length).toBe(10); expect(tokens[3].type).toBe('{'); expect(tokens[4].value).toBe('first'); @@ -50,8 +50,8 @@ describe('when lexing graphite expression', function() { }); it('should tokenize metric expression with number segments', function() { - var lexer = new Lexer('metric.10.12_10.test'); - var tokens = lexer.tokenize(); + const lexer = new Lexer('metric.10.12_10.test'); + const tokens = lexer.tokenize(); expect(tokens[0].type).toBe('identifier'); expect(tokens[2].type).toBe('identifier'); expect(tokens[2].value).toBe('10'); @@ -60,16 +60,16 @@ describe('when lexing graphite expression', function() { }); it('should tokenize metric expression with segment that start with number', function() { - var lexer = new Lexer('metric.001-server'); - var tokens = lexer.tokenize(); + const lexer = new Lexer('metric.001-server'); + const tokens = lexer.tokenize(); expect(tokens[0].type).toBe('identifier'); expect(tokens[2].type).toBe('identifier'); expect(tokens.length).toBe(3); }); it('should tokenize func call with numbered metric and number arg', function() { - var lexer = new Lexer('scale(metric.10, 15)'); - var tokens = lexer.tokenize(); + const lexer = new Lexer('scale(metric.10, 15)'); + const tokens = lexer.tokenize(); expect(tokens[0].type).toBe('identifier'); expect(tokens[2].type).toBe('identifier'); expect(tokens[2].value).toBe('metric'); @@ -79,24 +79,24 @@ describe('when lexing graphite expression', function() { }); it('should tokenize metric with template parameter', function() { - var lexer = new Lexer('metric.[[server]].test'); - var tokens = lexer.tokenize(); + const lexer = new Lexer('metric.[[server]].test'); + const tokens = lexer.tokenize(); expect(tokens[2].type).toBe('identifier'); expect(tokens[2].value).toBe('[[server]]'); expect(tokens[4].type).toBe('identifier'); }); it('should tokenize metric with question mark', function() { - var lexer = new Lexer('metric.server_??.test'); - var tokens = lexer.tokenize(); + const lexer = new Lexer('metric.server_??.test'); + const tokens = lexer.tokenize(); expect(tokens[2].type).toBe('identifier'); expect(tokens[2].value).toBe('server_??'); expect(tokens[4].type).toBe('identifier'); }); it('should handle error with unterminated string', function() { - var lexer = new Lexer("alias(metric, 'asd)"); - var tokens = lexer.tokenize(); + const lexer = new Lexer("alias(metric, 'asd)"); + const tokens = lexer.tokenize(); expect(tokens[0].value).toBe('alias'); expect(tokens[1].value).toBe('('); expect(tokens[2].value).toBe('metric'); @@ -107,15 +107,15 @@ describe('when lexing graphite expression', function() { }); it('should handle float parameters', function() { - var lexer = new Lexer('alias(metric, 0.002)'); - var tokens = lexer.tokenize(); + const lexer = new Lexer('alias(metric, 0.002)'); + const tokens = lexer.tokenize(); expect(tokens[4].type).toBe('number'); expect(tokens[4].value).toBe('0.002'); }); it('should handle bool parameters', function() { - var lexer = new Lexer('alias(metric, true, false)'); - var tokens = lexer.tokenize(); + const lexer = new Lexer('alias(metric, true, false)'); + const tokens = lexer.tokenize(); expect(tokens[4].type).toBe('bool'); expect(tokens[4].value).toBe('true'); expect(tokens[6].type).toBe('bool'); diff --git a/public/app/plugins/datasource/graphite/specs/parser.test.ts b/public/app/plugins/datasource/graphite/specs/parser.test.ts index 7964d9d257b..966eb213d64 100644 --- a/public/app/plugins/datasource/graphite/specs/parser.test.ts +++ b/public/app/plugins/datasource/graphite/specs/parser.test.ts @@ -2,8 +2,8 @@ import { Parser } from '../parser'; describe('when parsing', function() { it('simple metric expression', function() { - var parser = new Parser('metric.test.*.asd.count'); - var rootNode = parser.getAst(); + const parser = new Parser('metric.test.*.asd.count'); + const rootNode = parser.getAst(); expect(rootNode.type).toBe('metric'); expect(rootNode.segments.length).toBe(5); @@ -11,8 +11,8 @@ describe('when parsing', function() { }); it('simple metric expression with numbers in segments', function() { - var parser = new Parser('metric.10.15_20.5'); - var rootNode = parser.getAst(); + const parser = new Parser('metric.10.15_20.5'); + const rootNode = parser.getAst(); expect(rootNode.type).toBe('metric'); expect(rootNode.segments.length).toBe(4); @@ -22,8 +22,8 @@ describe('when parsing', function() { }); it('simple metric expression with curly braces', function() { - var parser = new Parser('metric.se1-{count, max}'); - var rootNode = parser.getAst(); + const parser = new Parser('metric.se1-{count, max}'); + const rootNode = parser.getAst(); expect(rootNode.type).toBe('metric'); expect(rootNode.segments.length).toBe(2); @@ -31,8 +31,8 @@ describe('when parsing', function() { }); it('simple metric expression with curly braces at start of segment and with post chars', function() { - var parser = new Parser('metric.{count, max}-something.count'); - var rootNode = parser.getAst(); + const parser = new Parser('metric.{count, max}-something.count'); + const rootNode = parser.getAst(); expect(rootNode.type).toBe('metric'); expect(rootNode.segments.length).toBe(3); @@ -40,31 +40,31 @@ describe('when parsing', function() { }); it('simple function', function() { - var parser = new Parser('sum(test)'); - var rootNode = parser.getAst(); + const parser = new Parser('sum(test)'); + const rootNode = parser.getAst(); expect(rootNode.type).toBe('function'); expect(rootNode.params.length).toBe(1); }); it('simple function2', function() { - var parser = new Parser('offset(test.metric, -100)'); - var rootNode = parser.getAst(); + const parser = new Parser('offset(test.metric, -100)'); + const rootNode = parser.getAst(); expect(rootNode.type).toBe('function'); expect(rootNode.params[0].type).toBe('metric'); expect(rootNode.params[1].type).toBe('number'); }); it('simple function with string arg', function() { - var parser = new Parser("randomWalk('test')"); - var rootNode = parser.getAst(); + const parser = new Parser("randomWalk('test')"); + const rootNode = parser.getAst(); expect(rootNode.type).toBe('function'); expect(rootNode.params.length).toBe(1); expect(rootNode.params[0].type).toBe('string'); }); it('function with multiple args', function() { - var parser = new Parser("sum(test, 1, 'test')"); - var rootNode = parser.getAst(); + const parser = new Parser("sum(test, 1, 'test')"); + const rootNode = parser.getAst(); expect(rootNode.type).toBe('function'); expect(rootNode.params.length).toBe(3); @@ -74,8 +74,8 @@ describe('when parsing', function() { }); it('function with nested function', function() { - var parser = new Parser('sum(scaleToSeconds(test, 1))'); - var rootNode = parser.getAst(); + const parser = new Parser('sum(scaleToSeconds(test, 1))'); + const rootNode = parser.getAst(); expect(rootNode.type).toBe('function'); expect(rootNode.params.length).toBe(1); @@ -87,8 +87,8 @@ describe('when parsing', function() { }); it('function with multiple series', function() { - var parser = new Parser('sum(test.test.*.count, test.timers.*.count)'); - var rootNode = parser.getAst(); + const parser = new Parser('sum(test.test.*.count, test.timers.*.count)'); + const rootNode = parser.getAst(); expect(rootNode.type).toBe('function'); expect(rootNode.params.length).toBe(2); @@ -97,8 +97,8 @@ describe('when parsing', function() { }); it('function with templated series', function() { - var parser = new Parser('sum(test.[[server]].count)'); - var rootNode = parser.getAst(); + const parser = new Parser('sum(test.[[server]].count)'); + const rootNode = parser.getAst(); expect(rootNode.message).toBe(undefined); expect(rootNode.params[0].type).toBe('metric'); @@ -107,54 +107,54 @@ describe('when parsing', function() { }); it('invalid metric expression', function() { - var parser = new Parser('metric.test.*.asd.'); - var rootNode = parser.getAst(); + const parser = new Parser('metric.test.*.asd.'); + const rootNode = parser.getAst(); expect(rootNode.message).toBe('Expected metric identifier instead found end of string'); expect(rootNode.pos).toBe(19); }); it('invalid function expression missing closing parenthesis', function() { - var parser = new Parser('sum(test'); - var rootNode = parser.getAst(); + const parser = new Parser('sum(test'); + const rootNode = parser.getAst(); expect(rootNode.message).toBe('Expected closing parenthesis instead found end of string'); expect(rootNode.pos).toBe(9); }); it('unclosed string in function', function() { - var parser = new Parser("sum('test)"); - var rootNode = parser.getAst(); + const parser = new Parser("sum('test)"); + const rootNode = parser.getAst(); expect(rootNode.message).toBe('Unclosed string parameter'); expect(rootNode.pos).toBe(11); }); it('handle issue #69', function() { - var parser = new Parser('cactiStyle(offset(scale(net.192-168-1-1.192-168-1-9.ping_value.*,0.001),-100))'); - var rootNode = parser.getAst(); + const parser = new Parser('cactiStyle(offset(scale(net.192-168-1-1.192-168-1-9.ping_value.*,0.001),-100))'); + const rootNode = parser.getAst(); expect(rootNode.type).toBe('function'); }); it('handle float function arguments', function() { - var parser = new Parser('scale(test, 0.002)'); - var rootNode = parser.getAst(); + const parser = new Parser('scale(test, 0.002)'); + const rootNode = parser.getAst(); expect(rootNode.type).toBe('function'); expect(rootNode.params[1].type).toBe('number'); expect(rootNode.params[1].value).toBe(0.002); }); it('handle curly brace pattern at start', function() { - var parser = new Parser('{apps}.test'); - var rootNode = parser.getAst(); + const parser = new Parser('{apps}.test'); + const rootNode = parser.getAst(); expect(rootNode.type).toBe('metric'); expect(rootNode.segments[0].value).toBe('{apps}'); expect(rootNode.segments[1].value).toBe('test'); }); it('series parameters', function() { - var parser = new Parser('asPercent(#A, #B)'); - var rootNode = parser.getAst(); + const parser = new Parser('asPercent(#A, #B)'); + const rootNode = parser.getAst(); expect(rootNode.type).toBe('function'); expect(rootNode.params[0].type).toBe('series-ref'); expect(rootNode.params[0].value).toBe('#A'); @@ -162,8 +162,8 @@ describe('when parsing', function() { }); it('series parameters, issue 2788', function() { - var parser = new Parser("summarize(diffSeries(#A, #B), '10m', 'sum', false)"); - var rootNode = parser.getAst(); + const parser = new Parser("summarize(diffSeries(#A, #B), '10m', 'sum', false)"); + const rootNode = parser.getAst(); expect(rootNode.type).toBe('function'); expect(rootNode.params[0].type).toBe('function'); expect(rootNode.params[1].value).toBe('10m'); @@ -171,8 +171,8 @@ describe('when parsing', function() { }); it('should parse metric expression with ip number segments', function() { - var parser = new Parser('5.10.123.5'); - var rootNode = parser.getAst(); + const parser = new Parser('5.10.123.5'); + const rootNode = parser.getAst(); expect(rootNode.segments[0].value).toBe('5'); expect(rootNode.segments[1].value).toBe('10'); expect(rootNode.segments[2].value).toBe('123'); diff --git a/public/app/plugins/datasource/influxdb/specs/influx_query.test.ts b/public/app/plugins/datasource/influxdb/specs/influx_query.test.ts index 7c354e8aeeb..a62d5384ac6 100644 --- a/public/app/plugins/datasource/influxdb/specs/influx_query.test.ts +++ b/public/app/plugins/datasource/influxdb/specs/influx_query.test.ts @@ -1,11 +1,11 @@ import InfluxQuery from '../influx_query'; describe('InfluxQuery', function() { - var templateSrv = { replace: val => val }; + const templateSrv = { replace: val => val }; describe('render series with mesurement only', function() { it('should generate correct query', function() { - var query = new InfluxQuery( + const query = new InfluxQuery( { measurement: 'cpu', }, @@ -13,14 +13,14 @@ describe('InfluxQuery', function() { {} ); - var queryText = query.render(); + const queryText = query.render(); expect(queryText).toBe('SELECT mean("value") FROM "cpu" WHERE $timeFilter GROUP BY time($__interval) fill(null)'); }); }); describe('render series with policy only', function() { it('should generate correct query', function() { - var query = new InfluxQuery( + const query = new InfluxQuery( { measurement: 'cpu', policy: '5m_avg', @@ -29,7 +29,7 @@ describe('InfluxQuery', function() { {} ); - var queryText = query.render(); + const queryText = query.render(); expect(queryText).toBe( 'SELECT mean("value") FROM "5m_avg"."cpu" WHERE $timeFilter GROUP BY time($__interval) fill(null)' ); @@ -38,7 +38,7 @@ describe('InfluxQuery', function() { describe('render series with math and alias', function() { it('should generate correct query', function() { - var query = new InfluxQuery( + const query = new InfluxQuery( { measurement: 'cpu', select: [ @@ -54,7 +54,7 @@ describe('InfluxQuery', function() { {} ); - var queryText = query.render(); + const queryText = query.render(); expect(queryText).toBe( 'SELECT mean("value") /100 AS "text" FROM "cpu" WHERE $timeFilter GROUP BY time($__interval) fill(null)' ); @@ -63,7 +63,7 @@ describe('InfluxQuery', function() { describe('series with single tag only', function() { it('should generate correct query', function() { - var query = new InfluxQuery( + const query = new InfluxQuery( { measurement: 'cpu', groupBy: [{ type: 'time', params: ['auto'] }], @@ -73,7 +73,7 @@ describe('InfluxQuery', function() { {} ); - var queryText = query.render(); + const queryText = query.render(); expect(queryText).toBe( 'SELECT mean("value") FROM "cpu" WHERE ("hostname" = \'server\\\\1\') AND $timeFilter' + @@ -82,7 +82,7 @@ describe('InfluxQuery', function() { }); it('should switch regex operator with tag value is regex', function() { - var query = new InfluxQuery( + const query = new InfluxQuery( { measurement: 'cpu', groupBy: [{ type: 'time', params: ['auto'] }], @@ -92,7 +92,7 @@ describe('InfluxQuery', function() { {} ); - var queryText = query.render(); + const queryText = query.render(); expect(queryText).toBe( 'SELECT mean("value") FROM "cpu" WHERE ("app" =~ /e.*/) AND $timeFilter GROUP BY time($__interval)' ); @@ -101,7 +101,7 @@ describe('InfluxQuery', function() { describe('series with multiple tags only', function() { it('should generate correct query', function() { - var query = new InfluxQuery( + const query = new InfluxQuery( { measurement: 'cpu', groupBy: [{ type: 'time', params: ['auto'] }], @@ -111,7 +111,7 @@ describe('InfluxQuery', function() { {} ); - var queryText = query.render(); + const queryText = query.render(); expect(queryText).toBe( 'SELECT mean("value") FROM "cpu" WHERE ("hostname" = \'server1\' AND "app" = \'email\') AND ' + '$timeFilter GROUP BY time($__interval)' @@ -121,7 +121,7 @@ describe('InfluxQuery', function() { describe('series with tags OR condition', function() { it('should generate correct query', function() { - var query = new InfluxQuery( + const query = new InfluxQuery( { measurement: 'cpu', groupBy: [{ type: 'time', params: ['auto'] }], @@ -131,7 +131,7 @@ describe('InfluxQuery', function() { {} ); - var queryText = query.render(); + const queryText = query.render(); expect(queryText).toBe( 'SELECT mean("value") FROM "cpu" WHERE ("hostname" = \'server1\' OR "hostname" = \'server2\') AND ' + '$timeFilter GROUP BY time($__interval)' @@ -141,7 +141,7 @@ describe('InfluxQuery', function() { describe('query with value condition', function() { it('should not quote value', function() { - var query = new InfluxQuery( + const query = new InfluxQuery( { measurement: 'cpu', groupBy: [], @@ -151,14 +151,14 @@ describe('InfluxQuery', function() { {} ); - var queryText = query.render(); + const queryText = query.render(); expect(queryText).toBe('SELECT mean("value") FROM "cpu" WHERE ("value" > 5) AND $timeFilter'); }); }); describe('series with groupByTag', function() { it('should generate correct query', function() { - var query = new InfluxQuery( + const query = new InfluxQuery( { measurement: 'cpu', tags: [], @@ -168,14 +168,14 @@ describe('InfluxQuery', function() { {} ); - var queryText = query.render(); + const queryText = query.render(); expect(queryText).toBe('SELECT mean("value") FROM "cpu" WHERE $timeFilter GROUP BY time($__interval), "host"'); }); }); describe('render series without group by', function() { it('should generate correct query', function() { - var query = new InfluxQuery( + const query = new InfluxQuery( { measurement: 'cpu', select: [[{ type: 'field', params: ['value'] }]], @@ -184,14 +184,14 @@ describe('InfluxQuery', function() { templateSrv, {} ); - var queryText = query.render(); + const queryText = query.render(); expect(queryText).toBe('SELECT "value" FROM "cpu" WHERE $timeFilter'); }); }); describe('render series without group by and fill', function() { it('should generate correct query', function() { - var query = new InfluxQuery( + const query = new InfluxQuery( { measurement: 'cpu', select: [[{ type: 'field', params: ['value'] }]], @@ -200,14 +200,14 @@ describe('InfluxQuery', function() { templateSrv, {} ); - var queryText = query.render(); + const queryText = query.render(); expect(queryText).toBe('SELECT "value" FROM "cpu" WHERE $timeFilter GROUP BY time($__interval) fill(0)'); }); }); describe('when adding group by part', function() { it('should add tag before fill', function() { - var query = new InfluxQuery( + const query = new InfluxQuery( { measurement: 'cpu', groupBy: [{ type: 'time' }, { type: 'fill' }], @@ -224,7 +224,7 @@ describe('InfluxQuery', function() { }); it('should add tag last if no fill', function() { - var query = new InfluxQuery( + const query = new InfluxQuery( { measurement: 'cpu', groupBy: [], @@ -241,7 +241,7 @@ describe('InfluxQuery', function() { describe('when adding select part', function() { it('should add mean after after field', function() { - var query = new InfluxQuery( + const query = new InfluxQuery( { measurement: 'cpu', select: [[{ type: 'field', params: ['value'] }]], @@ -256,7 +256,7 @@ describe('InfluxQuery', function() { }); it('should replace sum by mean', function() { - var query = new InfluxQuery( + const query = new InfluxQuery( { measurement: 'cpu', select: [[{ type: 'field', params: ['value'] }, { type: 'mean' }]], @@ -271,7 +271,7 @@ describe('InfluxQuery', function() { }); it('should add math before alias', function() { - var query = new InfluxQuery( + const query = new InfluxQuery( { measurement: 'cpu', select: [[{ type: 'field', params: ['value'] }, { type: 'mean' }, { type: 'alias' }]], @@ -286,7 +286,7 @@ describe('InfluxQuery', function() { }); it('should add math last', function() { - var query = new InfluxQuery( + const query = new InfluxQuery( { measurement: 'cpu', select: [[{ type: 'field', params: ['value'] }, { type: 'mean' }]], @@ -301,7 +301,7 @@ describe('InfluxQuery', function() { }); it('should replace math', function() { - var query = new InfluxQuery( + const query = new InfluxQuery( { measurement: 'cpu', select: [[{ type: 'field', params: ['value'] }, { type: 'mean' }, { type: 'math' }]], @@ -316,7 +316,7 @@ describe('InfluxQuery', function() { }); it('should add math when one only query part', function() { - var query = new InfluxQuery( + const query = new InfluxQuery( { measurement: 'cpu', select: [[{ type: 'field', params: ['value'] }]], @@ -332,9 +332,9 @@ describe('InfluxQuery', function() { describe('when render adhoc filters', function() { it('should generate correct query segment', function() { - var query = new InfluxQuery({ measurement: 'cpu' }, templateSrv, {}); + const query = new InfluxQuery({ measurement: 'cpu' }, templateSrv, {}); - var queryText = query.renderAdhocFilters([ + const queryText = query.renderAdhocFilters([ { key: 'key1', operator: '=', value: 'value1' }, { key: 'key2', operator: '!=', value: 'value2' }, ]); diff --git a/public/app/plugins/datasource/influxdb/specs/influx_series.test.ts b/public/app/plugins/datasource/influxdb/specs/influx_series.test.ts index 8c8fee9ab9f..bb20db1ba76 100644 --- a/public/app/plugins/datasource/influxdb/specs/influx_series.test.ts +++ b/public/app/plugins/datasource/influxdb/specs/influx_series.test.ts @@ -2,7 +2,7 @@ import InfluxSeries from '../influx_series'; describe('when generating timeseries from influxdb response', function() { describe('given multiple fields for series', function() { - var options = { + const options = { alias: '', series: [ { @@ -15,8 +15,8 @@ describe('when generating timeseries from influxdb response', function() { }; describe('and no alias', function() { it('should generate multiple datapoints for each column', function() { - var series = new InfluxSeries(options); - var result = series.getTimeSeries(); + const series = new InfluxSeries(options); + const result = series.getTimeSeries(); expect(result.length).toBe(3); expect(result[0].target).toBe('cpu.mean {app: test, server: server1}'); @@ -42,8 +42,8 @@ describe('when generating timeseries from influxdb response', function() { describe('and simple alias', function() { it('should use alias', function() { options.alias = 'new series'; - var series = new InfluxSeries(options); - var result = series.getTimeSeries(); + const series = new InfluxSeries(options); + const result = series.getTimeSeries(); expect(result[0].target).toBe('new series'); expect(result[1].target).toBe('new series'); @@ -54,8 +54,8 @@ describe('when generating timeseries from influxdb response', function() { describe('and alias patterns', function() { it('should replace patterns', function() { options.alias = 'alias: $m -> $tag_server ([[measurement]])'; - var series = new InfluxSeries(options); - var result = series.getTimeSeries(); + const series = new InfluxSeries(options); + const result = series.getTimeSeries(); expect(result[0].target).toBe('alias: cpu -> server1 (cpu)'); expect(result[1].target).toBe('alias: cpu -> server1 (cpu)'); @@ -65,7 +65,7 @@ describe('when generating timeseries from influxdb response', function() { }); describe('given measurement with default fieldname', function() { - var options = { + const options = { series: [ { name: 'cpu', @@ -84,8 +84,8 @@ describe('when generating timeseries from influxdb response', function() { describe('and no alias', function() { it('should generate label with no field', function() { - var series = new InfluxSeries(options); - var result = series.getTimeSeries(); + const series = new InfluxSeries(options); + const result = series.getTimeSeries(); expect(result[0].target).toBe('cpu {app: test, server: server1}'); expect(result[1].target).toBe('cpu {app: test2, server: server2}'); @@ -94,7 +94,7 @@ describe('when generating timeseries from influxdb response', function() { }); describe('given two series', function() { - var options = { + const options = { alias: '', series: [ { @@ -114,8 +114,8 @@ describe('when generating timeseries from influxdb response', function() { describe('and no alias', function() { it('should generate two time series', function() { - var series = new InfluxSeries(options); - var result = series.getTimeSeries(); + const series = new InfluxSeries(options); + const result = series.getTimeSeries(); expect(result.length).toBe(2); expect(result[0].target).toBe('cpu.mean {app: test, server: server1}'); @@ -135,8 +135,8 @@ describe('when generating timeseries from influxdb response', function() { describe('and simple alias', function() { it('should use alias', function() { options.alias = 'new series'; - var series = new InfluxSeries(options); - var result = series.getTimeSeries(); + const series = new InfluxSeries(options); + const result = series.getTimeSeries(); expect(result[0].target).toBe('new series'); }); @@ -145,8 +145,8 @@ describe('when generating timeseries from influxdb response', function() { describe('and alias patterns', function() { it('should replace patterns', function() { options.alias = 'alias: $m -> $tag_server ([[measurement]])'; - var series = new InfluxSeries(options); - var result = series.getTimeSeries(); + const series = new InfluxSeries(options); + const result = series.getTimeSeries(); expect(result[0].target).toBe('alias: cpu -> server1 (cpu)'); expect(result[1].target).toBe('alias: cpu -> server2 (cpu)'); @@ -155,7 +155,7 @@ describe('when generating timeseries from influxdb response', function() { }); describe('given measurement with dots', function() { - var options = { + const options = { alias: '', series: [ { @@ -169,15 +169,15 @@ describe('when generating timeseries from influxdb response', function() { it('should replace patterns', function() { options.alias = 'alias: $1 -> [[3]]'; - var series = new InfluxSeries(options); - var result = series.getTimeSeries(); + const series = new InfluxSeries(options); + const result = series.getTimeSeries(); expect(result[0].target).toBe('alias: prod -> count'); }); }); describe('given table response', function() { - var options = { + const options = { alias: '', series: [ { @@ -190,8 +190,8 @@ describe('when generating timeseries from influxdb response', function() { }; it('should return table', function() { - var series = new InfluxSeries(options); - var table = series.getTable(); + const series = new InfluxSeries(options); + const table = series.getTable(); expect(table.type).toBe('table'); expect(table.columns.length).toBe(5); @@ -201,7 +201,7 @@ describe('when generating timeseries from influxdb response', function() { }); describe('given table response from SHOW CARDINALITY', function() { - var options = { + const options = { alias: '', series: [ { @@ -213,8 +213,8 @@ describe('when generating timeseries from influxdb response', function() { }; it('should return table', function() { - var series = new InfluxSeries(options); - var table = series.getTable(); + const series = new InfluxSeries(options); + const table = series.getTable(); expect(table.type).toBe('table'); expect(table.columns.length).toBe(1); @@ -225,7 +225,7 @@ describe('when generating timeseries from influxdb response', function() { describe('given annotation response', function() { describe('with empty tagsColumn', function() { - var options = { + const options = { alias: '', annotation: {}, series: [ @@ -239,15 +239,15 @@ describe('when generating timeseries from influxdb response', function() { }; it('should multiple tags', function() { - var series = new InfluxSeries(options); - var annotations = series.getAnnotations(); + const series = new InfluxSeries(options); + const annotations = series.getAnnotations(); expect(annotations[0].tags.length).toBe(0); }); }); describe('given annotation response', function() { - var options = { + const options = { alias: '', annotation: { tagsColumn: 'datacenter, source', @@ -263,8 +263,8 @@ describe('when generating timeseries from influxdb response', function() { }; it('should multiple tags', function() { - var series = new InfluxSeries(options); - var annotations = series.getAnnotations(); + const series = new InfluxSeries(options); + const annotations = series.getAnnotations(); expect(annotations[0].tags.length).toBe(2); expect(annotations[0].tags[0]).toBe('America'); diff --git a/public/app/plugins/datasource/influxdb/specs/query_builder.test.ts b/public/app/plugins/datasource/influxdb/specs/query_builder.test.ts index 30a9343f56e..d8b27f8b1bf 100644 --- a/public/app/plugins/datasource/influxdb/specs/query_builder.test.ts +++ b/public/app/plugins/datasource/influxdb/specs/query_builder.test.ts @@ -3,139 +3,139 @@ import { InfluxQueryBuilder } from '../query_builder'; describe('InfluxQueryBuilder', function() { describe('when building explore queries', function() { it('should only have measurement condition in tag keys query given query with measurement', function() { - var builder = new InfluxQueryBuilder({ measurement: 'cpu', tags: [] }); - var query = builder.buildExploreQuery('TAG_KEYS'); + const builder = new InfluxQueryBuilder({ measurement: 'cpu', tags: [] }); + const query = builder.buildExploreQuery('TAG_KEYS'); expect(query).toBe('SHOW TAG KEYS FROM "cpu"'); }); it('should handle regex measurement in tag keys query', function() { - var builder = new InfluxQueryBuilder({ + const builder = new InfluxQueryBuilder({ measurement: '/.*/', tags: [], }); - var query = builder.buildExploreQuery('TAG_KEYS'); + const query = builder.buildExploreQuery('TAG_KEYS'); expect(query).toBe('SHOW TAG KEYS FROM /.*/'); }); it('should have no conditions in tags keys query given query with no measurement or tag', function() { - var builder = new InfluxQueryBuilder({ measurement: '', tags: [] }); - var query = builder.buildExploreQuery('TAG_KEYS'); + const builder = new InfluxQueryBuilder({ measurement: '', tags: [] }); + const query = builder.buildExploreQuery('TAG_KEYS'); expect(query).toBe('SHOW TAG KEYS'); }); it('should have where condition in tag keys query with tags', function() { - var builder = new InfluxQueryBuilder({ + const builder = new InfluxQueryBuilder({ measurement: '', tags: [{ key: 'host', value: 'se1' }], }); - var query = builder.buildExploreQuery('TAG_KEYS'); + const query = builder.buildExploreQuery('TAG_KEYS'); expect(query).toBe('SHOW TAG KEYS WHERE "host" = \'se1\''); }); it('should have no conditions in measurement query for query with no tags', function() { - var builder = new InfluxQueryBuilder({ measurement: '', tags: [] }); - var query = builder.buildExploreQuery('MEASUREMENTS'); + const builder = new InfluxQueryBuilder({ measurement: '', tags: [] }); + const query = builder.buildExploreQuery('MEASUREMENTS'); expect(query).toBe('SHOW MEASUREMENTS LIMIT 100'); }); it('should have no conditions in measurement query for query with no tags and empty query', function() { - var builder = new InfluxQueryBuilder({ measurement: '', tags: [] }); - var query = builder.buildExploreQuery('MEASUREMENTS', undefined, ''); + const builder = new InfluxQueryBuilder({ measurement: '', tags: [] }); + const query = builder.buildExploreQuery('MEASUREMENTS', undefined, ''); expect(query).toBe('SHOW MEASUREMENTS LIMIT 100'); }); it('should have WITH MEASUREMENT in measurement query for non-empty query with no tags', function() { - var builder = new InfluxQueryBuilder({ measurement: '', tags: [] }); - var query = builder.buildExploreQuery('MEASUREMENTS', undefined, 'something'); + const builder = new InfluxQueryBuilder({ measurement: '', tags: [] }); + const query = builder.buildExploreQuery('MEASUREMENTS', undefined, 'something'); expect(query).toBe('SHOW MEASUREMENTS WITH MEASUREMENT =~ /something/ LIMIT 100'); }); it('should have WITH MEASUREMENT WHERE in measurement query for non-empty query with tags', function() { - var builder = new InfluxQueryBuilder({ + const builder = new InfluxQueryBuilder({ measurement: '', tags: [{ key: 'app', value: 'email' }], }); - var query = builder.buildExploreQuery('MEASUREMENTS', undefined, 'something'); + const query = builder.buildExploreQuery('MEASUREMENTS', undefined, 'something'); expect(query).toBe('SHOW MEASUREMENTS WITH MEASUREMENT =~ /something/ WHERE "app" = \'email\' LIMIT 100'); }); it('should have where condition in measurement query for query with tags', function() { - var builder = new InfluxQueryBuilder({ + const builder = new InfluxQueryBuilder({ measurement: '', tags: [{ key: 'app', value: 'email' }], }); - var query = builder.buildExploreQuery('MEASUREMENTS'); + const query = builder.buildExploreQuery('MEASUREMENTS'); expect(query).toBe('SHOW MEASUREMENTS WHERE "app" = \'email\' LIMIT 100'); }); it('should have where tag name IN filter in tag values query for query with one tag', function() { - var builder = new InfluxQueryBuilder({ + const builder = new InfluxQueryBuilder({ measurement: '', tags: [{ key: 'app', value: 'asdsadsad' }], }); - var query = builder.buildExploreQuery('TAG_VALUES', 'app'); + const query = builder.buildExploreQuery('TAG_VALUES', 'app'); expect(query).toBe('SHOW TAG VALUES WITH KEY = "app"'); }); it('should have measurement tag condition and tag name IN filter in tag values query', function() { - var builder = new InfluxQueryBuilder({ + const builder = new InfluxQueryBuilder({ measurement: 'cpu', tags: [{ key: 'app', value: 'email' }, { key: 'host', value: 'server1' }], }); - var query = builder.buildExploreQuery('TAG_VALUES', 'app'); + const query = builder.buildExploreQuery('TAG_VALUES', 'app'); expect(query).toBe('SHOW TAG VALUES FROM "cpu" WITH KEY = "app" WHERE "host" = \'server1\''); }); it('should select from policy correctly if policy is specified', function() { - var builder = new InfluxQueryBuilder({ + const builder = new InfluxQueryBuilder({ measurement: 'cpu', policy: 'one_week', tags: [{ key: 'app', value: 'email' }, { key: 'host', value: 'server1' }], }); - var query = builder.buildExploreQuery('TAG_VALUES', 'app'); + const query = builder.buildExploreQuery('TAG_VALUES', 'app'); expect(query).toBe('SHOW TAG VALUES FROM "one_week"."cpu" WITH KEY = "app" WHERE "host" = \'server1\''); }); it('should not include policy when policy is default', function() { - var builder = new InfluxQueryBuilder({ + const builder = new InfluxQueryBuilder({ measurement: 'cpu', policy: 'default', tags: [], }); - var query = builder.buildExploreQuery('TAG_VALUES', 'app'); + const query = builder.buildExploreQuery('TAG_VALUES', 'app'); expect(query).toBe('SHOW TAG VALUES FROM "cpu" WITH KEY = "app"'); }); it('should switch to regex operator in tag condition', function() { - var builder = new InfluxQueryBuilder({ + const builder = new InfluxQueryBuilder({ measurement: 'cpu', tags: [{ key: 'host', value: '/server.*/' }], }); - var query = builder.buildExploreQuery('TAG_VALUES', 'app'); + const query = builder.buildExploreQuery('TAG_VALUES', 'app'); expect(query).toBe('SHOW TAG VALUES FROM "cpu" WITH KEY = "app" WHERE "host" =~ /server.*/'); }); it('should build show field query', function() { - var builder = new InfluxQueryBuilder({ + const builder = new InfluxQueryBuilder({ measurement: 'cpu', tags: [{ key: 'app', value: 'email' }], }); - var query = builder.buildExploreQuery('FIELDS'); + const query = builder.buildExploreQuery('FIELDS'); expect(query).toBe('SHOW FIELD KEYS FROM "cpu"'); }); it('should build show field query with regexp', function() { - var builder = new InfluxQueryBuilder({ + const builder = new InfluxQueryBuilder({ measurement: '/$var/', tags: [{ key: 'app', value: 'email' }], }); - var query = builder.buildExploreQuery('FIELDS'); + const query = builder.buildExploreQuery('FIELDS'); expect(query).toBe('SHOW FIELD KEYS FROM /$var/'); }); it('should build show retention policies query', function() { - var builder = new InfluxQueryBuilder({ measurement: 'cpu', tags: [] }, 'site'); - var query = builder.buildExploreQuery('RETENTION POLICIES'); + const builder = new InfluxQueryBuilder({ measurement: 'cpu', tags: [] }, 'site'); + const query = builder.buildExploreQuery('RETENTION POLICIES'); expect(query).toBe('SHOW RETENTION POLICIES on "site"'); }); }); diff --git a/public/app/plugins/datasource/influxdb/specs/query_part.test.ts b/public/app/plugins/datasource/influxdb/specs/query_part.test.ts index e9e6d216c1e..264c695c8a7 100644 --- a/public/app/plugins/datasource/influxdb/specs/query_part.test.ts +++ b/public/app/plugins/datasource/influxdb/specs/query_part.test.ts @@ -3,7 +3,7 @@ import queryPart from '../query_part'; describe('InfluxQueryPart', () => { describe('series with measurement only', () => { it('should handle nested function parts', () => { - var part = queryPart.create({ + const part = queryPart.create({ type: 'derivative', params: ['10s'], }); @@ -13,7 +13,7 @@ describe('InfluxQueryPart', () => { }); it('should nest spread function', () => { - var part = queryPart.create({ + const part = queryPart.create({ type: 'spread', }); @@ -22,7 +22,7 @@ describe('InfluxQueryPart', () => { }); it('should handle suffix parts', () => { - var part = queryPart.create({ + const part = queryPart.create({ type: 'math', params: ['/ 100'], }); @@ -32,7 +32,7 @@ describe('InfluxQueryPart', () => { }); it('should handle alias parts', () => { - var part = queryPart.create({ + const part = queryPart.create({ type: 'alias', params: ['test'], }); @@ -42,7 +42,7 @@ describe('InfluxQueryPart', () => { }); it('should nest distinct when count is selected', () => { - var selectParts = [ + const selectParts = [ queryPart.create({ type: 'field', category: queryPart.getCategories().Fields, @@ -52,7 +52,7 @@ describe('InfluxQueryPart', () => { category: queryPart.getCategories().Aggregations, }), ]; - var partModel = queryPart.create({ + const partModel = queryPart.create({ type: 'distinct', category: queryPart.getCategories().Aggregations, }); @@ -64,7 +64,7 @@ describe('InfluxQueryPart', () => { }); it('should convert to count distinct when distinct is selected and count added', () => { - var selectParts = [ + const selectParts = [ queryPart.create({ type: 'field', category: queryPart.getCategories().Fields, @@ -74,7 +74,7 @@ describe('InfluxQueryPart', () => { category: queryPart.getCategories().Aggregations, }), ]; - var partModel = queryPart.create({ + const partModel = queryPart.create({ type: 'count', category: queryPart.getCategories().Aggregations, }); @@ -86,7 +86,7 @@ describe('InfluxQueryPart', () => { }); it('should replace count distinct if an aggregation is selected', () => { - var selectParts = [ + const selectParts = [ queryPart.create({ type: 'field', category: queryPart.getCategories().Fields, @@ -100,7 +100,7 @@ describe('InfluxQueryPart', () => { category: queryPart.getCategories().Aggregations, }), ]; - var partModel = queryPart.create({ + const partModel = queryPart.create({ type: 'mean', category: queryPart.getCategories().Selectors, }); @@ -112,7 +112,7 @@ describe('InfluxQueryPart', () => { }); it('should not allowed nested counts when count distinct is selected', () => { - var selectParts = [ + const selectParts = [ queryPart.create({ type: 'field', category: queryPart.getCategories().Fields, @@ -126,7 +126,7 @@ describe('InfluxQueryPart', () => { category: queryPart.getCategories().Aggregations, }), ]; - var partModel = queryPart.create({ + const partModel = queryPart.create({ type: 'count', category: queryPart.getCategories().Aggregations, }); @@ -139,7 +139,7 @@ describe('InfluxQueryPart', () => { }); it('should not remove count distinct when distinct is added', () => { - var selectParts = [ + const selectParts = [ queryPart.create({ type: 'field', category: queryPart.getCategories().Fields, @@ -153,7 +153,7 @@ describe('InfluxQueryPart', () => { category: queryPart.getCategories().Aggregations, }), ]; - var partModel = queryPart.create({ + const partModel = queryPart.create({ type: 'distinct', category: queryPart.getCategories().Aggregations, }); @@ -166,7 +166,7 @@ describe('InfluxQueryPart', () => { }); it('should remove distinct when sum aggregation is selected', () => { - var selectParts = [ + const selectParts = [ queryPart.create({ type: 'field', category: queryPart.getCategories().Fields, @@ -176,7 +176,7 @@ describe('InfluxQueryPart', () => { category: queryPart.getCategories().Aggregations, }), ]; - var partModel = queryPart.create({ + const partModel = queryPart.create({ type: 'sum', category: queryPart.getCategories().Aggregations, }); diff --git a/public/app/plugins/datasource/influxdb/specs/response_parser.test.ts b/public/app/plugins/datasource/influxdb/specs/response_parser.test.ts index 525508b2c1d..cca78974fe3 100644 --- a/public/app/plugins/datasource/influxdb/specs/response_parser.test.ts +++ b/public/app/plugins/datasource/influxdb/specs/response_parser.test.ts @@ -5,8 +5,8 @@ describe('influxdb response parser', () => { const parser = new ResponseParser(); describe('SHOW TAG response', () => { - var query = 'SHOW TAG KEYS FROM "cpu"'; - var response = { + const query = 'SHOW TAG KEYS FROM "cpu"'; + const response = { results: [ { series: [ @@ -20,7 +20,7 @@ describe('influxdb response parser', () => { ], }; - var result = parser.parse(query, response); + const result = parser.parse(query, response); it('expects three results', () => { expect(_.size(result)).toBe(3); @@ -28,10 +28,10 @@ describe('influxdb response parser', () => { }); describe('SHOW TAG VALUES response', () => { - var query = 'SHOW TAG VALUES FROM "cpu" WITH KEY = "hostname"'; + const query = 'SHOW TAG VALUES FROM "cpu" WITH KEY = "hostname"'; describe('response from 0.10.0', () => { - var response = { + const response = { results: [ { series: [ @@ -45,7 +45,7 @@ describe('influxdb response parser', () => { ], }; - var result = parser.parse(query, response); + const result = parser.parse(query, response); it('should get two responses', () => { expect(_.size(result)).toBe(2); @@ -55,7 +55,7 @@ describe('influxdb response parser', () => { }); describe('response from 0.12.0', () => { - var response = { + const response = { results: [ { series: [ @@ -74,7 +74,7 @@ describe('influxdb response parser', () => { ], }; - var result = parser.parse(query, response); + const result = parser.parse(query, response); it('should get two responses', () => { expect(_.size(result)).toBe(3); @@ -86,8 +86,8 @@ describe('influxdb response parser', () => { }); describe('SELECT response', () => { - var query = 'SELECT "usage_iowait" FROM "cpu" LIMIT 10'; - var response = { + const query = 'SELECT "usage_iowait" FROM "cpu" LIMIT 10'; + const response = { results: [ { series: [ @@ -101,7 +101,7 @@ describe('influxdb response parser', () => { ], }; - var result = parser.parse(query, response); + const result = parser.parse(query, response); it('should return second column', () => { expect(_.size(result)).toBe(3); @@ -112,10 +112,10 @@ describe('influxdb response parser', () => { }); describe('SHOW FIELD response', () => { - var query = 'SHOW FIELD KEYS FROM "cpu"'; + const query = 'SHOW FIELD KEYS FROM "cpu"'; describe('response from pre-1.0', () => { - var response = { + const response = { results: [ { series: [ @@ -129,7 +129,7 @@ describe('influxdb response parser', () => { ], }; - var result = parser.parse(query, response); + const result = parser.parse(query, response); it('should get two responses', () => { expect(_.size(result)).toBe(1); @@ -137,7 +137,7 @@ describe('influxdb response parser', () => { }); describe('response from 1.0', () => { - var response = { + const response = { results: [ { series: [ @@ -151,7 +151,7 @@ describe('influxdb response parser', () => { ], }; - var result = parser.parse(query, response); + const result = parser.parse(query, response); it('should return first column', () => { expect(_.size(result)).toBe(1); diff --git a/public/app/plugins/datasource/opentsdb/specs/datasource.test.ts b/public/app/plugins/datasource/opentsdb/specs/datasource.test.ts index befa39fc80e..e7e53c0dd5b 100644 --- a/public/app/plugins/datasource/opentsdb/specs/datasource.test.ts +++ b/public/app/plugins/datasource/opentsdb/specs/datasource.test.ts @@ -16,8 +16,8 @@ describe('opentsdb', () => { }); describe('When performing metricFindQuery', () => { - var results; - var requestOptions; + let results; + let requestOptions; beforeEach(async () => { ctx.backendSrv.datasourceRequest = await function(options) { diff --git a/public/app/plugins/datasource/opentsdb/specs/query_ctrl.test.ts b/public/app/plugins/datasource/opentsdb/specs/query_ctrl.test.ts index 58a10b21207..6fdcd29aecd 100644 --- a/public/app/plugins/datasource/opentsdb/specs/query_ctrl.test.ts +++ b/public/app/plugins/datasource/opentsdb/specs/query_ctrl.test.ts @@ -1,7 +1,7 @@ import { OpenTsQueryCtrl } from '../query_ctrl'; describe('OpenTsQueryCtrl', () => { - var ctx = { + const ctx = { target: { target: '' }, datasource: { tsdbVersion: '', diff --git a/public/app/plugins/datasource/prometheus/specs/datasource.test.ts b/public/app/plugins/datasource/prometheus/specs/datasource.test.ts index fd963f7986e..846a00212d0 100644 --- a/public/app/plugins/datasource/prometheus/specs/datasource.test.ts +++ b/public/app/plugins/datasource/prometheus/specs/datasource.test.ts @@ -409,14 +409,14 @@ const timeSrv = { describe('PrometheusDatasource', () => { describe('When querying prometheus with one target using query editor target spec', async () => { - var results; - var query = { + let results; + const query = { range: { from: time({ seconds: 63 }), to: time({ seconds: 183 }) }, targets: [{ expr: 'test{job="testjob"}', format: 'time_series' }], interval: '60s', }; // Interval alignment with step - var urlExpected = + const urlExpected = 'proxied/api/v1/query_range?query=' + encodeURIComponent('test{job="testjob"}') + '&start=60&end=240&step=60'; beforeEach(async () => { @@ -453,12 +453,12 @@ describe('PrometheusDatasource', () => { }); }); describe('When querying prometheus with one target which return multiple series', () => { - var results; - var start = 60; - var end = 360; - var step = 60; + let results; + const start = 60; + const end = 360; + const step = 60; - var query = { + const query = { range: { from: time({ seconds: start }), to: time({ seconds: end }) }, targets: [{ expr: 'test{job="testjob"}', format: 'time_series' }], interval: '60s', @@ -505,7 +505,7 @@ describe('PrometheusDatasource', () => { expect(results.data[0].datapoints[1][0]).toBe(3846); }); it('should fill null after last datapoint in response', () => { - var length = (end - start) / step + 1; + const length = (end - start) / step + 1; expect(results.data[0].datapoints[length - 2][1]).toBe((end - step * 1) * 1000); expect(results.data[0].datapoints[length - 2][0]).toBe(3848); expect(results.data[0].datapoints[length - 1][1]).toBe(end * 1000); @@ -521,9 +521,9 @@ describe('PrometheusDatasource', () => { }); }); describe('When querying prometheus with one target and instant = true', () => { - var results; - var urlExpected = 'proxied/api/v1/query?query=' + encodeURIComponent('test{job="testjob"}') + '&time=123'; - var query = { + let results; + const urlExpected = 'proxied/api/v1/query?query=' + encodeURIComponent('test{job="testjob"}') + '&time=123'; + const query = { range: { from: time({ seconds: 63 }), to: time({ seconds: 123 }) }, targets: [{ expr: 'test{job="testjob"}', format: 'time_series', instant: true }], interval: '60s', @@ -563,9 +563,9 @@ describe('PrometheusDatasource', () => { }); }); describe('When performing annotationQuery', () => { - var results; + let results; - var options = { + const options = { annotation: { expr: 'ALERTS{alertstate="firing"}', tagKeys: 'job', @@ -617,8 +617,8 @@ describe('PrometheusDatasource', () => { }); describe('When resultFormat is table and instant = true', () => { - var results; - var query = { + let results; + const query = { range: { from: time({ seconds: 63 }), to: time({ seconds: 123 }) }, targets: [{ expr: 'test{job="testjob"}', format: 'time_series', instant: true }], interval: '60s', @@ -653,7 +653,7 @@ describe('PrometheusDatasource', () => { }); describe('The "step" query parameter', () => { - var response = { + const response = { status: 'success', data: { data: { @@ -686,13 +686,13 @@ describe('PrometheusDatasource', () => { }); it('step should never go below 1', async () => { - var query = { + const query = { // 6 minute range range: { from: time({ minutes: 1 }), to: time({ minutes: 7 }) }, targets: [{ expr: 'test' }], interval: '100ms', }; - var urlExpected = 'proxied/api/v1/query_range?query=test&start=60&end=420&step=1'; + const urlExpected = 'proxied/api/v1/query_range?query=test&start=60&end=420&step=1'; backendSrv.datasourceRequest = jest.fn(() => Promise.resolve(response)); ctx.ds = new PrometheusDatasource(instanceSettings, q, backendSrv, templateSrv, timeSrv); await ctx.ds.query(query); @@ -702,7 +702,7 @@ describe('PrometheusDatasource', () => { }); it('should be auto interval when greater than min interval', async () => { - var query = { + const query = { // 6 minute range range: { from: time({ minutes: 1 }), to: time({ minutes: 7 }) }, targets: [ @@ -713,7 +713,7 @@ describe('PrometheusDatasource', () => { ], interval: '10s', }; - var 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); @@ -722,15 +722,15 @@ describe('PrometheusDatasource', () => { expect(res.url).toBe(urlExpected); }); it('should result in querying fewer than 11000 data points', async () => { - var query = { + const query = { // 6 hour range range: { from: time({ hours: 1 }), to: time({ hours: 7 }) }, targets: [{ expr: 'test' }], interval: '1s', }; - var end = 7 * 60 * 60; - var start = 60 * 60; - var urlExpected = 'proxied/api/v1/query_range?query=test&start=' + start + '&end=' + end + '&step=2'; + const end = 7 * 60 * 60; + const start = 60 * 60; + const urlExpected = 'proxied/api/v1/query_range?query=test&start=' + start + '&end=' + end + '&step=2'; backendSrv.datasourceRequest = jest.fn(() => Promise.resolve(response)); ctx.ds = new PrometheusDatasource(instanceSettings, q, backendSrv, templateSrv, timeSrv); await ctx.ds.query(query); @@ -739,7 +739,7 @@ describe('PrometheusDatasource', () => { expect(res.url).toBe(urlExpected); }); it('should not apply min interval when interval * intervalFactor greater', async () => { - var query = { + const query = { // 6 minute range range: { from: time({ minutes: 1 }), to: time({ minutes: 7 }) }, targets: [ @@ -752,7 +752,7 @@ describe('PrometheusDatasource', () => { interval: '5s', }; // times get rounded up to interval - var urlExpected = 'proxied/api/v1/query_range?query=test&start=50&end=450&step=50'; + const urlExpected = 'proxied/api/v1/query_range?query=test&start=50&end=450&step=50'; backendSrv.datasourceRequest = jest.fn(() => Promise.resolve(response)); ctx.ds = new PrometheusDatasource(instanceSettings, q, backendSrv, templateSrv, timeSrv); await ctx.ds.query(query); @@ -761,7 +761,7 @@ describe('PrometheusDatasource', () => { expect(res.url).toBe(urlExpected); }); it('should apply min interval when interval * intervalFactor smaller', async () => { - var query = { + const query = { // 6 minute range range: { from: time({ minutes: 1 }), to: time({ minutes: 7 }) }, targets: [ @@ -773,7 +773,7 @@ describe('PrometheusDatasource', () => { ], interval: '5s', }; - var urlExpected = 'proxied/api/v1/query_range?query=test' + '&start=60&end=420&step=15'; + const urlExpected = 'proxied/api/v1/query_range?query=test' + '&start=60&end=420&step=15'; backendSrv.datasourceRequest = jest.fn(() => Promise.resolve(response)); ctx.ds = new PrometheusDatasource(instanceSettings, q, backendSrv, templateSrv, timeSrv); await ctx.ds.query(query); @@ -782,7 +782,7 @@ describe('PrometheusDatasource', () => { expect(res.url).toBe(urlExpected); }); it('should apply intervalFactor to auto interval when greater', async () => { - var query = { + const query = { // 6 minute range range: { from: time({ minutes: 1 }), to: time({ minutes: 7 }) }, targets: [ @@ -795,7 +795,7 @@ describe('PrometheusDatasource', () => { interval: '10s', }; // times get aligned to interval - var urlExpected = 'proxied/api/v1/query_range?query=test' + '&start=0&end=500&step=100'; + const urlExpected = 'proxied/api/v1/query_range?query=test' + '&start=0&end=500&step=100'; backendSrv.datasourceRequest = jest.fn(() => Promise.resolve(response)); ctx.ds = new PrometheusDatasource(instanceSettings, q, backendSrv, templateSrv, timeSrv); await ctx.ds.query(query); @@ -804,7 +804,7 @@ describe('PrometheusDatasource', () => { expect(res.url).toBe(urlExpected); }); it('should not not be affected by the 11000 data points limit when large enough', async () => { - var query = { + const query = { // 1 week range range: { from: time({}), to: time({ hours: 7 * 24 }) }, targets: [ @@ -815,9 +815,9 @@ describe('PrometheusDatasource', () => { ], interval: '10s', }; - var end = 7 * 24 * 60 * 60; - var start = 0; - var urlExpected = 'proxied/api/v1/query_range?query=test' + '&start=' + start + '&end=' + end + '&step=100'; + const end = 7 * 24 * 60 * 60; + const start = 0; + const urlExpected = 'proxied/api/v1/query_range?query=test' + '&start=' + start + '&end=' + end + '&step=100'; backendSrv.datasourceRequest = jest.fn(() => Promise.resolve(response)); ctx.ds = new PrometheusDatasource(instanceSettings, q, backendSrv, templateSrv, timeSrv); await ctx.ds.query(query); @@ -826,7 +826,7 @@ describe('PrometheusDatasource', () => { expect(res.url).toBe(urlExpected); }); it('should be determined by the 11000 data points limit when too small', async () => { - var query = { + const query = { // 1 week range range: { from: time({}), to: time({ hours: 7 * 24 }) }, targets: [ @@ -837,9 +837,9 @@ describe('PrometheusDatasource', () => { ], interval: '5s', }; - var end = 7 * 24 * 60 * 60; - var start = 0; - var urlExpected = 'proxied/api/v1/query_range?query=test' + '&start=' + start + '&end=' + end + '&step=60'; + const end = 7 * 24 * 60 * 60; + const start = 0; + const urlExpected = 'proxied/api/v1/query_range?query=test' + '&start=' + start + '&end=' + end + '&step=60'; backendSrv.datasourceRequest = jest.fn(() => Promise.resolve(response)); ctx.ds = new PrometheusDatasource(instanceSettings, q, backendSrv, templateSrv, timeSrv); await ctx.ds.query(query); @@ -850,7 +850,7 @@ describe('PrometheusDatasource', () => { }); describe('The __interval and __interval_ms template variables', () => { - var response = { + const response = { status: 'success', data: { data: { @@ -861,7 +861,7 @@ describe('PrometheusDatasource', () => { }; it('should be unchanged when auto interval is greater than min interval', async () => { - var query = { + const query = { // 6 minute range range: { from: time({ minutes: 1 }), to: time({ minutes: 7 }) }, targets: [ @@ -877,7 +877,7 @@ describe('PrometheusDatasource', () => { }, }; - var urlExpected = + const urlExpected = 'proxied/api/v1/query_range?query=' + encodeURIComponent('rate(test[$__interval])') + '&start=60&end=420&step=10'; @@ -902,7 +902,7 @@ describe('PrometheusDatasource', () => { }); }); it('should be min interval when it is greater than auto interval', async () => { - var query = { + const query = { // 6 minute range range: { from: time({ minutes: 1 }), to: time({ minutes: 7 }) }, targets: [ @@ -917,7 +917,7 @@ describe('PrometheusDatasource', () => { __interval_ms: { text: 5 * 1000, value: 5 * 1000 }, }, }; - var urlExpected = + const urlExpected = 'proxied/api/v1/query_range?query=' + encodeURIComponent('rate(test[$__interval])') + '&start=60&end=420&step=10'; @@ -941,7 +941,7 @@ describe('PrometheusDatasource', () => { }); }); it('should account for intervalFactor', async () => { - var query = { + const query = { // 6 minute range range: { from: time({ minutes: 1 }), to: time({ minutes: 7 }) }, targets: [ @@ -957,7 +957,7 @@ describe('PrometheusDatasource', () => { __interval_ms: { text: 10 * 1000, value: 10 * 1000 }, }, }; - var urlExpected = + const urlExpected = 'proxied/api/v1/query_range?query=' + encodeURIComponent('rate(test[$__interval])') + '&start=0&end=500&step=100'; @@ -986,7 +986,7 @@ describe('PrometheusDatasource', () => { expect(query.scopedVars.__interval_ms.value).toBe(10 * 1000); }); it('should be interval * intervalFactor when greater than min interval', async () => { - var query = { + const query = { // 6 minute range range: { from: time({ minutes: 1 }), to: time({ minutes: 7 }) }, targets: [ @@ -1002,7 +1002,7 @@ describe('PrometheusDatasource', () => { __interval_ms: { text: 5 * 1000, value: 5 * 1000 }, }, }; - var urlExpected = + const urlExpected = 'proxied/api/v1/query_range?query=' + encodeURIComponent('rate(test[$__interval])') + '&start=50&end=450&step=50'; @@ -1027,7 +1027,7 @@ describe('PrometheusDatasource', () => { }); }); it('should be min interval when greater than interval * intervalFactor', async () => { - var query = { + const query = { // 6 minute range range: { from: time({ minutes: 1 }), to: time({ minutes: 7 }) }, targets: [ @@ -1043,7 +1043,7 @@ describe('PrometheusDatasource', () => { __interval_ms: { text: 5 * 1000, value: 5 * 1000 }, }, }; - var urlExpected = + const urlExpected = 'proxied/api/v1/query_range?query=' + encodeURIComponent('rate(test[$__interval])') + '&start=60&end=420&step=15'; @@ -1067,7 +1067,7 @@ describe('PrometheusDatasource', () => { }); }); it('should be determined by the 11000 data points limit, accounting for intervalFactor', async () => { - var query = { + const query = { // 1 week range range: { from: time({}), to: time({ hours: 7 * 24 }) }, targets: [ @@ -1082,9 +1082,9 @@ describe('PrometheusDatasource', () => { __interval_ms: { text: 5 * 1000, value: 5 * 1000 }, }, }; - var end = 7 * 24 * 60 * 60; - var start = 0; - var urlExpected = + const end = 7 * 24 * 60 * 60; + const start = 0; + const urlExpected = 'proxied/api/v1/query_range?query=' + encodeURIComponent('rate(test[$__interval])') + '&start=' + @@ -1115,7 +1115,7 @@ describe('PrometheusDatasource', () => { }); describe('PrometheusDatasource for POST', () => { - // var ctx = new helpers.ServiceTestContext(); + // const ctx = new helpers.ServiceTestContext(); const instanceSettings = { url: 'proxied', directUrl: 'direct', @@ -1125,15 +1125,15 @@ describe('PrometheusDatasource for POST', () => { }; describe('When querying prometheus with one target using query editor target spec', () => { - var results; - var urlExpected = 'proxied/api/v1/query_range'; - var dataExpected = { + let results; + const urlExpected = 'proxied/api/v1/query_range'; + const dataExpected = { query: 'test{job="testjob"}', start: 1 * 60, end: 3 * 60, step: 60, }; - var query = { + const query = { range: { from: time({ minutes: 1, seconds: 3 }), to: time({ minutes: 2, seconds: 3 }) }, targets: [{ expr: 'test{job="testjob"}', format: 'time_series' }], interval: '60s', 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 ac85e1374bb..0ccb79a5d1f 100644 --- a/public/app/plugins/datasource/prometheus/specs/result_transformer.test.ts +++ b/public/app/plugins/datasource/prometheus/specs/result_transformer.test.ts @@ -11,7 +11,7 @@ describe('Prometheus Result Transformer', () => { }); describe('When resultFormat is table', () => { - var response = { + const response = { status: 'success', data: { resultType: 'matrix', @@ -33,7 +33,7 @@ describe('Prometheus Result Transformer', () => { }; it('should return table model', () => { - var table = ctx.resultTransformer.transformMetricDataToTable(response.data.result); + const table = ctx.resultTransformer.transformMetricDataToTable(response.data.result); expect(table.type).toBe('table'); expect(table.rows).toEqual([ [1443454528000, 'test', '', 'testjob', 3846], @@ -49,7 +49,7 @@ describe('Prometheus Result Transformer', () => { }); it('should column title include refId if response count is more than 2', () => { - var table = ctx.resultTransformer.transformMetricDataToTable(response.data.result, 2, 'B'); + const table = ctx.resultTransformer.transformMetricDataToTable(response.data.result, 2, 'B'); expect(table.type).toBe('table'); expect(table.columns).toMatchObject([ { text: 'Time', type: 'time' }, @@ -62,7 +62,7 @@ describe('Prometheus Result Transformer', () => { }); describe('When resultFormat is table and instant = true', () => { - var response = { + const response = { status: 'success', data: { resultType: 'vector', @@ -76,7 +76,7 @@ describe('Prometheus Result Transformer', () => { }; it('should return table model', () => { - var table = ctx.resultTransformer.transformMetricDataToTable(response.data.result); + const table = ctx.resultTransformer.transformMetricDataToTable(response.data.result); expect(table.type).toBe('table'); expect(table.rows).toEqual([[1443454528000, 'test', 'testjob', 3846]]); expect(table.columns).toMatchObject([ @@ -89,7 +89,7 @@ describe('Prometheus Result Transformer', () => { }); describe('When resultFormat is heatmap', () => { - var response = { + const response = { status: 'success', data: { resultType: 'matrix', diff --git a/public/app/plugins/panel/graph/specs/data_processor.test.ts b/public/app/plugins/panel/graph/specs/data_processor.test.ts index 3ae34e277c8..2e8d4eb6eab 100644 --- a/public/app/plugins/panel/graph/specs/data_processor.test.ts +++ b/public/app/plugins/panel/graph/specs/data_processor.test.ts @@ -1,11 +1,11 @@ import { DataProcessor } from '../data_processor'; describe('Graph DataProcessor', function() { - var panel: any = { + const panel: any = { xaxis: {}, }; - var processor = new DataProcessor(panel); + const processor = new DataProcessor(panel); describe('Given default xaxis options and query that returns docs', () => { beforeEach(() => { @@ -29,7 +29,7 @@ describe('Graph DataProcessor', function() { }); describe('getDataFieldNames(', () => { - var dataList = [ + const dataList = [ { type: 'docs', datapoints: [ @@ -46,7 +46,7 @@ describe('Graph DataProcessor', function() { ]; it('Should return all field names', () => { - var fields = processor.getDataFieldNames(dataList, false); + const fields = processor.getDataFieldNames(dataList, false); expect(fields).toContain('hostname'); expect(fields).toContain('valueField'); expect(fields).toContain('nested.prop1'); @@ -54,7 +54,7 @@ describe('Graph DataProcessor', function() { }); it('Should return all number fields', () => { - var fields = processor.getDataFieldNames(dataList, true); + const fields = processor.getDataFieldNames(dataList, true); expect(fields).toContain('valueField'); expect(fields).toContain('nested.value2'); }); diff --git a/public/app/plugins/panel/graph/specs/graph.test.ts b/public/app/plugins/panel/graph/specs/graph.test.ts index 2ae76bb9c9c..64dd1de01ed 100644 --- a/public/app/plugins/panel/graph/specs/graph.test.ts +++ b/public/app/plugins/panel/graph/specs/graph.test.ts @@ -243,7 +243,7 @@ describe('grafanaGraph', function() { }); it('should apply axis transform, autoscaling (if necessary) and ticks', function() { - var axisAutoscale = ctx.plotOptions.yaxes[0]; + const axisAutoscale = ctx.plotOptions.yaxes[0]; expect(axisAutoscale.transform(100)).toBe(2); expect(axisAutoscale.inverseTransform(-3)).toBeCloseTo(0.001); expect(axisAutoscale.min).toBeCloseTo(0.001); @@ -256,7 +256,7 @@ describe('grafanaGraph', function() { expect(axisAutoscale.ticks[axisAutoscale.ticks.length - 1]).toBe(10000); } - var axisFixedscale = ctx.plotOptions.yaxes[1]; + const axisFixedscale = ctx.plotOptions.yaxes[1]; expect(axisFixedscale.min).toBe(0.05); expect(axisFixedscale.max).toBe(1500); expect(axisFixedscale.ticks.length).toBe(5); @@ -278,7 +278,7 @@ describe('grafanaGraph', function() { }); it('should not set min and max and should create some fake ticks', function() { - var axisAutoscale = ctx.plotOptions.yaxes[0]; + const axisAutoscale = ctx.plotOptions.yaxes[0]; expect(axisAutoscale.transform(100)).toBe(2); expect(axisAutoscale.inverseTransform(-3)).toBeCloseTo(0.001); expect(axisAutoscale.min).toBe(undefined); @@ -304,7 +304,7 @@ describe('grafanaGraph', function() { }); }); it('should set min to 0.1 and add a tick for 0.1', function() { - var axisAutoscale = ctx.plotOptions.yaxes[0]; + const axisAutoscale = ctx.plotOptions.yaxes[0]; expect(axisAutoscale.transform(100)).toBe(2); expect(axisAutoscale.inverseTransform(-3)).toBeCloseTo(0.001); expect(axisAutoscale.min).toBe(0.1); @@ -331,7 +331,7 @@ describe('grafanaGraph', function() { }); it('should regenerate ticks so that if fits on the y-axis', function() { - var axisAutoscale = ctx.plotOptions.yaxes[0]; + const axisAutoscale = ctx.plotOptions.yaxes[0]; expect(axisAutoscale.min).toBe(0.1); expect(axisAutoscale.ticks.length).toBe(8); expect(axisAutoscale.ticks[0]).toBe(0.1); @@ -432,7 +432,7 @@ describe('grafanaGraph', function() { }); it('should show percentage', function() { - var axis = ctx.plotOptions.yaxes[0]; + const axis = ctx.plotOptions.yaxes[0]; expect(axis.tickFormatter(100, axis)).toBe('100%'); }); }); @@ -448,7 +448,7 @@ describe('grafanaGraph', function() { }); it('should format dates as hours minutes', function() { - var axis = ctx.plotOptions.xaxis; + const axis = ctx.plotOptions.xaxis; expect(axis.timeformat).toBe('%H:%M'); }); }); @@ -462,7 +462,7 @@ describe('grafanaGraph', function() { }); it('should format dates as month days', function() { - var axis = ctx.plotOptions.xaxis; + const axis = ctx.plotOptions.xaxis; expect(axis.timeformat).toBe('%m/%d'); }); }); 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 49efa8d4120..2feb94a5626 100644 --- a/public/app/plugins/panel/graph/specs/graph_ctrl.test.ts +++ b/public/app/plugins/panel/graph/specs/graph_ctrl.test.ts @@ -43,7 +43,7 @@ describe('GraphCtrl', () => { describe('when time series are outside range', () => { beforeEach(() => { - var data = [ + const data = [ { target: 'test.cpu1', datapoints: [[45, 1234567890], [60, 1234567899]], @@ -61,14 +61,14 @@ describe('GraphCtrl', () => { describe('when time series are inside range', () => { beforeEach(() => { - var range = { + const range = { from: moment() .subtract(1, 'days') .valueOf(), to: moment().valueOf(), }; - var data = [ + const data = [ { target: 'test.cpu1', datapoints: [[45, range.from + 1000], [60, range.from + 10000]], @@ -86,7 +86,7 @@ describe('GraphCtrl', () => { describe('datapointsCount given 2 series', () => { beforeEach(() => { - var data = [{ target: 'test.cpu1', datapoints: [] }, { target: 'test.cpu2', datapoints: [] }]; + const data = [{ target: 'test.cpu1', datapoints: [] }, { target: 'test.cpu2', datapoints: [] }]; ctx.ctrl.onDataReceived(data); }); diff --git a/public/app/plugins/panel/graph/specs/graph_tooltip.test.ts b/public/app/plugins/panel/graph/specs/graph_tooltip.test.ts index baebf2c5930..ecc6ce0fb21 100644 --- a/public/app/plugins/panel/graph/specs/graph_tooltip.test.ts +++ b/public/app/plugins/panel/graph/specs/graph_tooltip.test.ts @@ -3,18 +3,18 @@ jest.mock('app/core/core', () => ({})); import $ from 'jquery'; import GraphTooltip from '../graph_tooltip'; -var scope = { +const scope = { appEvent: jest.fn(), onAppEvent: jest.fn(), ctrl: {}, }; -var elem = $('
    '); -var dashboard = {}; -var getSeriesFn; +const elem = $('
    '); +const dashboard = {}; +const getSeriesFn = () => {}; function describeSharedTooltip(desc, fn) { - var ctx: any = {}; + const ctx: any = {}; ctx.ctrl = scope.ctrl; ctx.ctrl.panel = { tooltip: { @@ -31,7 +31,7 @@ function describeSharedTooltip(desc, fn) { describe(desc, function() { beforeEach(function() { ctx.setupFn(); - var tooltip = new GraphTooltip(elem, dashboard, scope, getSeriesFn); + const tooltip = new GraphTooltip(elem, dashboard, scope, getSeriesFn); ctx.results = tooltip.getMultiSeriesPlotHoverInfo(ctx.data, ctx.pos); }); @@ -40,28 +40,28 @@ function describeSharedTooltip(desc, fn) { } describe('findHoverIndexFromData', function() { - var tooltip = new GraphTooltip(elem, dashboard, scope, getSeriesFn); - var series = { + const tooltip = new GraphTooltip(elem, dashboard, scope, getSeriesFn); + const series = { data: [[100, 0], [101, 0], [102, 0], [103, 0], [104, 0], [105, 0], [106, 0], [107, 0]], }; it('should return 0 if posX out of lower bounds', function() { - var posX = 99; + const posX = 99; expect(tooltip.findHoverIndexFromData(posX, series)).toBe(0); }); it('should return n - 1 if posX out of upper bounds', function() { - var posX = 108; + const posX = 108; expect(tooltip.findHoverIndexFromData(posX, series)).toBe(series.data.length - 1); }); it('should return i if posX in series', function() { - var posX = 104; + const posX = 104; expect(tooltip.findHoverIndexFromData(posX, series)).toBe(4); }); it('should return i if posX not in series and i + 1 > posX', function() { - var posX = 104.9; + const posX = 104.9; expect(tooltip.findHoverIndexFromData(posX, series)).toBe(4); }); }); diff --git a/public/app/plugins/panel/graph/specs/threshold_manager.test.ts b/public/app/plugins/panel/graph/specs/threshold_manager.test.ts index 4a7a46fc6b0..ecbc382923e 100644 --- a/public/app/plugins/panel/graph/specs/threshold_manager.test.ts +++ b/public/app/plugins/panel/graph/specs/threshold_manager.test.ts @@ -5,7 +5,7 @@ import { ThresholdManager } from '../threshold_manager'; describe('ThresholdManager', function() { function plotOptionsScenario(desc, func) { describe(desc, function() { - var ctx: any = { + const ctx: any = { panel: { thresholds: [], }, @@ -17,9 +17,9 @@ describe('ThresholdManager', function() { ctx.setup = function(thresholds, data) { ctx.panel.thresholds = thresholds; - var manager = new ThresholdManager(ctx.panelCtrl); + const manager = new ThresholdManager(ctx.panelCtrl); if (data !== undefined) { - var element = angular.element('
    '); + const element = angular.element('
    '); manager.prepare(element, data); } manager.addFlotOptions(ctx.options, ctx.panel); @@ -34,7 +34,7 @@ describe('ThresholdManager', function() { ctx.setup([{ op: 'gt', value: 300, fill: true, line: true, colorMode: 'critical' }]); it('should add fill for threshold with fill: true', function() { - var markings = ctx.options.grid.markings; + const markings = ctx.options.grid.markings; expect(markings[0].yaxis.from).toBe(300); expect(markings[0].yaxis.to).toBe(Infinity); @@ -42,7 +42,7 @@ describe('ThresholdManager', function() { }); it('should add line', function() { - var markings = ctx.options.grid.markings; + const markings = ctx.options.grid.markings; expect(markings[1].yaxis.from).toBe(300); expect(markings[1].yaxis.to).toBe(300); expect(markings[1].color).toBe('rgba(237, 46, 24, 0.60)'); @@ -56,13 +56,13 @@ describe('ThresholdManager', function() { ]); it('should add fill for first thresholds to next threshold', function() { - var markings = ctx.options.grid.markings; + const markings = ctx.options.grid.markings; expect(markings[0].yaxis.from).toBe(200); expect(markings[0].yaxis.to).toBe(300); }); it('should add fill for last thresholds to infinity', function() { - var markings = ctx.options.grid.markings; + const markings = ctx.options.grid.markings; expect(markings[1].yaxis.from).toBe(300); expect(markings[1].yaxis.to).toBe(Infinity); }); @@ -75,13 +75,13 @@ describe('ThresholdManager', function() { ]); it('should add fill for first thresholds to next threshold', function() { - var markings = ctx.options.grid.markings; + const markings = ctx.options.grid.markings; expect(markings[0].yaxis.from).toBe(300); expect(markings[0].yaxis.to).toBe(200); }); it('should add fill for last thresholds to itself', function() { - var markings = ctx.options.grid.markings; + const markings = ctx.options.grid.markings; expect(markings[1].yaxis.from).toBe(200); expect(markings[1].yaxis.to).toBe(200); }); @@ -94,20 +94,20 @@ describe('ThresholdManager', function() { ]); it('should add fill for first thresholds to next threshold', function() { - var markings = ctx.options.grid.markings; + const markings = ctx.options.grid.markings; expect(markings[0].yaxis.from).toBe(300); expect(markings[0].yaxis.to).toBe(Infinity); }); it('should add fill for last thresholds to itself', function() { - var markings = ctx.options.grid.markings; + const markings = ctx.options.grid.markings; expect(markings[1].yaxis.from).toBe(200); expect(markings[1].yaxis.to).toBe(-Infinity); }); }); plotOptionsScenario('for threshold on two Y axes', ctx => { - var data = new Array(2); + const data = new Array(2); data[0] = new TimeSeries({ datapoints: [[0, 1], [300, 2]], alias: 'left', @@ -127,12 +127,12 @@ describe('ThresholdManager', function() { ); it('should add first threshold for left axis', function() { - var markings = ctx.options.grid.markings; + const markings = ctx.options.grid.markings; expect(markings[0].yaxis.from).toBe(100); }); it('should add second threshold for right axis', function() { - var markings = ctx.options.grid.markings; + const markings = ctx.options.grid.markings; expect(markings[1].y2axis.from).toBe(200); }); }); 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 d9d929a2697..8e1623c7d6f 100644 --- a/public/app/plugins/panel/heatmap/specs/heatmap_ctrl.test.ts +++ b/public/app/plugins/panel/heatmap/specs/heatmap_ctrl.test.ts @@ -25,7 +25,7 @@ describe('HeatmapCtrl', function() { describe('when time series are outside range', function() { beforeEach(function() { - var data = [ + const data = [ { target: 'test.cpu1', datapoints: [[45, 1234567890], [60, 1234567899]], @@ -43,14 +43,14 @@ describe('HeatmapCtrl', function() { describe('when time series are inside range', function() { beforeEach(function() { - var range = { + const range = { from: moment() .subtract(1, 'days') .valueOf(), to: moment().valueOf(), }; - var data = [ + const data = [ { target: 'test.cpu1', datapoints: [[45, range.from + 1000], [60, range.from + 10000]], @@ -68,7 +68,7 @@ describe('HeatmapCtrl', function() { describe('datapointsCount given 2 series', function() { beforeEach(function() { - var data = [{ target: 'test.cpu1', datapoints: [] }, { target: 'test.cpu2', datapoints: [] }]; + const data = [{ target: 'test.cpu1', datapoints: [] }, { target: 'test.cpu2', datapoints: [] }]; ctx.ctrl.onDataReceived(data); }); diff --git a/public/app/plugins/panel/singlestat/specs/singlestat_panel.test.ts b/public/app/plugins/panel/singlestat/specs/singlestat_panel.test.ts index 028200147f7..114cdf132e1 100644 --- a/public/app/plugins/panel/singlestat/specs/singlestat_panel.test.ts +++ b/public/app/plugins/panel/singlestat/specs/singlestat_panel.test.ts @@ -3,7 +3,7 @@ import { getColorForValue } from '../module'; describe('grafanaSingleStat', function() { describe('legacy thresholds', () => { describe('positive thresholds', () => { - var data: any = { + const data: any = { colorMap: ['green', 'yellow', 'red'], thresholds: [20, 50], }; @@ -39,7 +39,7 @@ describe('grafanaSingleStat', function() { }); describe('negative thresholds', () => { - var data: any = { + const data: any = { colorMap: ['green', 'yellow', 'red'], thresholds: [0, 20], }; @@ -58,7 +58,7 @@ describe('grafanaSingleStat', function() { }); describe('negative thresholds', () => { - var data: any = { + const data: any = { colorMap: ['green', 'yellow', 'red'], thresholds: [-27, 20], }; diff --git a/public/app/plugins/panel/table/specs/renderer.test.ts b/public/app/plugins/panel/table/specs/renderer.test.ts index 22957d1aa66..b66984ba223 100644 --- a/public/app/plugins/panel/table/specs/renderer.test.ts +++ b/public/app/plugins/panel/table/specs/renderer.test.ts @@ -4,7 +4,7 @@ import { TableRenderer } from '../renderer'; describe('when rendering table', () => { describe('given 13 columns', () => { - var table = new TableModel(); + const table = new TableModel(); table.columns = [ { text: 'Time' }, { text: 'Value' }, @@ -24,7 +24,7 @@ describe('when rendering table', () => { [1388556366666, 1230, 40, undefined, '', '', 'my.host.com', 'host1', ['value1', 'value2'], 1, 2, 1, 2], ]; - var panel = { + const panel = { pageSize: 10, styles: [ { @@ -163,11 +163,11 @@ describe('when rendering table', () => { ], }; - var sanitize = function(value) { + const sanitize = function(value) { return 'sanitized'; }; - var templateSrv = { + const templateSrv = { replace: function(value, scopedVars) { if (scopedVars) { // For testing variables replacement in link @@ -179,75 +179,75 @@ describe('when rendering table', () => { }, }; - var renderer = new TableRenderer(panel, table, 'utc', sanitize, templateSrv); + const renderer = new TableRenderer(panel, table, 'utc', sanitize, templateSrv); it('time column should be formated', () => { - var html = renderer.renderCell(0, 0, 1388556366666); + const html = renderer.renderCell(0, 0, 1388556366666); expect(html).toBe('
    '); }); it('undefined time column should be rendered as -', () => { - var html = renderer.renderCell(0, 0, undefined); + const html = renderer.renderCell(0, 0, undefined); expect(html).toBe(''); }); it('null time column should be rendered as -', () => { - var html = renderer.renderCell(0, 0, null); + const html = renderer.renderCell(0, 0, null); expect(html).toBe(''); }); it('number column with unit specified should ignore style unit', () => { - var html = renderer.renderCell(5, 0, 1230); + const html = renderer.renderCell(5, 0, 1230); expect(html).toBe(''); }); it('number column should be formated', () => { - var html = renderer.renderCell(1, 0, 1230); + const html = renderer.renderCell(1, 0, 1230); expect(html).toBe(''); }); it('number style should ignore string values', () => { - var html = renderer.renderCell(1, 0, 'asd'); + const html = renderer.renderCell(1, 0, 'asd'); expect(html).toBe(''); }); it('colored cell should have style', () => { - var html = renderer.renderCell(2, 0, 40); + const html = renderer.renderCell(2, 0, 40); expect(html).toBe(''); }); it('colored cell should have style', () => { - var html = renderer.renderCell(2, 0, 55); + const html = renderer.renderCell(2, 0, 55); expect(html).toBe(''); }); it('colored cell should have style', () => { - var html = renderer.renderCell(2, 0, 85); + const html = renderer.renderCell(2, 0, 85); expect(html).toBe(''); }); it('unformated undefined should be rendered as string', () => { - var html = renderer.renderCell(3, 0, 'value'); + const html = renderer.renderCell(3, 0, 'value'); expect(html).toBe(''); }); it('string style with escape html should return escaped html', () => { - var html = renderer.renderCell(4, 0, '&breaking
    the
    row'); + const html = renderer.renderCell(4, 0, '&breaking
    the
    row'); expect(html).toBe('
    '); }); it('undefined formater should return escaped html', () => { - var html = renderer.renderCell(3, 0, '&breaking
    the
    row'); + const html = renderer.renderCell(3, 0, '&breaking
    the
    row'); expect(html).toBe('
    '); }); it('undefined value should render as -', () => { - var html = renderer.renderCell(3, 0, undefined); + const html = renderer.renderCell(3, 0, undefined); expect(html).toBe(''); }); it('sanitized value should render as', () => { - var html = renderer.renderCell(6, 0, 'text link'); + const html = renderer.renderCell(6, 0, 'text link'); expect(html).toBe(''); }); @@ -264,8 +264,8 @@ describe('when rendering table', () => { }); it('link should render as', () => { - var html = renderer.renderCell(7, 0, 'host1'); - var expectedHtml = ` + const html = renderer.renderCell(7, 0, 'host1'); + const expectedHtml = ` '); }); it('numeric value should be mapped to text', () => { - var html = renderer.renderCell(9, 0, 1); + const html = renderer.renderCell(9, 0, 1); expect(html).toBe(''); }); it('string numeric value should be mapped to text', () => { - var html = renderer.renderCell(9, 0, '0'); + const html = renderer.renderCell(9, 0, '0'); expect(html).toBe(''); }); it('string value should be mapped to text', () => { - var html = renderer.renderCell(9, 0, 'HELLO WORLD'); + const html = renderer.renderCell(9, 0, 'HELLO WORLD'); expect(html).toBe(''); }); it('array column value should be mapped to text', () => { - var html = renderer.renderCell(9, 0, ['value1', 'value2']); + const html = renderer.renderCell(9, 0, ['value1', 'value2']); expect(html).toBe(''); }); it('value should be mapped to text (range)', () => { - var html = renderer.renderCell(10, 0, 2); + const html = renderer.renderCell(10, 0, 2); expect(html).toBe(''); }); it('value should be mapped to text (range)', () => { - var html = renderer.renderCell(10, 0, 5); + const html = renderer.renderCell(10, 0, 5); expect(html).toBe(''); }); it('array column value should not be mapped to text', () => { - var html = renderer.renderCell(10, 0, ['value1', 'value2']); + const html = renderer.renderCell(10, 0, ['value1', 'value2']); expect(html).toBe(''); }); it('value should be mapped to text and colored cell should have style', () => { - var html = renderer.renderCell(11, 0, 1); + const html = renderer.renderCell(11, 0, 1); expect(html).toBe(''); }); it('value should be mapped to text and colored cell should have style', () => { - var html = renderer.renderCell(11, 0, '1'); + const html = renderer.renderCell(11, 0, '1'); expect(html).toBe(''); }); it('value should be mapped to text and colored cell should have style', () => { - var html = renderer.renderCell(11, 0, 0); + const html = renderer.renderCell(11, 0, 0); expect(html).toBe(''); }); it('value should be mapped to text and colored cell should have style', () => { - var html = renderer.renderCell(11, 0, '0'); + const html = renderer.renderCell(11, 0, '0'); expect(html).toBe(''); }); it('value should be mapped to text and colored cell should have style', () => { - var html = renderer.renderCell(11, 0, '2.1'); + const html = renderer.renderCell(11, 0, '2.1'); expect(html).toBe(''); }); it('value should be mapped to text (range) and colored cell should have style', () => { - var html = renderer.renderCell(12, 0, 0); + const html = renderer.renderCell(12, 0, 0); expect(html).toBe(''); }); it('value should be mapped to text (range) and colored cell should have style', () => { - var html = renderer.renderCell(12, 0, 1); + const html = renderer.renderCell(12, 0, 1); expect(html).toBe(''); }); it('value should be mapped to text (range) and colored cell should have style', () => { - var html = renderer.renderCell(12, 0, 4); + const html = renderer.renderCell(12, 0, 4); expect(html).toBe(''); }); it('value should be mapped to text (range) and colored cell should have style', () => { - var html = renderer.renderCell(12, 0, '7.1'); + const html = renderer.renderCell(12, 0, '7.1'); expect(html).toBe(''); }); }); diff --git a/public/app/plugins/panel/table/specs/transformers.test.ts b/public/app/plugins/panel/table/specs/transformers.test.ts index eefe3f9bdc0..2425d98f26d 100644 --- a/public/app/plugins/panel/table/specs/transformers.test.ts +++ b/public/app/plugins/panel/table/specs/transformers.test.ts @@ -1,11 +1,11 @@ import { transformers, transformDataToTable } from '../transformers'; describe('when transforming time series table', () => { - var table; + let table; describe('given 2 time series', () => { - var time = new Date().getTime(); - var timeSeries = [ + const time = new Date().getTime(); + const timeSeries = [ { target: 'series1', datapoints: [[12.12, time], [14.44, time + 1]], @@ -17,7 +17,7 @@ describe('when transforming time series table', () => { ]; describe('timeseries_to_rows', () => { - var panel = { + const panel = { transform: 'timeseries_to_rows', sort: { col: 0, desc: true }, }; @@ -43,7 +43,7 @@ describe('when transforming time series table', () => { }); describe('timeseries_to_columns', () => { - var panel = { + const panel = { transform: 'timeseries_to_columns', }; @@ -70,7 +70,7 @@ describe('when transforming time series table', () => { }); describe('timeseries_aggregations', () => { - var panel = { + const panel = { transform: 'timeseries_aggregations', sort: { col: 0, desc: true }, columns: [{ text: 'Max', value: 'max' }, { text: 'Min', value: 'min' }], @@ -99,12 +99,12 @@ describe('when transforming time series table', () => { describe('table data sets', () => { describe('Table', () => { const transform = 'table'; - var panel = { + const panel = { transform, }; - var time = new Date().getTime(); + const time = new Date().getTime(); - var nonTableData = [ + const nonTableData = [ { type: 'foo', columns: [{ text: 'Time' }, { text: 'Label Key 1' }, { text: 'Value' }], @@ -112,7 +112,7 @@ describe('when transforming time series table', () => { }, ]; - var singleQueryData = [ + const singleQueryData = [ { type: 'table', columns: [{ text: 'Time' }, { text: 'Label Key 1' }, { text: 'Value' }], @@ -120,7 +120,7 @@ describe('when transforming time series table', () => { }, ]; - var multipleQueriesDataSameLabels = [ + const multipleQueriesDataSameLabels = [ { type: 'table', columns: [{ text: 'Time' }, { text: 'Label Key 1' }, { text: 'Label Key 2' }, { text: 'Value #A' }], @@ -143,7 +143,7 @@ describe('when transforming time series table', () => { }, ]; - var multipleQueriesDataDifferentLabels = [ + const multipleQueriesDataDifferentLabels = [ { type: 'table', columns: [{ text: 'Time' }, { text: 'Label Key 1' }, { text: 'Value #A' }], @@ -163,14 +163,14 @@ describe('when transforming time series table', () => { describe('getColumns', function() { it('should return data columns given a single query', function() { - var columns = transformers[transform].getColumns(singleQueryData); + const columns = transformers[transform].getColumns(singleQueryData); expect(columns[0].text).toBe('Time'); expect(columns[1].text).toBe('Label Key 1'); expect(columns[2].text).toBe('Value'); }); it('should return the union of data columns given a multiple queries', function() { - var columns = transformers[transform].getColumns(multipleQueriesDataSameLabels); + const columns = transformers[transform].getColumns(multipleQueriesDataSameLabels); expect(columns[0].text).toBe('Time'); expect(columns[1].text).toBe('Label Key 1'); expect(columns[2].text).toBe('Label Key 2'); @@ -179,7 +179,7 @@ describe('when transforming time series table', () => { }); it('should return the union of data columns given a multiple queries with different labels', function() { - var columns = transformers[transform].getColumns(multipleQueriesDataDifferentLabels); + const columns = transformers[transform].getColumns(multipleQueriesDataDifferentLabels); expect(columns[0].text).toBe('Time'); expect(columns[1].text).toBe('Label Key 1'); expect(columns[2].text).toBe('Value #A'); @@ -263,7 +263,7 @@ describe('when transforming time series table', () => { describe('doc data sets', () => { describe('JSON Data', () => { - var panel = { + const panel = { transform: 'json', columns: [ { text: 'Timestamp', value: 'timestamp' }, @@ -271,7 +271,7 @@ describe('when transforming time series table', () => { { text: 'nested.level2', value: 'nested.level2' }, ], }; - var rawData = [ + const rawData = [ { type: 'docs', datapoints: [ @@ -288,7 +288,7 @@ describe('when transforming time series table', () => { describe('getColumns', function() { it('should return nested properties', function() { - var columns = transformers['json'].getColumns(rawData); + const columns = transformers['json'].getColumns(rawData); expect(columns[0].text).toBe('timestamp'); expect(columns[1].text).toBe('message'); expect(columns[2].text).toBe('nested.level2'); @@ -319,8 +319,8 @@ describe('when transforming time series table', () => { describe('annotation data', () => { describe('Annnotations', () => { - var panel = { transform: 'annotations' }; - var rawData = { + const panel = { transform: 'annotations' }; + const rawData = { annotations: [ { time: 1000, diff --git a/public/test/jest-setup.ts b/public/test/jest-setup.ts index 1608f890315..fed65097ac7 100644 --- a/public/test/jest-setup.ts +++ b/public/test/jest-setup.ts @@ -18,5 +18,5 @@ jest.mock('app/features/plugins/plugin_loader', () => ({})); configure({ adapter: new Adapter() }); -var global = window; +const global = window; global.$ = global.jQuery = $; diff --git a/public/test/specs/helpers.ts b/public/test/specs/helpers.ts index 677419f3f75..960ce84f494 100644 --- a/public/test/specs/helpers.ts +++ b/public/test/specs/helpers.ts @@ -5,7 +5,7 @@ import { angularMocks, sinon } from '../lib/common'; import { PanelModel } from 'app/features/dashboard/panel_model'; export function ControllerTestContext() { - var self = this; + const self = this; this.datasource = {}; this.$element = {}; @@ -58,7 +58,7 @@ export function ControllerTestContext() { $rootScope.onAppEvent = sinon.spy(); $rootScope.colors = []; - for (var i = 0; i < 50; i++) { + for (let i = 0; i < 50; i++) { $rootScope.colors.push('#' + i); } @@ -88,7 +88,7 @@ export function ControllerTestContext() { self.scope.onAppEvent = sinon.spy(); $rootScope.colors = []; - for (var i = 0; i < 50; i++) { + for (let i = 0; i < 50; i++) { $rootScope.colors.push('#' + i); } @@ -107,7 +107,7 @@ export function ControllerTestContext() { } export function ServiceTestContext() { - var self = this; + const self = this; self.templateSrv = new TemplateSrvStub(); self.timeSrv = new TimeSrvStub(); self.datasourceSrv = {}; @@ -195,7 +195,7 @@ export function TemplateSrvStub() { }; } -var allDeps = { +const allDeps = { ContextSrvStub, TemplateSrvStub, TimeSrvStub, From 35c00891e722cc68dfb9cefe8537d5229661754c Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Torkel=20=C3=96degaard?= Date: Sun, 26 Aug 2018 20:19:23 +0200 Subject: [PATCH 09/10] tslint: more const fixes (#13035) --- public/app/core/config.ts | 6 ++-- .../features/admin/admin_edit_user_ctrl.ts | 6 ++-- .../alerting/notification_edit_ctrl.ts | 2 +- .../annotations/specs/annotations_srv.test.ts | 6 +--- .../app/features/dashboard/ad_hoc_filters.ts | 12 +++---- .../app/features/dashboard/change_tracker.ts | 18 +++++----- .../dashboard/dashboard_import_ctrl.ts | 12 +++---- .../dashboard/dashgrid/AddPanelPanel.tsx | 2 +- .../features/dashboard/export/export_modal.ts | 4 +-- .../app/features/dashboard/export/exporter.ts | 22 ++++++------ .../dashboard/repeat_option/repeat_option.ts | 2 +- .../features/dashboard/settings/settings.ts | 2 +- .../dashboard/specs/change_tracker.test.ts | 2 +- .../specs/dashboard_import_ctrl.test.ts | 2 +- .../specs/dashboard_migration.test.ts | 11 +++--- public/app/features/dashboard/time_srv.ts | 34 +++++++++---------- .../dashboard/timepicker/input_date.ts | 6 ++-- .../dashboard/timepicker/timepicker.ts | 10 +++--- public/app/features/dashboard/upload.ts | 10 +++--- public/app/features/org/org_api_keys_ctrl.ts | 2 +- public/app/features/org/org_details_ctrl.ts | 2 +- public/app/features/org/prefs_control.ts | 4 +-- public/app/features/panel/panel_directive.ts | 26 +++++++------- public/app/features/panel/panel_editor_tab.ts | 8 ++--- public/app/features/panel/panel_header.ts | 2 +- public/app/features/panel/query_editor_row.ts | 6 ++-- .../features/panel/query_troubleshooter.ts | 2 +- public/app/features/panel/solo_panel_ctrl.ts | 4 +-- .../features/playlist/playlist_edit_ctrl.ts | 8 ++--- .../app/features/playlist/playlist_search.ts | 4 +-- public/app/features/playlist/playlist_srv.ts | 4 +-- public/app/features/styleguide/styleguide.ts | 2 +- 32 files changed, 120 insertions(+), 123 deletions(-) diff --git a/public/app/core/config.ts b/public/app/core/config.ts index e065ddb22fb..f522c6340e6 100644 --- a/public/app/core/config.ts +++ b/public/app/core/config.ts @@ -31,7 +31,7 @@ export class Settings { loginError: any; constructor(options) { - var defaults = { + const defaults = { datasources: {}, window_title_prefix: 'Grafana - ', panels: {}, @@ -51,8 +51,8 @@ export class Settings { } } -var bootData = (window).grafanaBootData || { settings: {} }; -var options = bootData.settings; +const bootData = (window).grafanaBootData || { settings: {} }; +const options = bootData.settings; options.bootData = bootData; const config = new Settings(options); diff --git a/public/app/features/admin/admin_edit_user_ctrl.ts b/public/app/features/admin/admin_edit_user_ctrl.ts index 1d4fb9cf19a..b84b690d44a 100644 --- a/public/app/features/admin/admin_edit_user_ctrl.ts +++ b/public/app/features/admin/admin_edit_user_ctrl.ts @@ -29,14 +29,14 @@ export class AdminEditUserCtrl { return; } - var payload = { password: $scope.password }; + const payload = { password: $scope.password }; backendSrv.put('/api/admin/users/' + $scope.user_id + '/password', payload).then(function() { $location.path('/admin/users'); }); }; $scope.updatePermissions = function() { - var payload = $scope.permissions; + const payload = $scope.permissions; backendSrv.put('/api/admin/users/' + $scope.user_id + '/permissions', payload).then(function() { $location.path('/admin/users'); @@ -99,7 +99,7 @@ export class AdminEditUserCtrl { return; } - var orgInfo = _.find($scope.orgsSearchCache, { + const orgInfo = _.find($scope.orgsSearchCache, { name: $scope.newOrg.name, }); if (!orgInfo) { diff --git a/public/app/features/alerting/notification_edit_ctrl.ts b/public/app/features/alerting/notification_edit_ctrl.ts index eb14766d1fb..60942e6ffb4 100644 --- a/public/app/features/alerting/notification_edit_ctrl.ts +++ b/public/app/features/alerting/notification_edit_ctrl.ts @@ -99,7 +99,7 @@ export class AlertNotificationEditCtrl { return; } - var payload = { + const payload = { name: this.model.name, type: this.model.type, settings: this.model.settings, diff --git a/public/app/features/annotations/specs/annotations_srv.test.ts b/public/app/features/annotations/specs/annotations_srv.test.ts index 97696767536..f262544da43 100644 --- a/public/app/features/annotations/specs/annotations_srv.test.ts +++ b/public/app/features/annotations/specs/annotations_srv.test.ts @@ -6,12 +6,8 @@ describe('AnnotationsSrv', function() { const $rootScope = { onAppEvent: jest.fn(), }; - let $q; - let datasourceSrv; - let backendSrv; - let timeSrv; - const annotationsSrv = new AnnotationsSrv($rootScope, $q, datasourceSrv, backendSrv, timeSrv); + const annotationsSrv = new AnnotationsSrv($rootScope, null, null, null, null); describe('When translating the query result', () => { const annotationSource = { diff --git a/public/app/features/dashboard/ad_hoc_filters.ts b/public/app/features/dashboard/ad_hoc_filters.ts index 412761dc716..68b068152b5 100644 --- a/public/app/features/dashboard/ad_hoc_filters.ts +++ b/public/app/features/dashboard/ad_hoc_filters.ts @@ -55,8 +55,8 @@ export class AdHocFiltersCtrl { } return this.datasourceSrv.get(this.variable.datasource).then(ds => { - var options: any = {}; - var promise = null; + const options: any = {}; + let promise = null; if (segment.type !== 'value') { promise = ds.getTagKeys(); @@ -113,9 +113,9 @@ export class AdHocFiltersCtrl { } updateVariableModel() { - var filters = []; - var filterIndex = -1; - var hasFakes = false; + const filters = []; + let filterIndex = -1; + let hasFakes = false; this.segments.forEach(segment => { if (segment.type === 'value' && segment.fake) { @@ -153,7 +153,7 @@ export class AdHocFiltersCtrl { } } -var template = ` +const template = `
    { + const self = this; + const cancel = this.$rootScope.$on('dashboard-saved', () => { cancel(); this.$timeout(() => { self.gotoNext(); @@ -179,8 +179,8 @@ export class ChangeTracker { } gotoNext() { - var baseLen = this.$location.absUrl().length - this.$location.url().length; - var nextUrl = this.next.substring(baseLen); + const baseLen = this.$location.absUrl().length - this.$location.url().length; + const nextUrl = this.next.substring(baseLen); this.$location.url(nextUrl); } } diff --git a/public/app/features/dashboard/dashboard_import_ctrl.ts b/public/app/features/dashboard/dashboard_import_ctrl.ts index b70a1847602..3dfae1250dd 100644 --- a/public/app/features/dashboard/dashboard_import_ctrl.ts +++ b/public/app/features/dashboard/dashboard_import_ctrl.ts @@ -52,7 +52,7 @@ export class DashboardImportCtrl { if (this.dash.__inputs) { for (const input of this.dash.__inputs) { - var inputModel = { + const inputModel = { name: input.name, label: input.label, info: input.description, @@ -78,7 +78,7 @@ export class DashboardImportCtrl { } setDatasourceOptions(input, inputModel) { - var sources = _.filter(config.datasources, val => { + const sources = _.filter(config.datasources, val => { return val.type === input.pluginId; }); @@ -162,7 +162,7 @@ export class DashboardImportCtrl { } saveDashboard() { - var inputs = this.inputs.map(input => { + const inputs = this.inputs.map(input => { return { name: input.name, type: input.type, @@ -186,7 +186,7 @@ export class DashboardImportCtrl { loadJsonText() { try { this.parseError = ''; - var dash = JSON.parse(this.jsonText); + const dash = JSON.parse(this.jsonText); this.onUpload(dash); } catch (err) { console.log(err); @@ -198,8 +198,8 @@ export class DashboardImportCtrl { checkGnetDashboard() { this.gnetError = ''; - var match = /(^\d+$)|dashboards\/(\d+)/.exec(this.gnetUrl); - var dashboardId; + const match = /(^\d+$)|dashboards\/(\d+)/.exec(this.gnetUrl); + let dashboardId; if (match && match[1]) { dashboardId = match[1]; diff --git a/public/app/features/dashboard/dashgrid/AddPanelPanel.tsx b/public/app/features/dashboard/dashgrid/AddPanelPanel.tsx index 9459fc41753..a26a0401d56 100644 --- a/public/app/features/dashboard/dashgrid/AddPanelPanel.tsx +++ b/public/app/features/dashboard/dashgrid/AddPanelPanel.tsx @@ -97,7 +97,7 @@ export class AddPanelPanel extends React.Component { + const templateizeDatasourceUsage = obj => { // ignore data source properties that contain a variable if (obj.datasource && obj.datasource.indexOf('$') === 0) { if (variableLookup[obj.datasource.substring(1)]) { @@ -42,7 +42,7 @@ export class DashboardExporter { return; } - var refName = 'DS_' + ds.name.replace(' ', '_').toUpperCase(); + const refName = 'DS_' + ds.name.replace(' ', '_').toUpperCase(); datasources[refName] = { name: refName, label: ds.name, @@ -76,7 +76,7 @@ export class DashboardExporter { } } - var panelDef = config.panels[panel.type]; + const panelDef = config.panels[panel.type]; if (panelDef) { requires['panel' + panelDef.id] = { type: 'panel', @@ -131,7 +131,7 @@ export class DashboardExporter { // templatize constants for (const variable of saveModel.templating.list) { if (variable.type === 'constant') { - var refName = 'VAR_' + variable.name.replace(' ', '_').toUpperCase(); + const refName = 'VAR_' + variable.name.replace(' ', '_').toUpperCase(); inputs.push({ name: refName, type: 'constant', @@ -149,7 +149,7 @@ export class DashboardExporter { } // make inputs and requires a top thing - var newObj = {}; + const newObj = {}; newObj['__inputs'] = inputs; newObj['__requires'] = _.sortBy(requires, ['id']); diff --git a/public/app/features/dashboard/repeat_option/repeat_option.ts b/public/app/features/dashboard/repeat_option/repeat_option.ts index 696c634ddae..01e1d716fc5 100644 --- a/public/app/features/dashboard/repeat_option/repeat_option.ts +++ b/public/app/features/dashboard/repeat_option/repeat_option.ts @@ -1,6 +1,6 @@ import { coreModule } from 'app/core/core'; -var template = ` +const template = `
    2014-01-01T06:06:06Z--1.23 kbps1.230 sasd40.055.085.0value&breaking <br /> the <br /> row&breaking <br /> the <br /> rowsanitizedvalue1, value2onoffHELLO GRAFANAvalue3, value4onoffvalue1, value2ononoffoff2.10onoff7.1