diff --git a/CHANGELOG.md b/CHANGELOG.md index 651b4dd22f6..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) @@ -54,6 +56,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 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 } 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/app.ts b/public/app/app.ts index 9ac76b8ec91..d9e31018af9 100644 --- a/public/app/app.ts +++ b/public/app/app.ts @@ -53,7 +53,7 @@ export class GrafanaApp { } init() { - var app = angular.module('grafana', []); + const app = angular.module('grafana', []); moment.locale(config.bootData.user.locale); @@ -77,7 +77,7 @@ export class GrafanaApp { '$delegate', '$templateCache', function($delegate, $templateCache) { - var get = $delegate.get; + const get = $delegate.get; $delegate.get = function(url, config) { if (url.match(/\.html$/)) { // some template's already exist in the cache @@ -105,10 +105,10 @@ export class GrafanaApp { 'react', ]; - var module_types = ['controllers', 'directives', 'factories', 'services', 'filters', 'routes']; + const module_types = ['controllers', 'directives', 'factories', 'services', 'filters', 'routes']; _.each(module_types, type => { - var moduleName = 'grafana.' + type; + const moduleName = 'grafana.' + type; this.useModule(angular.module(moduleName, [])); }); @@ -119,7 +119,7 @@ export class GrafanaApp { coreModule.config(setupAngularRoutes); registerAngularDirectives(); - var preBootRequires = [System.import('app/features/all')]; + const preBootRequires = [System.import('app/features/all')]; Promise.all(preBootRequires) .then(() => { 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 b61c7fbaac3..668136dee6f 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; } @@ -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/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..92712709858 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, @@ -346,19 +346,24 @@ export class Explore extends React.Component { onQuerySuccess(datasourceId: string, queries: any[]): void { // save queries to history - let { datasource, history } = this.state; + let { history } = this.state; + const { datasource } = this.state; + if (datasource.meta.id !== datasourceId) { // Navigated away, queries did not matter return; } + const ts = Date.now(); queries.forEach(q => { const { query } = q; history = [{ query, ts }, ...history]; }); + if (history.length > MAX_HISTORY_ITEMS) { history = history.slice(0, MAX_HISTORY_ITEMS); } + // Combine all queries of a datasource type into one history const historyKey = `grafana.explore.history.${datasourceId}`; store.setObject(historyKey, history); diff --git a/public/app/containers/Explore/Graph.tsx b/public/app/containers/Explore/Graph.tsx index 171be9da6ba..9243f612466 100644 --- a/public/app/containers/Explore/Graph.tsx +++ b/public/app/containers/Explore/Graph.tsx @@ -12,10 +12,10 @@ import Legend from './Legend'; // Copied from graph.ts function time_format(ticks, min, max) { if (min && max && ticks) { - var range = max - min; - var secPerTick = range / ticks / 1000; - var oneDay = 86400000; - var oneYear = 31536000000; + const range = max - min; + const secPerTick = range / ticks / 1000; + const oneDay = 86400000; + const oneYear = 31536000000; if (secPerTick <= 45) { return '%H:%M:%S'; 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/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 ( @@ -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..d0feee75184 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,8 +35,8 @@ export class TeamList extends React.Component { this.props.teams.setSearchQuery(evt.target.value); }; - renderTeamMember(team: ITeam): JSX.Element { - let teamUrl = `org/teams/edit/${team.id}`; + renderTeamMember(team: Team): JSX.Element { + const 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 ( '); }); 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/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/routes/dashboard_loaders.ts b/public/app/routes/dashboard_loaders.ts index b33d5b6afb1..d8a66185d96 100644 --- a/public/app/routes/dashboard_loaders.ts +++ b/public/app/routes/dashboard_loaders.ts @@ -11,7 +11,7 @@ export class LoadDashboardCtrl { if (homeDash.redirectUri) { $location.path(homeDash.redirectUri); } else { - var meta = homeDash.meta; + const meta = homeDash.meta; meta.canSave = meta.canShare = meta.canStar = false; $scope.initDashboard(homeDash, $scope); } diff --git a/public/app/stores/AlertListStore/AlertListStore.ts b/public/app/stores/AlertListStore/AlertListStore.ts index 7d60ce04180..c2b9f5e4962 100644 --- a/public/app/stores/AlertListStore/AlertListStore.ts +++ b/public/app/stores/AlertListStore/AlertListStore.ts @@ -1,19 +1,19 @@ 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, ''), }) .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') { @@ -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..d869b0f740d 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', { @@ -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, @@ -117,8 +117,8 @@ export const NavStore = types self.main = NavItem.create(main); }, - initTeamPage(team: ITeam, tab: string, isSyncEnabled: boolean) { - let main = { + initTeamPage(team: Team, tab: string, isSyncEnabled: boolean) { + 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/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..f8e101163a2 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,13 +27,13 @@ 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() { - 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,12 +66,12 @@ export const Team = types const rsp = yield backendSrv.get(`/api/teams/${self.id}/members`); self.members.clear(); - for (let member of rsp) { - self.members.set(member.userId.toString(), TeamMember.create(member)); + for (const member of rsp) { + 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 @@ -88,8 +88,8 @@ export const Team = types const rsp = yield backendSrv.get(`/api/teams/${self.id}/groups`); self.groups.clear(); - for (let group of rsp) { - self.groups.set(group.groupId, TeamGroup.create(group)); + for (const group of rsp) { + 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,18 +112,18 @@ 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 => ({ 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,8 +135,8 @@ 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) { - self.map.set(team.id.toString(), Team.create(team)); + for (const team of rsp.teams) { + 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/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/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/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/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/lib/common.ts b/public/test/lib/common.ts index c6b74fc7ecb..ac05f83391c 100644 --- a/public/test/lib/common.ts +++ b/public/test/lib/common.ts @@ -1,24 +1,15 @@ -var _global = (window); -var beforeEach = _global.beforeEach; -var afterEach = _global.afterEach; -var before = _global.before; -var describe = _global.describe; -var it = _global.it; -var sinon = _global.sinon; -var expect = _global.expect; +const _global = window; +const beforeEach = _global.beforeEach; +const afterEach = _global.afterEach; +const before = _global.before; +const describe = _global.describe; +const it = _global.it; +const sinon = _global.sinon; +const expect = _global.expect; -var angularMocks = { +const angularMocks = { module: _global.module, inject: _global.inject, }; -export { - beforeEach, - afterEach, - before, - describe, - it, - sinon, - expect, - angularMocks, -}; +export { beforeEach, afterEach, before, describe, it, sinon, expect, angularMocks }; 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; } 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, 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"
    {group.groupId}
    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..b7bef2495bb 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; } @@ -15,8 +15,8 @@ const SelectNav = ({ main, customCss }: { main: NavModelItem; customCss: string }); const gotoUrl = evt => { - var element = evt.target; - var url = element.options[element.selectedIndex].value; + const element = evt.target; + const url = element.options[element.selectedIndex].value; appEvents.emit('location-change', { href: url }); }; @@ -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/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/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..a879f544da0 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) { @@ -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/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/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/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..6e5083b6d6b 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; @@ -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 360c3fdd5c4..c42bcfa1d06 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, }; } @@ -28,11 +28,11 @@ export class ColorPickerPopover extends React.Component { } setColor(color) { - let newColor = tinycolor(color); + const newColor = tinycolor(color); if (newColor.isValid()) { this.setState({ color: newColor.toString(), - colorString: newColor.toString() + colorString: newColor.toString(), }); this.props.onColorSelect(color); } @@ -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 + 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,17 +65,17 @@ export class ColorPickerPopover extends React.Component { } onColorStringBlur(e) { - let colorString = e.target.value; + const colorString = e.target.value; this.setColor(colorString); } 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); + const 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..15a76068e9b 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); + const 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/core/components/form_dropdown/form_dropdown.ts b/public/app/core/components/form_dropdown/form_dropdown.ts index 7ac55e54cf1..4604e1d7838 100644 --- a/public/app/core/components/form_dropdown/form_dropdown.ts +++ b/public/app/core/components/form_dropdown/form_dropdown.ts @@ -67,7 +67,7 @@ export class FormDropdownCtrl { // modify typeahead lookup // this = typeahead - var typeahead = this.inputElement.data('typeahead'); + const typeahead = this.inputElement.data('typeahead'); typeahead.lookup = function() { this.query = this.$element.val() || ''; this.source(this.query, this.process.bind(this)); @@ -100,7 +100,7 @@ export class FormDropdownCtrl { } getOptionsInternal(query) { - var result = this.getOptions({ $query: query }); + const result = this.getOptions({ $query: query }); if (this.isPromiseLike(result)) { return result; } @@ -118,7 +118,7 @@ export class FormDropdownCtrl { // if we have text use it if (this.lookupText) { this.getOptionsInternal('').then(options => { - var item = _.find(options, { value: this.model }); + const item = _.find(options, { value: this.model }); this.updateDisplay(item ? item.text : this.model); }); } else { @@ -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); }); @@ -186,7 +186,7 @@ export class FormDropdownCtrl { } this.$scope.$apply(() => { - var option = _.find(this.optionCache, { text: text }); + const option = _.find(this.optionCache, { text: text }); if (option) { if (_.isObject(this.model)) { @@ -228,7 +228,7 @@ export class FormDropdownCtrl { this.linkElement.hide(); this.linkMode = false; - var typeahead = this.inputElement.data('typeahead'); + const typeahead = this.inputElement.data('typeahead'); if (typeahead) { this.inputElement.val(''); typeahead.lookup(); 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..0016305e617 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 }); @@ -238,7 +238,7 @@ export class ManageDashboardsCtrl { } onTagFilterChange() { - var res = this.filterByTag(this.selectedTagFilter.term); + const res = this.filterByTag(this.selectedTagFilter.term); this.selectedTagFilter = this.tagFilterOptions[0]; return res; } @@ -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/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/core/controllers/inspect_ctrl.ts b/public/app/core/controllers/inspect_ctrl.ts index 5dd4cb3d06f..612b9cac42e 100644 --- a/public/app/core/controllers/inspect_ctrl.ts +++ b/public/app/core/controllers/inspect_ctrl.ts @@ -6,7 +6,7 @@ import coreModule from '../core_module'; export class InspectCtrl { /** @ngInject */ constructor($scope, $sanitize) { - var model = $scope.inspector; + const model = $scope.inspector; $scope.init = function() { $scope.editor = { index: 0 }; @@ -53,10 +53,10 @@ export class InspectCtrl { }; } getParametersFromQueryString(queryString) { - var result = []; - var parameters = queryString.split('&'); - for (var i = 0; i < parameters.length; i++) { - var keyValue = parameters[i].split('='); + const result = []; + const parameters = queryString.split('&'); + for (let i = 0; i < parameters.length; i++) { + const keyValue = parameters[i].split('='); if (keyValue[1].length > 0) { result.push({ key: keyValue[0], diff --git a/public/app/core/controllers/json_editor_ctrl.ts b/public/app/core/controllers/json_editor_ctrl.ts index d369fe8b3c0..3260f6ff537 100644 --- a/public/app/core/controllers/json_editor_ctrl.ts +++ b/public/app/core/controllers/json_editor_ctrl.ts @@ -9,7 +9,7 @@ export class JsonEditorCtrl { $scope.canCopy = $scope.enableCopy; $scope.update = function() { - var newObject = angular.fromJson($scope.json); + const newObject = angular.fromJson($scope.json); $scope.updateHandler(newObject, $scope.object); }; diff --git a/public/app/core/controllers/login_ctrl.ts b/public/app/core/controllers/login_ctrl.ts index 0a66f83d08a..daf562c65da 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(() => { @@ -118,7 +118,7 @@ export class LoginCtrl { }; $scope.toGrafana = function() { - var params = $location.search(); + const params = $location.search(); if (params.redirect && params.redirect[0] === '/') { window.location.href = config.appSubUrl + params.redirect; diff --git a/public/app/core/controllers/reset_password_ctrl.ts b/public/app/core/controllers/reset_password_ctrl.ts index 360c5bf8071..244f0307150 100644 --- a/public/app/core/controllers/reset_password_ctrl.ts +++ b/public/app/core/controllers/reset_password_ctrl.ts @@ -7,7 +7,7 @@ export class ResetPasswordCtrl { $scope.formModel = {}; $scope.mode = 'send'; - var params = $location.search(); + const params = $location.search(); if (params.code) { $scope.mode = 'reset'; $scope.formModel.code = params.code; diff --git a/public/app/core/controllers/signup_ctrl.ts b/public/app/core/controllers/signup_ctrl.ts index ad23e0f7f22..5a85e1605b7 100644 --- a/public/app/core/controllers/signup_ctrl.ts +++ b/public/app/core/controllers/signup_ctrl.ts @@ -9,7 +9,7 @@ export class SignUpCtrl { $scope.formModel = {}; - var params = $location.search(); + const params = $location.search(); // validate email is semi ok if (params.email && !params.email.match(/^\S+@\S+$/)) { 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/filters/filters.ts b/public/app/core/filters/filters.ts index c6aea32d38d..098bda58de9 100644 --- a/public/app/core/filters/filters.ts +++ b/public/app/core/filters/filters.ts @@ -38,7 +38,7 @@ coreModule.filter('moment', function() { }); coreModule.filter('noXml', function() { - var noXml = function(text) { + const noXml = function(text) { return _.isString(text) ? text .replace(/&/g, '&') @@ -55,7 +55,7 @@ coreModule.filter('noXml', function() { /** @ngInject */ function interpolateTemplateVars(templateSrv) { - var filterFunc: any = function(text, scope) { + const filterFunc: any = function(text, scope) { var scopedVars; if (scope.ctrl) { scopedVars = (scope.ctrl.panel || scope.ctrl.row).scopedVars; 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/alert_srv.ts b/public/app/core/services/alert_srv.ts index fc76ef9e371..19ad81667d7 100644 --- a/public/app/core/services/alert_srv.ts +++ b/public/app/core/services/alert_srv.ts @@ -60,14 +60,14 @@ export class AlertSrv { } } - var newAlert = { + const newAlert = { title: title || '', text: text || '', severity: severity || 'info', icon: this.getIconForSeverity(severity), }; - var newAlertJson = angular.toJson(newAlert); + const newAlertJson = angular.toJson(newAlert); // remove same alert if it already exists _.remove(this.list, function(value) { diff --git a/public/app/core/services/analytics.ts b/public/app/core/services/analytics.ts index d1998f44cbc..c3936f45451 100644 --- a/public/app/core/services/analytics.ts +++ b/public/app/core/services/analytics.ts @@ -12,7 +12,7 @@ export class Analytics { dataType: 'script', cache: true, }); - var ga = ((window).ga = + const ga = ((window).ga = (window).ga || function() { (ga.q = ga.q || []).push(arguments); @@ -25,8 +25,8 @@ export class Analytics { init() { this.$rootScope.$on('$viewContentLoaded', () => { - var track = { page: this.$location.url() }; - var ga = (window).ga || this.gaInit(); + const track = { page: this.$location.url() }; + const ga = (window).ga || this.gaInit(); ga('set', track); ga('send', 'pageview'); }); 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..ccd86856755 100644 --- a/public/app/core/services/dynamic_directive_srv.ts +++ b/public/app/core/services/dynamic_directive_srv.ts @@ -6,7 +6,7 @@ class DynamicDirectiveSrv { constructor(private $compile, private $rootScope) {} addDirective(element, name, scope) { - var child = angular.element(document.createElement(name)); + const child = angular.element(document.createElement(name)); this.$compile(child)(scope); element.empty(); @@ -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..cad538d13aa 100644 --- a/public/app/core/services/keybindingSrv.ts +++ b/public/app/core/services/keybindingSrv.ts @@ -70,7 +70,7 @@ export class KeybindingSrv { } exit() { - var popups = $('.popover.in'); + const popups = $('.popover.in'); if (popups.length > 0) { return; } @@ -89,7 +89,7 @@ export class KeybindingSrv { } // close settings view - var search = this.$location.search(); + const search = this.$location.search(); if (search.editview) { delete search.editview; this.$location.search(search); @@ -123,7 +123,7 @@ export class KeybindingSrv { } showDashEditView() { - var search = _.extend(this.$location.search(), { editview: 'settings' }); + const search = _.extend(this.$location.search(), { editview: 'settings' }); this.$location.search(search); } @@ -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]); } }); @@ -218,8 +218,8 @@ export class KeybindingSrv { // share panel this.bind('p s', () => { if (dashboard.meta.focusPanelId) { - var shareScope = scope.$new(); - var panelInfo = dashboard.getPanelInfoById(dashboard.meta.focusPanelId); + const shareScope = scope.$new(); + const panelInfo = dashboard.getPanelInfoById(dashboard.meta.focusPanelId); shareScope.panel = panelInfo.panel; shareScope.dashboard = dashboard; 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/popover_srv.ts b/public/app/core/services/popover_srv.ts index 113e1e5fae7..33568cda8d3 100644 --- a/public/app/core/services/popover_srv.ts +++ b/public/app/core/services/popover_srv.ts @@ -18,10 +18,10 @@ function popoverSrv($compile, $rootScope, $timeout) { openDrop = null; } - var scope = _.extend($rootScope.$new(true), options.model); - var drop; + const scope = _.extend($rootScope.$new(true), options.model); + let drop; - var cleanUp = () => { + const cleanUp = () => { setTimeout(() => { scope.$destroy(); @@ -41,7 +41,7 @@ function popoverSrv($compile, $rootScope, $timeout) { drop.close(); }; - var contentElement = document.createElement('div'); + const contentElement = document.createElement('div'); contentElement.innerHTML = options.template; $compile(contentElement)(scope); 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/services/util_srv.ts b/public/app/core/services/util_srv.ts index 1afae0a02f4..da598fbb127 100644 --- a/public/app/core/services/util_srv.ts +++ b/public/app/core/services/util_srv.ts @@ -33,7 +33,7 @@ export class UtilSrv { this.modalScope = this.$rootScope.$new(); } - var modal = this.$modal({ + const modal = this.$modal({ modalClass: options.modalClass, template: options.src, templateHtml: options.templateHtml, @@ -50,7 +50,7 @@ export class UtilSrv { } showConfirmModal(payload) { - var scope = this.$rootScope.$new(); + const scope = this.$rootScope.$new(); scope.onConfirm = function() { payload.onConfirm(); 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/datemath.test.ts b/public/app/core/specs/datemath.test.ts index 820c53486db..cca6eb31593 100644 --- a/public/app/core/specs/datemath.test.ts +++ b/public/app/core/specs/datemath.test.ts @@ -5,11 +5,11 @@ import moment from 'moment'; import _ from 'lodash'; describe('DateMath', () => { - var spans = ['s', 'm', 'h', 'd', 'w', 'M', 'y']; - var anchor = '2014-01-01T06:06:06.666Z'; - var unix = moment(anchor).valueOf(); - var format = 'YYYY-MM-DDTHH:mm:ss.SSSZ'; - var clock; + const spans = ['s', 'm', 'h', 'd', 'w', 'M', 'y']; + const anchor = '2014-01-01T06:06:06.666Z'; + const unix = moment(anchor).valueOf(); + const format = 'YYYY-MM-DDTHH:mm:ss.SSSZ'; + let clock; describe('errors', () => { it('should return undefined if passed something falsy', () => { @@ -36,21 +36,21 @@ describe('DateMath', () => { }); it('now/d should set to start of current day', () => { - var expected = new Date(); + const expected = new Date(); expected.setHours(0); expected.setMinutes(0); expected.setSeconds(0); expected.setMilliseconds(0); - var startOfDay = dateMath.parse('now/d', false).valueOf(); + const startOfDay = dateMath.parse('now/d', false).valueOf(); expect(startOfDay).toBe(expected.getTime()); }); it('now/d on a utc dashboard should be start of the current day in UTC time', () => { - var today = new Date(); - var expected = new Date(Date.UTC(today.getUTCFullYear(), today.getUTCMonth(), today.getUTCDate(), 0, 0, 0, 0)); + const today = new Date(); + const expected = new Date(Date.UTC(today.getUTCFullYear(), today.getUTCMonth(), today.getUTCDate(), 0, 0, 0, 0)); - var startOfDay = dateMath.parse('now/d', false, 'utc').valueOf(); + const startOfDay = dateMath.parse('now/d', false, 'utc').valueOf(); expect(startOfDay).toBe(expected.getTime()); }); @@ -65,8 +65,8 @@ describe('DateMath', () => { }); _.each(spans, span => { - var nowEx = 'now-5' + span; - var thenEx = anchor + '||-5' + span; + const nowEx = 'now-5' + span; + const thenEx = anchor + '||-5' + span; it('should return 5' + span + ' ago', () => { expect(dateMath.parse(nowEx).format(format)).toEqual(now.subtract(5, span).format(format)); @@ -116,17 +116,17 @@ describe('DateMath', () => { describe('relative time to date parsing', function() { it('should handle negative time', function() { - var date = dateMath.parseDateMath('-2d', moment([2014, 1, 5])); + const date = dateMath.parseDateMath('-2d', moment([2014, 1, 5])); expect(date.valueOf()).toEqual(moment([2014, 1, 3]).valueOf()); }); it('should handle multiple math expressions', function() { - var date = dateMath.parseDateMath('-2d-6h', moment([2014, 1, 5])); + const date = dateMath.parseDateMath('-2d-6h', moment([2014, 1, 5])); expect(date.valueOf()).toEqual(moment([2014, 1, 2, 18]).valueOf()); }); it('should return false when invalid expression', function() { - var date = dateMath.parseDateMath('2', moment([2014, 1, 5])); + const date = dateMath.parseDateMath('2', moment([2014, 1, 5])); expect(date).toEqual(undefined); }); }); diff --git a/public/app/core/specs/emitter.test.ts b/public/app/core/specs/emitter.test.ts index a819cf0ede2..549dcb2d84a 100644 --- a/public/app/core/specs/emitter.test.ts +++ b/public/app/core/specs/emitter.test.ts @@ -3,9 +3,9 @@ import { Emitter } from '../utils/emitter'; describe('Emitter', () => { describe('given 2 subscribers', () => { it('should notfiy subscribers', () => { - var events = new Emitter(); - var sub1Called = false; - var sub2Called = false; + const events = new Emitter(); + let sub1Called = false; + let sub2Called = false; events.on('test', () => { sub1Called = true; @@ -21,8 +21,8 @@ describe('Emitter', () => { }); it('when subscribing twice', () => { - var events = new Emitter(); - var sub1Called = 0; + const events = new Emitter(); + let sub1Called = 0; function handler() { sub1Called += 1; @@ -37,9 +37,9 @@ describe('Emitter', () => { }); it('should handle errors', () => { - var events = new Emitter(); - var sub1Called = 0; - var sub2Called = 0; + const events = new Emitter(); + let sub1Called = 0; + let sub2Called = 0; events.on('test', () => { sub1Called++; 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/flatten.test.ts b/public/app/core/specs/flatten.test.ts index 7c7f4816d94..f1c5237802d 100644 --- a/public/app/core/specs/flatten.test.ts +++ b/public/app/core/specs/flatten.test.ts @@ -2,7 +2,7 @@ import flatten from 'app/core/utils/flatten'; describe('flatten', () => { it('should return flatten object', () => { - var flattened = flatten( + const flattened = flatten( { level1: 'level1-value', deeper: { diff --git a/public/app/core/specs/kbn.test.ts b/public/app/core/specs/kbn.test.ts index 9c62990615c..b4072adf7cf 100644 --- a/public/app/core/specs/kbn.test.ts +++ b/public/app/core/specs/kbn.test.ts @@ -3,7 +3,7 @@ import * as dateMath from '../utils/datemath'; import moment from 'moment'; describe('unit format menu', function() { - var menu = kbn.getUnitFormats(); + const menu = kbn.getUnitFormats(); menu.map(function(submenu) { describe('submenu ' + submenu.text, function() { it('should have a title', function() { @@ -34,8 +34,8 @@ describe('unit format menu', function() { function describeValueFormat(desc, value, tickSize, tickDecimals, result) { describe('value format: ' + desc, function() { it('should translate ' + value + ' as ' + result, function() { - var scaledDecimals = tickDecimals - Math.floor(Math.log(tickSize) / Math.LN10); - var str = kbn.valueFormats[desc](value, tickDecimals, scaledDecimals); + const scaledDecimals = tickDecimals - Math.floor(Math.log(tickSize) / Math.LN10); + const str = kbn.valueFormats[desc](value, tickDecimals, scaledDecimals); expect(str).toBe(result); }); }); @@ -106,177 +106,177 @@ describe('date time formats', function() { const browserTime = moment(epoch); it('should format as iso date', function() { - var expected = browserTime.format('YYYY-MM-DD HH:mm:ss'); - var actual = kbn.valueFormats.dateTimeAsIso(epoch); + const expected = browserTime.format('YYYY-MM-DD HH:mm:ss'); + const actual = kbn.valueFormats.dateTimeAsIso(epoch); expect(actual).toBe(expected); }); it('should format as iso date (in UTC)', function() { - var expected = utcTime.format('YYYY-MM-DD HH:mm:ss'); - var actual = kbn.valueFormats.dateTimeAsIso(epoch, true); + const expected = utcTime.format('YYYY-MM-DD HH:mm:ss'); + const actual = kbn.valueFormats.dateTimeAsIso(epoch, true); expect(actual).toBe(expected); }); it('should format as iso date and skip date when today', function() { - var now = moment(); - var expected = now.format('HH:mm:ss'); - var actual = kbn.valueFormats.dateTimeAsIso(now.valueOf(), false); + const now = moment(); + const expected = now.format('HH:mm:ss'); + const actual = kbn.valueFormats.dateTimeAsIso(now.valueOf(), false); expect(actual).toBe(expected); }); it('should format as iso date (in UTC) and skip date when today', function() { - var now = moment.utc(); - var expected = now.format('HH:mm:ss'); - var actual = kbn.valueFormats.dateTimeAsIso(now.valueOf(), true); + const now = moment.utc(); + const expected = now.format('HH:mm:ss'); + const actual = kbn.valueFormats.dateTimeAsIso(now.valueOf(), true); expect(actual).toBe(expected); }); it('should format as US date', function() { - var expected = browserTime.format('MM/DD/YYYY h:mm:ss a'); - var actual = kbn.valueFormats.dateTimeAsUS(epoch, false); + const expected = browserTime.format('MM/DD/YYYY h:mm:ss a'); + const actual = kbn.valueFormats.dateTimeAsUS(epoch, false); expect(actual).toBe(expected); }); it('should format as US date (in UTC)', function() { - var expected = utcTime.format('MM/DD/YYYY h:mm:ss a'); - var actual = kbn.valueFormats.dateTimeAsUS(epoch, true); + const expected = utcTime.format('MM/DD/YYYY h:mm:ss a'); + const actual = kbn.valueFormats.dateTimeAsUS(epoch, true); expect(actual).toBe(expected); }); it('should format as US date and skip date when today', function() { - var now = moment(); - var expected = now.format('h:mm:ss a'); - var actual = kbn.valueFormats.dateTimeAsUS(now.valueOf(), false); + const now = moment(); + const expected = now.format('h:mm:ss a'); + const actual = kbn.valueFormats.dateTimeAsUS(now.valueOf(), false); expect(actual).toBe(expected); }); it('should format as US date (in UTC) and skip date when today', function() { - var now = moment.utc(); - var expected = now.format('h:mm:ss a'); - var actual = kbn.valueFormats.dateTimeAsUS(now.valueOf(), true); + const now = moment.utc(); + const expected = now.format('h:mm:ss a'); + const actual = kbn.valueFormats.dateTimeAsUS(now.valueOf(), true); expect(actual).toBe(expected); }); it('should format as from now with days', function() { - var daysAgo = moment().add(-7, 'd'); - var expected = '7 days ago'; - var actual = kbn.valueFormats.dateTimeFromNow(daysAgo.valueOf(), false); + const daysAgo = moment().add(-7, 'd'); + const expected = '7 days ago'; + const actual = kbn.valueFormats.dateTimeFromNow(daysAgo.valueOf(), false); expect(actual).toBe(expected); }); it('should format as from now with days (in UTC)', function() { - var daysAgo = moment.utc().add(-7, 'd'); - var expected = '7 days ago'; - var actual = kbn.valueFormats.dateTimeFromNow(daysAgo.valueOf(), true); + const daysAgo = moment.utc().add(-7, 'd'); + const expected = '7 days ago'; + const actual = kbn.valueFormats.dateTimeFromNow(daysAgo.valueOf(), true); expect(actual).toBe(expected); }); it('should format as from now with minutes', function() { - var daysAgo = moment().add(-2, 'm'); - var expected = '2 minutes ago'; - var actual = kbn.valueFormats.dateTimeFromNow(daysAgo.valueOf(), false); + const daysAgo = moment().add(-2, 'm'); + const expected = '2 minutes ago'; + const actual = kbn.valueFormats.dateTimeFromNow(daysAgo.valueOf(), false); expect(actual).toBe(expected); }); it('should format as from now with minutes (in UTC)', function() { - var daysAgo = moment.utc().add(-2, 'm'); - var expected = '2 minutes ago'; - var actual = kbn.valueFormats.dateTimeFromNow(daysAgo.valueOf(), true); + const daysAgo = moment.utc().add(-2, 'm'); + const expected = '2 minutes ago'; + const actual = kbn.valueFormats.dateTimeFromNow(daysAgo.valueOf(), true); expect(actual).toBe(expected); }); }); describe('kbn.toFixed and negative decimals', function() { it('should treat as zero decimals', function() { - var str = kbn.toFixed(186.123, -2); + const str = kbn.toFixed(186.123, -2); expect(str).toBe('186'); }); }); describe('kbn ms format when scaled decimals is null do not use it', function() { it('should use specified decimals', function() { - var str = kbn.valueFormats['ms'](10000086.123, 1, null); + const str = kbn.valueFormats['ms'](10000086.123, 1, null); expect(str).toBe('2.8 hour'); }); }); describe('kbn kbytes format when scaled decimals is null do not use it', function() { it('should use specified decimals', function() { - var str = kbn.valueFormats['kbytes'](10000000, 3, null); + const str = kbn.valueFormats['kbytes'](10000000, 3, null); expect(str).toBe('9.537 GiB'); }); }); describe('kbn deckbytes format when scaled decimals is null do not use it', function() { it('should use specified decimals', function() { - var str = kbn.valueFormats['deckbytes'](10000000, 3, null); + const str = kbn.valueFormats['deckbytes'](10000000, 3, null); expect(str).toBe('10.000 GB'); }); }); describe('kbn roundValue', function() { it('should should handle null value', function() { - var str = kbn.roundValue(null, 2); + const str = kbn.roundValue(null, 2); expect(str).toBe(null); }); it('should round value', function() { - var str = kbn.roundValue(200.877, 2); + const str = kbn.roundValue(200.877, 2); expect(str).toBe(200.88); }); }); describe('calculateInterval', function() { it('1h 100 resultion', function() { - var range = { from: dateMath.parse('now-1h'), to: dateMath.parse('now') }; - var res = kbn.calculateInterval(range, 100, null); + const range = { from: dateMath.parse('now-1h'), to: dateMath.parse('now') }; + const res = kbn.calculateInterval(range, 100, null); expect(res.interval).toBe('30s'); }); it('10m 1600 resolution', function() { - var range = { from: dateMath.parse('now-10m'), to: dateMath.parse('now') }; - var res = kbn.calculateInterval(range, 1600, null); + const range = { from: dateMath.parse('now-10m'), to: dateMath.parse('now') }; + const res = kbn.calculateInterval(range, 1600, null); expect(res.interval).toBe('500ms'); expect(res.intervalMs).toBe(500); }); it('fixed user min interval', function() { - var range = { from: dateMath.parse('now-10m'), to: dateMath.parse('now') }; - var res = kbn.calculateInterval(range, 1600, '10s'); + const range = { from: dateMath.parse('now-10m'), to: dateMath.parse('now') }; + const res = kbn.calculateInterval(range, 1600, '10s'); expect(res.interval).toBe('10s'); expect(res.intervalMs).toBe(10000); }); it('short time range and user low limit', function() { - var range = { from: dateMath.parse('now-10m'), to: dateMath.parse('now') }; - var res = kbn.calculateInterval(range, 1600, '>10s'); + const range = { from: dateMath.parse('now-10m'), to: dateMath.parse('now') }; + const res = kbn.calculateInterval(range, 1600, '>10s'); expect(res.interval).toBe('10s'); }); it('large time range and user low limit', function() { - var range = { from: dateMath.parse('now-14d'), to: dateMath.parse('now') }; - var res = kbn.calculateInterval(range, 1000, '>10s'); + const range = { from: dateMath.parse('now-14d'), to: dateMath.parse('now') }; + const res = kbn.calculateInterval(range, 1000, '>10s'); expect(res.interval).toBe('20m'); }); it('10s 900 resolution and user low limit in ms', function() { - var range = { from: dateMath.parse('now-10s'), to: dateMath.parse('now') }; - var res = kbn.calculateInterval(range, 900, '>15ms'); + const range = { from: dateMath.parse('now-10s'), to: dateMath.parse('now') }; + const res = kbn.calculateInterval(range, 900, '>15ms'); expect(res.interval).toBe('15ms'); }); it('1d 1 resolution', function() { - var range = { from: dateMath.parse('now-1d'), to: dateMath.parse('now') }; - var res = kbn.calculateInterval(range, 1, null); + const range = { from: dateMath.parse('now-1d'), to: dateMath.parse('now') }; + const res = kbn.calculateInterval(range, 1, null); expect(res.interval).toBe('1d'); expect(res.intervalMs).toBe(86400000); }); it('86399s 1 resolution', function() { - var range = { + const range = { from: dateMath.parse('now-86390s'), to: dateMath.parse('now'), }; - var res = kbn.calculateInterval(range, 1, null); + const res = kbn.calculateInterval(range, 1, null); expect(res.interval).toBe('12h'); expect(res.intervalMs).toBe(43200000); }); @@ -284,139 +284,139 @@ describe('calculateInterval', function() { describe('hex', function() { it('positive integer', function() { - var str = kbn.valueFormats.hex(100, 0); + const str = kbn.valueFormats.hex(100, 0); expect(str).toBe('64'); }); it('negative integer', function() { - var str = kbn.valueFormats.hex(-100, 0); + const str = kbn.valueFormats.hex(-100, 0); expect(str).toBe('-64'); }); it('null', function() { - var str = kbn.valueFormats.hex(null, 0); + const str = kbn.valueFormats.hex(null, 0); expect(str).toBe(''); }); it('positive float', function() { - var str = kbn.valueFormats.hex(50.52, 1); + const str = kbn.valueFormats.hex(50.52, 1); expect(str).toBe('32.8'); }); it('negative float', function() { - var str = kbn.valueFormats.hex(-50.333, 2); + const str = kbn.valueFormats.hex(-50.333, 2); expect(str).toBe('-32.547AE147AE14'); }); }); describe('hex 0x', function() { it('positive integeter', function() { - var str = kbn.valueFormats.hex0x(7999, 0); + const str = kbn.valueFormats.hex0x(7999, 0); expect(str).toBe('0x1F3F'); }); it('negative integer', function() { - var str = kbn.valueFormats.hex0x(-584, 0); + const str = kbn.valueFormats.hex0x(-584, 0); expect(str).toBe('-0x248'); }); it('null', function() { - var str = kbn.valueFormats.hex0x(null, 0); + const str = kbn.valueFormats.hex0x(null, 0); expect(str).toBe(''); }); it('positive float', function() { - var str = kbn.valueFormats.hex0x(74.443, 3); + const str = kbn.valueFormats.hex0x(74.443, 3); expect(str).toBe('0x4A.716872B020C4'); }); it('negative float', function() { - var str = kbn.valueFormats.hex0x(-65.458, 1); + const str = kbn.valueFormats.hex0x(-65.458, 1); expect(str).toBe('-0x41.8'); }); }); describe('duration', function() { it('null', function() { - var str = kbn.toDuration(null, 0, 'millisecond'); + const str = kbn.toDuration(null, 0, 'millisecond'); expect(str).toBe(''); }); it('0 milliseconds', function() { - var str = kbn.toDuration(0, 0, 'millisecond'); + const str = kbn.toDuration(0, 0, 'millisecond'); expect(str).toBe('0 milliseconds'); }); it('1 millisecond', function() { - var str = kbn.toDuration(1, 0, 'millisecond'); + const str = kbn.toDuration(1, 0, 'millisecond'); expect(str).toBe('1 millisecond'); }); it('-1 millisecond', function() { - var str = kbn.toDuration(-1, 0, 'millisecond'); + const str = kbn.toDuration(-1, 0, 'millisecond'); expect(str).toBe('1 millisecond ago'); }); it('seconds', function() { - var str = kbn.toDuration(1, 0, 'second'); + const str = kbn.toDuration(1, 0, 'second'); expect(str).toBe('1 second'); }); it('minutes', function() { - var str = kbn.toDuration(1, 0, 'minute'); + const str = kbn.toDuration(1, 0, 'minute'); expect(str).toBe('1 minute'); }); it('hours', function() { - var str = kbn.toDuration(1, 0, 'hour'); + const str = kbn.toDuration(1, 0, 'hour'); expect(str).toBe('1 hour'); }); it('days', function() { - var str = kbn.toDuration(1, 0, 'day'); + const str = kbn.toDuration(1, 0, 'day'); expect(str).toBe('1 day'); }); it('weeks', function() { - var str = kbn.toDuration(1, 0, 'week'); + const str = kbn.toDuration(1, 0, 'week'); expect(str).toBe('1 week'); }); it('months', function() { - var str = kbn.toDuration(1, 0, 'month'); + const str = kbn.toDuration(1, 0, 'month'); expect(str).toBe('1 month'); }); it('years', function() { - var str = kbn.toDuration(1, 0, 'year'); + const str = kbn.toDuration(1, 0, 'year'); expect(str).toBe('1 year'); }); it('decimal days', function() { - var str = kbn.toDuration(1.5, 2, 'day'); + const str = kbn.toDuration(1.5, 2, 'day'); expect(str).toBe('1 day, 12 hours, 0 minutes'); }); it('decimal months', function() { - var str = kbn.toDuration(1.5, 3, 'month'); + const str = kbn.toDuration(1.5, 3, 'month'); expect(str).toBe('1 month, 2 weeks, 1 day, 0 hours'); }); it('no decimals', function() { - var str = kbn.toDuration(38898367008, 0, 'millisecond'); + const str = kbn.toDuration(38898367008, 0, 'millisecond'); expect(str).toBe('1 year'); }); it('1 decimal', function() { - var str = kbn.toDuration(38898367008, 1, 'millisecond'); + const str = kbn.toDuration(38898367008, 1, 'millisecond'); expect(str).toBe('1 year, 2 months'); }); it('too many decimals', function() { - var str = kbn.toDuration(38898367008, 20, 'millisecond'); + const str = kbn.toDuration(38898367008, 20, 'millisecond'); expect(str).toBe('1 year, 2 months, 3 weeks, 4 days, 5 hours, 6 minutes, 7 seconds, 8 milliseconds'); }); it('floating point error', function() { - var str = kbn.toDuration(36993906007, 8, 'millisecond'); + const str = kbn.toDuration(36993906007, 8, 'millisecond'); expect(str).toBe('1 year, 2 months, 0 weeks, 3 days, 4 hours, 5 minutes, 6 seconds, 7 milliseconds'); }); }); describe('volume', function() { it('1000m3', function() { - var str = kbn.valueFormats['m3'](1000, 1, null); + const str = kbn.valueFormats['m3'](1000, 1, null); expect(str).toBe('1000.0 m³'); }); }); describe('hh:mm:ss', function() { it('00:04:06', function() { - var str = kbn.valueFormats['dthms'](246, 1); + const str = kbn.valueFormats['dthms'](246, 1); expect(str).toBe('00:04:06'); }); it('24:00:00', function() { - var str = kbn.valueFormats['dthms'](86400, 1); + const str = kbn.valueFormats['dthms'](86400, 1); expect(str).toBe('24:00:00'); }); it('6824413:53:20', function() { - var str = kbn.valueFormats['dthms'](24567890000, 1); + const str = kbn.valueFormats['dthms'](24567890000, 1); expect(str).toBe('6824413:53:20'); }); }); diff --git a/public/app/core/specs/rangeutil.test.ts b/public/app/core/specs/rangeutil.test.ts index 6bfc0503900..4c0d3dc90c8 100644 --- a/public/app/core/specs/rangeutil.test.ts +++ b/public/app/core/specs/rangeutil.test.ts @@ -5,7 +5,7 @@ import moment from 'moment'; describe('rangeUtil', () => { describe('Can get range grouped list of ranges', () => { it('when custom settings should return default range list', () => { - var groups = rangeUtil.getRelativeTimesList({ time_options: [] }, 'Last 5 minutes'); + const groups = rangeUtil.getRelativeTimesList({ time_options: [] }, 'Last 5 minutes'); expect(_.keys(groups).length).toBe(4); expect(groups[3][0].active).toBe(true); }); @@ -13,62 +13,62 @@ describe('rangeUtil', () => { describe('Can get range text described', () => { it('should handle simple old expression with only amount and unit', () => { - var info = rangeUtil.describeTextRange('5m'); + const info = rangeUtil.describeTextRange('5m'); expect(info.display).toBe('Last 5 minutes'); }); it('should have singular when amount is 1', () => { - var info = rangeUtil.describeTextRange('1h'); + const info = rangeUtil.describeTextRange('1h'); expect(info.display).toBe('Last 1 hour'); }); it('should handle non default amount', () => { - var info = rangeUtil.describeTextRange('13h'); + const info = rangeUtil.describeTextRange('13h'); expect(info.display).toBe('Last 13 hours'); expect(info.from).toBe('now-13h'); }); it('should handle non default future amount', () => { - var info = rangeUtil.describeTextRange('+3h'); + const info = rangeUtil.describeTextRange('+3h'); expect(info.display).toBe('Next 3 hours'); expect(info.from).toBe('now'); expect(info.to).toBe('now+3h'); }); it('should handle now/d', () => { - var info = rangeUtil.describeTextRange('now/d'); + const info = rangeUtil.describeTextRange('now/d'); expect(info.display).toBe('Today so far'); }); it('should handle now/w', () => { - var info = rangeUtil.describeTextRange('now/w'); + const info = rangeUtil.describeTextRange('now/w'); expect(info.display).toBe('This week so far'); }); it('should handle now/M', () => { - var info = rangeUtil.describeTextRange('now/M'); + const info = rangeUtil.describeTextRange('now/M'); expect(info.display).toBe('This month so far'); }); it('should handle now/y', () => { - var info = rangeUtil.describeTextRange('now/y'); + const info = rangeUtil.describeTextRange('now/y'); expect(info.display).toBe('This year so far'); }); }); describe('Can get date range described', () => { it('Date range with simple ranges', () => { - var text = rangeUtil.describeTimeRange({ from: 'now-1h', to: 'now' }); + const text = rangeUtil.describeTimeRange({ from: 'now-1h', to: 'now' }); expect(text).toBe('Last 1 hour'); }); it('Date range with rounding ranges', () => { - var text = rangeUtil.describeTimeRange({ from: 'now/d+6h', to: 'now' }); + const text = rangeUtil.describeTimeRange({ from: 'now/d+6h', to: 'now' }); expect(text).toBe('now/d+6h to now'); }); it('Date range with absolute to now', () => { - var text = rangeUtil.describeTimeRange({ + const text = rangeUtil.describeTimeRange({ from: moment([2014, 10, 10, 2, 3, 4]), to: 'now', }); @@ -76,7 +76,7 @@ describe('rangeUtil', () => { }); it('Date range with absolute to relative', () => { - var text = rangeUtil.describeTimeRange({ + const text = rangeUtil.describeTimeRange({ from: moment([2014, 10, 10, 2, 3, 4]), to: 'now-1d', }); @@ -84,7 +84,7 @@ describe('rangeUtil', () => { }); it('Date range with relative to absolute', () => { - var text = rangeUtil.describeTimeRange({ + const text = rangeUtil.describeTimeRange({ from: 'now-7d', to: moment([2014, 10, 10, 2, 3, 4]), }); @@ -92,17 +92,17 @@ describe('rangeUtil', () => { }); it('Date range with non matching default ranges', () => { - var text = rangeUtil.describeTimeRange({ from: 'now-13h', to: 'now' }); + const text = rangeUtil.describeTimeRange({ from: 'now-13h', to: 'now' }); expect(text).toBe('Last 13 hours'); }); it('Date range with from and to both are in now-* format', () => { - var text = rangeUtil.describeTimeRange({ from: 'now-6h', to: 'now-3h' }); + const text = rangeUtil.describeTimeRange({ from: 'now-6h', to: 'now-3h' }); expect(text).toBe('now-6h to now-3h'); }); it('Date range with from and to both are either in now-* or now/* format', () => { - var text = rangeUtil.describeTimeRange({ + const text = rangeUtil.describeTimeRange({ from: 'now/d+6h', to: 'now-3h', }); @@ -110,7 +110,7 @@ describe('rangeUtil', () => { }); it('Date range with from and to both are either in now-* or now+* format', () => { - var text = rangeUtil.describeTimeRange({ from: 'now-6h', to: 'now+1h' }); + const text = rangeUtil.describeTimeRange({ from: 'now-6h', to: 'now+1h' }); expect(text).toBe('now-6h to now+1h'); }); }); 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/table_model.test.ts b/public/app/core/specs/table_model.test.ts index 3d4c526cfea..b88bad12227 100644 --- a/public/app/core/specs/table_model.test.ts +++ b/public/app/core/specs/table_model.test.ts @@ -1,8 +1,8 @@ import TableModel from 'app/core/table_model'; describe('when sorting table desc', () => { - var table; - var panel = { + let table; + const panel = { sort: { col: 0, desc: true }, }; @@ -27,7 +27,7 @@ describe('when sorting table desc', () => { describe('when sorting table asc', () => { var table; - var panel = { + const panel = { sort: { col: 1, desc: false }, }; 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..605c8fd0a2e 100644 --- a/public/app/core/specs/time_series.test.ts +++ b/public/app/core/specs/time_series.test.ts @@ -2,9 +2,9 @@ import TimeSeries from 'app/core/time_series2'; import { updateLegendValues } from 'app/core/time_series2'; describe('TimeSeries', function() { - var points, series; - var yAxisFormats = ['short', 'ms']; - var testData; + let points, series; + const yAxisFormats = ['short', 'ms']; + let testData; beforeEach(function() { testData = { @@ -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/css_loader.ts b/public/app/core/utils/css_loader.ts index ba8623df842..b8aaef47085 100644 --- a/public/app/core/utils/css_loader.ts +++ b/public/app/core/utils/css_loader.ts @@ -1,18 +1,18 @@ -var waitSeconds = 100; -var head = document.getElementsByTagName('head')[0]; +const waitSeconds = 100; +const head = document.getElementsByTagName('head')[0]; // get all link tags in the page -var links = document.getElementsByTagName('link'); -var linkHrefs = []; -for (var i = 0; i < links.length; i++) { +const links = document.getElementsByTagName('link'); +const linkHrefs = []; +for (let i = 0; i < links.length; i++) { linkHrefs.push(links[i].href); } -var isWebkit = !!window.navigator.userAgent.match(/AppleWebKit\/([^ ;]*)/); -var webkitLoadCheck = function(link, callback) { +const isWebkit = !!window.navigator.userAgent.match(/AppleWebKit\/([^ ;]*)/); +const webkitLoadCheck = function(link, callback) { setTimeout(function() { for (var i = 0; i < document.styleSheets.length; i++) { - var sheet = document.styleSheets[i]; + const sheet = document.styleSheets[i]; if (sheet.href === link.href) { return callback(); } @@ -21,16 +21,16 @@ var webkitLoadCheck = function(link, callback) { }, 10); }; -var noop = function() {}; +const noop = function() {}; -var loadCSS = function(url) { +const loadCSS = function(url) { return new Promise(function(resolve, reject) { - var link = document.createElement('link'); - var timeout = setTimeout(function() { + const link = document.createElement('link'); + const timeout = setTimeout(function() { reject('Unable to load CSS'); }, waitSeconds * 1000); - var _callback = function(error) { + const _callback = function(error) { clearTimeout(timeout); link.onload = link.onerror = noop; setTimeout(function() { 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/flatten.ts b/public/app/core/utils/flatten.ts index 150017e34f8..3350f5f6c33 100644 --- a/public/app/core/utils/flatten.ts +++ b/public/app/core/utils/flatten.ts @@ -4,19 +4,19 @@ export default function flatten(target, opts): any { opts = opts || {}; - var delimiter = opts.delimiter || '.'; - var maxDepth = opts.maxDepth || 3; - var currentDepth = 1; - var output = {}; + const delimiter = opts.delimiter || '.'; + let maxDepth = opts.maxDepth || 3; + let currentDepth = 1; + const output = {}; function step(object, prev) { Object.keys(object).forEach(function(key) { - var value = object[key]; - var isarray = opts.safe && Array.isArray(value); - var type = Object.prototype.toString.call(value); - var isobject = type === '[object Object]'; + const value = object[key]; + const isarray = opts.safe && Array.isArray(value); + const type = Object.prototype.toString.call(value); + const isobject = type === '[object Object]'; - var newKey = prev ? prev + delimiter + key : key; + const newKey = prev ? prev + delimiter + key : key; if (!opts.maxDepth) { maxDepth = currentDepth + 1; diff --git a/public/app/core/utils/kbn.ts b/public/app/core/utils/kbn.ts index c2764670b95..9f30972bc61 100644 --- a/public/app/core/utils/kbn.ts +++ b/public/app/core/utils/kbn.ts @@ -1,7 +1,7 @@ import _ from 'lodash'; import moment from 'moment'; -var kbn: any = {}; +const kbn: any = {}; kbn.valueFormats = {}; @@ -103,27 +103,27 @@ kbn.round_interval = function(interval) { }; kbn.secondsToHms = function(seconds) { - var numyears = Math.floor(seconds / 31536000); + const numyears = Math.floor(seconds / 31536000); if (numyears) { return numyears + 'y'; } - var numdays = Math.floor((seconds % 31536000) / 86400); + const numdays = Math.floor((seconds % 31536000) / 86400); if (numdays) { return numdays + 'd'; } - var numhours = Math.floor(((seconds % 31536000) % 86400) / 3600); + const numhours = Math.floor(((seconds % 31536000) % 86400) / 3600); if (numhours) { return numhours + 'h'; } - var numminutes = Math.floor((((seconds % 31536000) % 86400) % 3600) / 60); + const numminutes = Math.floor((((seconds % 31536000) % 86400) % 3600) / 60); if (numminutes) { return numminutes + 'm'; } - var numseconds = Math.floor((((seconds % 31536000) % 86400) % 3600) % 60); + const numseconds = Math.floor((((seconds % 31536000) % 86400) % 3600) % 60); if (numseconds) { return numseconds + 's'; } - var nummilliseconds = Math.floor(seconds * 1000.0); + const nummilliseconds = Math.floor(seconds * 1000.0); if (nummilliseconds) { return nummilliseconds + 'ms'; } @@ -132,10 +132,10 @@ kbn.secondsToHms = function(seconds) { }; kbn.secondsToHhmmss = function(seconds) { - var strings = []; - var numhours = Math.floor(seconds / 3600); - var numminutes = Math.floor((seconds % 3600) / 60); - var numseconds = Math.floor((seconds % 3600) % 60); + const strings = []; + const numhours = Math.floor(seconds / 3600); + const numminutes = Math.floor((seconds % 3600) / 60); + const numseconds = Math.floor((seconds % 3600) % 60); numhours > 9 ? strings.push('' + numhours) : strings.push('0' + numhours); numminutes > 9 ? strings.push('' + numminutes) : strings.push('0' + numminutes); numseconds > 9 ? strings.push('' + numseconds) : strings.push('0' + numseconds); @@ -191,7 +191,7 @@ kbn.calculateInterval = function(range, resolution, lowLimitInterval) { }; kbn.describe_interval = function(str) { - var matches = str.match(kbn.interval_regex); + const matches = str.match(kbn.interval_regex); if (!matches || !_.has(kbn.intervals_in_seconds, matches[2])) { throw new Error('Invalid interval string, expecting a number followed by one of "Mwdhmsy"'); } else { @@ -204,12 +204,12 @@ kbn.describe_interval = function(str) { }; kbn.interval_to_ms = function(str) { - var info = kbn.describe_interval(str); + const info = kbn.describe_interval(str); return info.sec * 1000 * info.count; }; kbn.interval_to_seconds = function(str) { - var info = kbn.describe_interval(str); + const info = kbn.describe_interval(str); return info.sec * info.count; }; @@ -233,7 +233,7 @@ kbn.stringToJsRegex = function(str) { return new RegExp('^' + str + '$'); } - var match = str.match(new RegExp('^/(.*?)/(g?i?m?y?)$')); + const match = str.match(new RegExp('^/(.*?)/(g?i?m?y?)$')); return new RegExp(match[1], match[2]); }; @@ -242,8 +242,8 @@ kbn.toFixed = function(value, decimals) { return ''; } - var factor = decimals ? Math.pow(10, Math.max(0, decimals)) : 1; - var formatted = String(Math.round(value * factor) / factor); + const factor = decimals ? Math.pow(10, Math.max(0, decimals)) : 1; + const formatted = String(Math.round(value * factor) / factor); // if exponent return directly if (formatted.indexOf('e') !== -1 || value === 0) { @@ -253,8 +253,8 @@ kbn.toFixed = function(value, decimals) { // If tickDecimals was specified, ensure that we have exactly that // much precision; otherwise default to the value's own precision. if (decimals != null) { - var decimalPos = formatted.indexOf('.'); - var precision = decimalPos === -1 ? 0 : formatted.length - decimalPos - 1; + const decimalPos = formatted.indexOf('.'); + const precision = decimalPos === -1 ? 0 : formatted.length - decimalPos - 1; if (precision < decimals) { return (precision ? formatted : formatted + '.') + String(factor).substr(1, decimals - precision); } @@ -275,8 +275,8 @@ kbn.roundValue = function(num, decimals) { if (num === null) { return null; } - var n = Math.pow(10, decimals); - var formatted = (n * num).toFixed(decimals); + const n = Math.pow(10, decimals); + const formatted = (n * num).toFixed(decimals); return Math.round(parseFloat(formatted)) / n; }; @@ -305,7 +305,7 @@ kbn.formatBuilders.scaledUnits = function(factor, extArray) { } var steps = 0; - var limit = extArray.length; + const limit = extArray.length; while (Math.abs(size) >= factor) { steps++; @@ -330,7 +330,7 @@ kbn.formatBuilders.scaledUnits = function(factor, extArray) { kbn.formatBuilders.decimalSIPrefix = function(unit, offset) { var prefixes = ['n', 'µ', 'm', '', 'k', 'M', 'G', 'T', 'P', 'E', 'Z', 'Y']; prefixes = prefixes.slice(3 + (offset || 0)); - var units = prefixes.map(function(p) { + const units = prefixes.map(function(p) { return ' ' + p + unit; }); return kbn.formatBuilders.scaledUnits(1000, units); @@ -340,8 +340,8 @@ kbn.formatBuilders.decimalSIPrefix = function(unit, offset) { // offset is given, it starts the units at the given prefix; otherwise, the // offset defaults to zero and the initial unit is not prefixed. kbn.formatBuilders.binarySIPrefix = function(unit, offset) { - var prefixes = ['', 'Ki', 'Mi', 'Gi', 'Ti', 'Pi', 'Ei', 'Zi', 'Yi'].slice(offset); - var units = prefixes.map(function(p) { + const prefixes = ['', 'Ki', 'Mi', 'Gi', 'Ti', 'Pi', 'Ei', 'Zi', 'Yi'].slice(offset); + const units = prefixes.map(function(p) { return ' ' + p + unit; }); return kbn.formatBuilders.scaledUnits(1024, units); @@ -350,25 +350,25 @@ kbn.formatBuilders.binarySIPrefix = function(unit, offset) { // Currency formatter for prefixing a symbol onto a number. Supports scaling // up to the trillions. kbn.formatBuilders.currency = function(symbol) { - var units = ['', 'K', 'M', 'B', 'T']; - var scaler = kbn.formatBuilders.scaledUnits(1000, units); + const units = ['', 'K', 'M', 'B', 'T']; + const scaler = kbn.formatBuilders.scaledUnits(1000, units); return function(size, decimals, scaledDecimals) { if (size === null) { return ''; } - var scaled = scaler(size, decimals, scaledDecimals); + const scaled = scaler(size, decimals, scaledDecimals); return symbol + scaled; }; }; kbn.formatBuilders.simpleCountUnit = function(symbol) { - var units = ['', 'K', 'M', 'B', 'T']; - var scaler = kbn.formatBuilders.scaledUnits(1000, units); + const units = ['', 'K', 'M', 'B', 'T']; + const scaler = kbn.formatBuilders.scaledUnits(1000, units); return function(size, decimals, scaledDecimals) { if (size === null) { return ''; } - var scaled = scaler(size, decimals, scaledDecimals); + const scaled = scaler(size, decimals, scaledDecimals); return scaled + ' ' + symbol; }; }; @@ -420,7 +420,7 @@ kbn.valueFormats.hex0x = function(value, decimals) { if (value == null) { return ''; } - var hexString = kbn.valueFormats.hex(value, decimals); + const hexString = kbn.valueFormats.hex(value, decimals); if (hexString.substring(0, 1) === '-') { return '-0x' + hexString.substring(1); } @@ -769,7 +769,7 @@ kbn.toDuration = function(size, decimals, timeScale) { return kbn.toDuration(-size, decimals, timeScale) + ' ago'; } - var units = [ + const units = [ { short: 'y', long: 'year' }, { short: 'M', long: 'month' }, { short: 'w', long: 'week' }, @@ -788,16 +788,16 @@ kbn.toDuration = function(size, decimals, timeScale) { }).short ] * 1000; - var strings = []; + const strings = []; // after first value >= 1 print only $decimals more var decrementDecimals = false; for (var i = 0; i < units.length && decimals >= 0; i++) { - var interval = kbn.intervals_in_seconds[units[i].short] * 1000; - var value = size / interval; + const interval = kbn.intervals_in_seconds[units[i].short] * 1000; + const value = size / interval; if (value >= 1 || decrementDecimals) { decrementDecimals = true; - var floor = Math.floor(value); - var unit = units[i].long + (floor !== 1 ? 's' : ''); + const floor = Math.floor(value); + const unit = units[i].long + (floor !== 1 ? 's' : ''); strings.push(floor + ' ' + unit); size = size % interval; decimals--; @@ -824,7 +824,7 @@ kbn.valueFormats.timeticks = function(size, decimals, scaledDecimals) { }; kbn.valueFormats.dateTimeAsIso = function(epoch, isUtc) { - var time = isUtc ? moment.utc(epoch) : moment(epoch); + const time = isUtc ? moment.utc(epoch) : moment(epoch); if (moment().isSame(epoch, 'day')) { return time.format('HH:mm:ss'); @@ -833,7 +833,7 @@ kbn.valueFormats.dateTimeAsIso = function(epoch, isUtc) { }; kbn.valueFormats.dateTimeAsUS = function(epoch, isUtc) { - var time = isUtc ? moment.utc(epoch) : moment(epoch); + const time = isUtc ? moment.utc(epoch) : moment(epoch); if (moment().isSame(epoch, 'day')) { return time.format('h:mm:ss a'); @@ -842,7 +842,7 @@ kbn.valueFormats.dateTimeAsUS = function(epoch, isUtc) { }; kbn.valueFormats.dateTimeFromNow = function(epoch, isUtc) { - var time = isUtc ? moment.utc(epoch) : moment(epoch); + const time = isUtc ? moment.utc(epoch) : moment(epoch); return time.fromNow(); }; 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..bda861e4b9f 100644 --- a/public/app/core/utils/rangeutil.ts +++ b/public/app/core/utils/rangeutil.ts @@ -2,7 +2,7 @@ import _ from 'lodash'; import moment from 'moment'; import * as dateMath from './datemath'; -var spans = { +const spans = { s: { display: 'second' }, m: { display: 'minute' }, h: { display: 'hour' }, @@ -12,7 +12,7 @@ var spans = { y: { display: 'year' }, }; -var rangeOptions = [ +const rangeOptions = [ { from: 'now/d', to: 'now/d', display: 'Today', section: 2 }, { from: 'now/d', to: 'now', display: 'Today so far', section: 2 }, { from: 'now/w', to: 'now/w', display: 'This week', section: 2 }, @@ -58,15 +58,15 @@ var rangeOptions = [ { from: 'now-5y', to: 'now', display: 'Last 5 years', section: 0 }, ]; -var absoluteFormat = 'MMM D, YYYY HH:mm:ss'; +const absoluteFormat = 'MMM D, YYYY HH:mm:ss'; -var rangeIndex = {}; +const rangeIndex = {}; _.each(rangeOptions, function(frame) { rangeIndex[frame.from + ' to ' + frame.to] = frame; }); export function getRelativeTimesList(timepickerSettings, currentDisplay) { - var groups = _.groupBy(rangeOptions, (option: any) => { + const groups = _.groupBy(rangeOptions, (option: any) => { option.active = option.display === currentDisplay; return option.section; }); @@ -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; @@ -130,7 +130,7 @@ export function describeTextRange(expr: any) { } export function describeTimeRange(range) { - var option = rangeIndex[range.from.toString() + ' to ' + range.to.toString()]; + const option = rangeIndex[range.from.toString() + ' to ' + range.to.toString()]; if (option) { return option.display; } @@ -140,17 +140,17 @@ export function describeTimeRange(range) { } if (moment.isMoment(range.from)) { - var toMoment = dateMath.parse(range.to, true); + const toMoment = dateMath.parse(range.to, true); return formatDate(range.from) + ' to ' + toMoment.fromNow(); } if (moment.isMoment(range.to)) { - var from = dateMath.parse(range.from, false); + const from = dateMath.parse(range.from, false); return from.fromNow() + ' to ' + formatDate(range.to); } if (range.to.toString() === 'now') { - var res = describeTextRange(range.from); + const res = describeTextRange(range.from); return res.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/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/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..60942e6ffb4 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); } @@ -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/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/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..f262544da43 100644 --- a/public/app/features/annotations/specs/annotations_srv.test.ts +++ b/public/app/features/annotations/specs/annotations_srv.test.ts @@ -3,15 +3,11 @@ import 'app/features/dashboard/time_srv'; import { AnnotationsSrv } from '../annotations_srv'; describe('AnnotationsSrv', function() { - let $rootScope = { + const $rootScope = { onAppEvent: jest.fn(), }; - let $q; - let datasourceSrv; - let backendSrv; - let timeSrv; - let 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/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..68b068152b5 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')); } @@ -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_ctrl.ts b/public/app/features/dashboard/dashboard_ctrl.ts index c6bb6492172..5524b55e3dd 100644 --- a/public/app/features/dashboard/dashboard_ctrl.ts +++ b/public/app/features/dashboard/dashboard_ctrl.ts @@ -106,7 +106,7 @@ export class DashboardCtrl implements PanelContainer { } showJsonEditor(evt, options) { - var editScope = this.$rootScope.$new(); + const editScope = this.$rootScope.$new(); editScope.object = options.object; editScope.updateHandler = options.updateHandler; this.$scope.appEvent('show-dash-editor', { @@ -137,7 +137,7 @@ export class DashboardCtrl implements PanelContainer { return; } - var panelInfo = this.dashboard.getPanelInfoById(options.panelId); + const panelInfo = this.dashboard.getPanelInfoById(options.panelId); this.removePanel(panelInfo.panel, true); } diff --git a/public/app/features/dashboard/dashboard_import_ctrl.ts b/public/app/features/dashboard/dashboard_import_ctrl.ts index 73e9e316b4e..3dfae1250dd 100644 --- a/public/app/features/dashboard/dashboard_import_ctrl.ts +++ b/public/app/features/dashboard/dashboard_import_ctrl.ts @@ -51,8 +51,8 @@ export class DashboardImportCtrl { this.inputs = []; if (this.dash.__inputs) { - for (let input of this.dash.__inputs) { - var inputModel = { + for (const input of this.dash.__inputs) { + 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; }); @@ -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; } @@ -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/dashboard_loader_srv.ts b/public/app/features/dashboard/dashboard_loader_srv.ts index 9e458c4e4bb..cbf753c0124 100644 --- a/public/app/features/dashboard/dashboard_loader_srv.ts +++ b/public/app/features/dashboard/dashboard_loader_srv.ts @@ -71,7 +71,7 @@ export class DashboardLoaderSrv { } _loadScriptedDashboard(file) { - var url = 'public/dashboards/' + file.replace(/\.(?!js)/, '/') + '?' + new Date().getTime(); + const url = 'public/dashboards/' + file.replace(/\.(?!js)/, '/') + '?' + new Date().getTime(); return this.$http({ url: url, method: 'GET' }) .then(this._executeScript.bind(this)) @@ -99,14 +99,14 @@ export class DashboardLoaderSrv { } _executeScript(result) { - var services = { + const services = { dashboardSrv: this.dashboardSrv, datasourceSrv: this.datasourceSrv, $q: this.$q, }; /*jshint -W054 */ - var script_func = new Function( + const script_func = new Function( 'ARGS', 'kbn', 'dateMath', @@ -119,11 +119,11 @@ export class DashboardLoaderSrv { 'services', result.data ); - var script_result = script_func(this.$routeParams, kbn, dateMath, _, moment, window, document, $, $, services); + const script_result = script_func(this.$routeParams, kbn, dateMath, _, moment, window, document, $, $, services); // Handle async dashboard scripts if (_.isFunction(script_result)) { - var deferred = this.$q.defer(); + const deferred = this.$q.defer(); script_result(dashboard => { this.$timeout(() => { deferred.resolve({ data: dashboard }); 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..a26a0401d56 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; @@ -97,7 +97,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/dashgrid/PanelLoader.ts b/public/app/features/dashboard/dashgrid/PanelLoader.ts index beda30bdff7..c654b756085 100644 --- a/public/app/features/dashboard/dashgrid/PanelLoader.ts +++ b/public/app/features/dashboard/dashgrid/PanelLoader.ts @@ -10,8 +10,8 @@ export class PanelLoader { constructor(private $compile, private $rootScope) {} load(elem, panel, dashboard): AttachedPanel { - var template = ''; - var panelScope = this.$rootScope.$new(); + const template = ''; + const panelScope = this.$rootScope.$new(); panelScope.panel = panel; panelScope.dashboard = dashboard; diff --git a/public/app/features/dashboard/dashnav/dashnav.ts b/public/app/features/dashboard/dashnav/dashnav.ts index 628f09349d3..6d6373c7e82 100644 --- a/public/app/features/dashboard/dashnav/dashnav.ts +++ b/public/app/features/dashboard/dashnav/dashnav.ts @@ -13,7 +13,7 @@ export class DashNavCtrl { appEvents.on('save-dashboard', this.saveDashboard.bind(this), $scope); if (this.dashboard.meta.isSnapshot) { - var meta = this.dashboard.meta; + const meta = this.dashboard.meta; this.titleTooltip = 'Created:  ' + moment(meta.created).calendar(); if (meta.expires) { this.titleTooltip += '
    Expires:  ' + moment(meta.expires).fromNow() + '
    '; @@ -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) { @@ -49,7 +49,7 @@ export class DashNavCtrl { } shareDashboard(tabIndex) { - var modalScope = this.$scope.$new(); + const modalScope = this.$scope.$new(); modalScope.tabIndex = tabIndex; modalScope.dashboard = this.dashboard; diff --git a/public/app/features/dashboard/export/export_modal.ts b/public/app/features/dashboard/export/export_modal.ts index 2e61ce9f8a8..f99946915d6 100644 --- a/public/app/features/dashboard/export/export_modal.ts +++ b/public/app/features/dashboard/export/export_modal.ts @@ -21,15 +21,15 @@ export class DashExportCtrl { } save() { - var blob = new Blob([angular.toJson(this.dash, true)], { + const blob = new Blob([angular.toJson(this.dash, true)], { type: 'application/json;charset=utf-8', }); saveAs(blob, this.dash.title + '-' + new Date().getTime() + '.json'); } saveJson() { - var clone = this.dash; - let editScope = this.$rootScope.$new(); + const clone = this.dash; + 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..d0802be72db 100644 --- a/public/app/features/dashboard/export/exporter.ts +++ b/public/app/features/dashboard/export/exporter.ts @@ -12,23 +12,23 @@ export class DashboardExporter { // this is pretty hacky and needs to be changed dashboard.cleanUpRepeats(); - var saveModel = dashboard.getSaveModelClone(); + const saveModel = dashboard.getSaveModelClone(); saveModel.id = null; // undo repeat cleanup dashboard.processRepeats(); - var inputs = []; - var requires = {}; - var datasources = {}; - var promises = []; - var variableLookup: any = {}; + const inputs = []; + const requires = {}; + const datasources = {}; + const promises = []; + const variableLookup: any = {}; - for (let variable of saveModel.templating.list) { + for (const variable of saveModel.templating.list) { variableLookup[variable.name] = variable; } - var templateizeDatasourceUsage = obj => { + 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, @@ -69,14 +69,14 @@ export class DashboardExporter { } if (panel.targets) { - for (let target of panel.targets) { + for (const target of panel.targets) { if (target.datasource !== undefined) { templateizeDatasourceUsage(target); } } } - var panelDef = config.panels[panel.type]; + const panelDef = config.panels[panel.type]; if (panelDef) { requires['panel' + panelDef.id] = { type: 'panel', @@ -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,9 +129,9 @@ 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(); + 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/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/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