prettier: ran on all files again, sorry. now settings are defined in package.json

This commit is contained in:
Torkel Ödegaard 2017-12-21 08:39:31 +01:00
parent af34f9977e
commit 3a1f52d8a2
262 changed files with 3996 additions and 7431 deletions

View File

@ -7,6 +7,8 @@ indent_size = 2
charset = utf-8 charset = utf-8
trim_trailing_whitespace = true trim_trailing_whitespace = true
insert_final_newline = true insert_final_newline = true
max_line_length = 120
insert_final_newline = true
[*.go] [*.go]
indent_style = tab indent_style = tab

View File

@ -107,14 +107,19 @@
}, },
"lint-staged": { "lint-staged": {
"*.{ts,tsx}": [ "*.{ts,tsx}": [
"prettier --single-quote --trailing-comma es5 --write", "prettier --write",
"git add" "git add"
], ],
"*.scss": [ "*.scss": [
"prettier --single-quote --write", "prettier --write",
"git add" "git add"
] ]
}, },
"prettier": {
"trailingComma": "es5",
"singleQuote": true,
"printWidth": 120
},
"license": "Apache-2.0", "license": "Apache-2.0",
"dependencies": { "dependencies": {
"angular": "^1.6.6", "angular": "^1.6.6",

View File

@ -54,15 +54,7 @@ export class GrafanaApp {
moment.locale(config.bootData.user.locale); moment.locale(config.bootData.user.locale);
app.config( app.config(($locationProvider, $controllerProvider, $compileProvider, $filterProvider, $httpProvider, $provide) => {
(
$locationProvider,
$controllerProvider,
$compileProvider,
$filterProvider,
$httpProvider,
$provide
) => {
// pre assing bindings before constructor calls // pre assing bindings before constructor calls
$compileProvider.preAssignBindingsEnabled(true); $compileProvider.preAssignBindingsEnabled(true);
@ -95,8 +87,7 @@ export class GrafanaApp {
return $delegate; return $delegate;
}, },
]); ]);
} });
);
this.ngModuleDependencies = [ this.ngModuleDependencies = [
'grafana.core', 'grafana.core',
@ -111,14 +102,7 @@ export class GrafanaApp {
'react', 'react',
]; ];
var module_types = [ var module_types = ['controllers', 'directives', 'factories', 'services', 'filters', 'routes'];
'controllers',
'directives',
'factories',
'services',
'filters',
'routes',
];
_.each(module_types, type => { _.each(module_types, type => {
var moduleName = 'grafana.' + type; var moduleName = 'grafana.' + type;

View File

@ -56,9 +56,7 @@ function link(scope, elem, attrs) {
let maxLines = attrs.maxLines || DEFAULT_MAX_LINES; let maxLines = attrs.maxLines || DEFAULT_MAX_LINES;
let showGutter = attrs.showGutter !== undefined; let showGutter = attrs.showGutter !== undefined;
let tabSize = attrs.tabSize || DEFAULT_TAB_SIZE; let tabSize = attrs.tabSize || DEFAULT_TAB_SIZE;
let behavioursEnabled = attrs.behavioursEnabled let behavioursEnabled = attrs.behavioursEnabled ? attrs.behavioursEnabled === 'true' : DEFAULT_BEHAVIOURS;
? attrs.behavioursEnabled === 'true'
: DEFAULT_BEHAVIOURS;
// Initialize editor // Initialize editor
let aceElem = elem.get(0); let aceElem = elem.get(0);

View File

@ -12,8 +12,7 @@ export function spectrumPicker() {
require: 'ngModel', require: 'ngModel',
scope: true, scope: true,
replace: true, replace: true,
template: template: '<color-picker color="ngModel.$viewValue" onChange="onColorChange"></color-picker>',
'<color-picker color="ngModel.$viewValue" onChange="onColorChange"></color-picker>',
link: function(scope, element, attrs, ngModel) { link: function(scope, element, attrs, ngModel) {
scope.ngModel = ngModel; scope.ngModel = ngModel;
scope.onColorChange = color => { scope.onColorChange = color => {

View File

@ -32,13 +32,7 @@ export class FormDropdownCtrl {
lookupText: boolean; lookupText: boolean;
/** @ngInject **/ /** @ngInject **/
constructor( constructor(private $scope, $element, private $sce, private templateSrv, private $q) {
private $scope,
$element,
private $sce,
private templateSrv,
private $q
) {
this.inputElement = $element.find('input').first(); this.inputElement = $element.find('input').first();
this.linkElement = $element.find('a').first(); this.linkElement = $element.find('a').first();
this.linkMode = true; this.linkMode = true;
@ -50,8 +44,7 @@ export class FormDropdownCtrl {
if (this.labelMode) { if (this.labelMode) {
this.cssClasses = 'gf-form-label ' + this.cssClass; this.cssClasses = 'gf-form-label ' + this.cssClass;
} else { } else {
this.cssClasses = this.cssClasses = 'gf-form-input gf-form-input--dropdown ' + this.cssClass;
'gf-form-input gf-form-input--dropdown ' + this.cssClass;
} }
this.inputElement.attr('data-provide', 'typeahead'); this.inputElement.attr('data-provide', 'typeahead');
@ -207,16 +200,11 @@ export class FormDropdownCtrl {
updateDisplay(text) { updateDisplay(text) {
this.text = text; this.text = text;
this.display = this.$sce.trustAsHtml( this.display = this.$sce.trustAsHtml(this.templateSrv.highlightVariablesAsHtml(text));
this.templateSrv.highlightVariablesAsHtml(text)
);
} }
open() { open() {
this.inputElement.css( this.inputElement.css('width', Math.max(this.linkElement.width(), 80) + 16 + 'px');
'width',
Math.max(this.linkElement.width(), 80) + 16 + 'px'
);
this.inputElement.show(); this.inputElement.show();
this.inputElement.focus(); this.inputElement.focus();

View File

@ -9,15 +9,7 @@ import Drop from 'tether-drop';
export class GrafanaCtrl { export class GrafanaCtrl {
/** @ngInject */ /** @ngInject */
constructor( constructor($scope, alertSrv, utilSrv, $rootScope, $controller, contextSrv, globalEventSrv) {
$scope,
alertSrv,
utilSrv,
$rootScope,
$controller,
contextSrv,
globalEventSrv
) {
$scope.init = function() { $scope.init = function() {
$scope.contextSrv = contextSrv; $scope.contextSrv = contextSrv;
@ -118,12 +110,7 @@ export class GrafanaCtrl {
} }
/** @ngInject */ /** @ngInject */
export function grafanaAppDirective( export function grafanaAppDirective(playlistSrv, contextSrv, $timeout, $rootScope) {
playlistSrv,
contextSrv,
$timeout,
$rootScope
) {
return { return {
restrict: 'E', restrict: 'E',
controller: GrafanaCtrl, controller: GrafanaCtrl,
@ -269,10 +256,7 @@ export function grafanaAppDirective(
// hide search // hide search
if (body.find('.search-container').length > 0) { if (body.find('.search-container').length > 0) {
if ( if (target.parents('.search-results-container, .search-field-wrapper').length === 0) {
target.parents('.search-results-container, .search-field-wrapper')
.length === 0
) {
scope.$apply(function() { scope.$apply(function() {
scope.appEvent('hide-dash-search'); scope.appEvent('hide-dash-search');
}); });
@ -281,10 +265,7 @@ export function grafanaAppDirective(
// hide popovers // hide popovers
var popover = elem.find('.popover'); var popover = elem.find('.popover');
if ( if (popover.length > 0 && target.parents('.graph-legend').length === 0) {
popover.length > 0 &&
target.parents('.graph-legend').length === 0
) {
popover.hide(); popover.hide();
} }
}); });

View File

@ -103,11 +103,7 @@ export function cssClass(className: string): string {
* Creates a new DOM element wiht given type and class * Creates a new DOM element wiht given type and class
* TODO: move me to helpers * TODO: move me to helpers
*/ */
export function createElement( export function createElement(type: string, className?: string, content?: Element | string): Element {
type: string,
className?: string,
content?: Element | string
): Element {
const el = document.createElement(type); const el = document.createElement(type);
if (className) { if (className) {
el.classList.add(cssClass(className)); el.classList.add(cssClass(className));

View File

@ -1,14 +1,7 @@
// Based on work https://github.com/mohsen1/json-formatter-js // Based on work https://github.com/mohsen1/json-formatter-js
// Licence MIT, Copyright (c) 2015 Mohsen Azimi // Licence MIT, Copyright (c) 2015 Mohsen Azimi
import { import { isObject, getObjectName, getType, getValuePreview, cssClass, createElement } from './helpers';
isObject,
getObjectName,
getType,
getValuePreview,
cssClass,
createElement,
} from './helpers';
import _ from 'lodash'; import _ from 'lodash';
@ -112,9 +105,7 @@ export class JsonExplorer {
private get isDate(): boolean { private get isDate(): boolean {
return ( return (
this.type === 'string' && this.type === 'string' &&
(DATE_STRING_REGEX.test(this.json) || (DATE_STRING_REGEX.test(this.json) || JSON_DATE_REGEX.test(this.json) || PARTIAL_DATE_REGEX.test(this.json))
JSON_DATE_REGEX.test(this.json) ||
PARTIAL_DATE_REGEX.test(this.json))
); );
} }
@ -151,9 +142,7 @@ export class JsonExplorer {
* is this an empty object or array? * is this an empty object or array?
*/ */
private get isEmpty(): boolean { private get isEmpty(): boolean {
return ( return this.isEmptyObject || (this.keys && !this.keys.length && this.isArray);
this.isEmptyObject || (this.keys && !this.keys.length && this.isArray)
);
} }
/* /*
@ -234,11 +223,7 @@ export class JsonExplorer {
} }
isNumberArray() { isNumberArray() {
return ( return this.json.length > 0 && this.json.length < 4 && (_.isNumber(this.json[0]) || _.isNumber(this.json[1]));
this.json.length > 0 &&
this.json.length < 4 &&
(_.isNumber(this.json[0]) || _.isNumber(this.json[1]))
);
} }
renderArray() { renderArray() {
@ -249,17 +234,13 @@ export class JsonExplorer {
if (this.isNumberArray()) { if (this.isNumberArray()) {
this.json.forEach((val, index) => { this.json.forEach((val, index) => {
if (index > 0) { if (index > 0) {
arrayWrapperSpan.appendChild( arrayWrapperSpan.appendChild(createElement('span', 'array-comma', ','));
createElement('span', 'array-comma', ',')
);
} }
arrayWrapperSpan.appendChild(createElement('span', 'number', val)); arrayWrapperSpan.appendChild(createElement('span', 'number', val));
}); });
this.skipChildren = true; this.skipChildren = true;
} else { } else {
arrayWrapperSpan.appendChild( arrayWrapperSpan.appendChild(createElement('span', 'number', this.json.length));
createElement('span', 'number', this.json.length)
);
} }
arrayWrapperSpan.appendChild(createElement('span', 'bracket', ']')); arrayWrapperSpan.appendChild(createElement('span', 'bracket', ']'));
@ -298,11 +279,7 @@ export class JsonExplorer {
const objectWrapperSpan = createElement('span'); const objectWrapperSpan = createElement('span');
// get constructor name and append it to wrapper span // get constructor name and append it to wrapper span
var constructorName = createElement( var constructorName = createElement('span', 'constructor-name', this.constructorName);
'span',
'constructor-name',
this.constructorName
);
objectWrapperSpan.appendChild(constructorName); objectWrapperSpan.appendChild(constructorName);
// if it's an array append the array specific elements like brackets and length // if it's an array append the array specific elements like brackets and length
@ -399,12 +376,7 @@ export class JsonExplorer {
let index = 0; let index = 0;
const addAChild = () => { const addAChild = () => {
const key = this.keys[index]; const key = this.keys[index];
const formatter = new JsonExplorer( const formatter = new JsonExplorer(this.json[key], this.open - 1, this.config, key);
this.json[key],
this.open - 1,
this.config,
key
);
children.appendChild(formatter.render()); children.appendChild(formatter.render());
index += 1; index += 1;
@ -421,12 +393,7 @@ export class JsonExplorer {
requestAnimationFrame(addAChild); requestAnimationFrame(addAChild);
} else { } else {
this.keys.forEach(key => { this.keys.forEach(key => {
const formatter = new JsonExplorer( const formatter = new JsonExplorer(this.json[key], this.open - 1, this.config, key);
this.json[key],
this.open - 1,
this.config,
key
);
children.appendChild(formatter.render()); children.appendChild(formatter.render());
}); });
} }
@ -437,9 +404,7 @@ export class JsonExplorer {
* Animated option is used when user triggers this via a click * Animated option is used when user triggers this via a click
*/ */
removeChildren(animated = false) { removeChildren(animated = false) {
const childrenElement = this.element.querySelector( const childrenElement = this.element.querySelector(`div.${cssClass('children')}`) as HTMLDivElement;
`div.${cssClass('children')}`
) as HTMLDivElement;
if (animated) { if (animated) {
let childrenRemoved = 0; let childrenRemoved = 0;

View File

@ -13,11 +13,7 @@ export class ManageDashboardsCtrl {
canMove = false; canMove = false;
hasFilters = false; hasFilters = false;
selectAllChecked = false; selectAllChecked = false;
starredFilterOptions = [ starredFilterOptions = [{ text: 'Filter by Starred', disabled: true }, { text: 'Yes' }, { text: 'No' }];
{ text: 'Filter by Starred', disabled: true },
{ text: 'Yes' },
{ text: 'No' },
];
selectedStarredFilter: any; selectedStarredFilter: any;
folderId?: number; folderId?: number;
@ -53,10 +49,7 @@ export class ManageDashboardsCtrl {
this.canMove = false; this.canMove = false;
this.canDelete = false; this.canDelete = false;
this.selectAllChecked = false; this.selectAllChecked = false;
this.hasFilters = this.hasFilters = this.query.query.length > 0 || this.query.tag.length > 0 || this.query.starred;
this.query.query.length > 0 ||
this.query.tag.length > 0 ||
this.query.starred;
if (!result) { if (!result) {
this.sections = []; this.sections = [];
@ -126,16 +119,10 @@ export class ManageDashboardsCtrl {
let text2; let text2;
if (folderCount > 0 && dashCount > 0) { if (folderCount > 0 && dashCount > 0) {
text += `selected folder${folderCount === 1 ? '' : 's'} and dashboard${ text += `selected folder${folderCount === 1 ? '' : 's'} and dashboard${dashCount === 1 ? '' : 's'}?`;
dashCount === 1 ? '' : 's' text2 = `All dashboards of the selected folder${folderCount === 1 ? '' : 's'} will also be deleted`;
}?`;
text2 = `All dashboards of the selected folder${
folderCount === 1 ? '' : 's'
} will also be deleted`;
} else if (folderCount > 0) { } else if (folderCount > 0) {
text += `selected folder${ text += `selected folder${folderCount === 1 ? '' : 's'} and all its dashboards?`;
folderCount === 1 ? '' : 's'
} and all its dashboards?`;
} else { } else {
text += `selected dashboard${dashCount === 1 ? '' : 's'}?`; text += `selected dashboard${dashCount === 1 ? '' : 's'}?`;
} }
@ -165,22 +152,16 @@ export class ManageDashboardsCtrl {
let msg; let msg;
if (folderCount > 0 && dashCount > 0) { if (folderCount > 0 && dashCount > 0) {
header = `Folder${folderCount === 1 ? '' : 's'} And Dashboard${ header = `Folder${folderCount === 1 ? '' : 's'} And Dashboard${dashCount === 1 ? '' : 's'} Deleted`;
dashCount === 1 ? '' : 's'
} Deleted`;
msg = `${folderCount} folder${folderCount === 1 ? '' : 's'} `; msg = `${folderCount} folder${folderCount === 1 ? '' : 's'} `;
msg += `and ${dashCount} dashboard${ msg += `and ${dashCount} dashboard${dashCount === 1 ? '' : 's'} has been deleted`;
dashCount === 1 ? '' : 's'
} has been deleted`;
} else if (folderCount > 0) { } else if (folderCount > 0) {
header = `Folder${folderCount === 1 ? '' : 's'} Deleted`; header = `Folder${folderCount === 1 ? '' : 's'} Deleted`;
if (folderCount === 1) { if (folderCount === 1) {
msg = `${folders[0].dashboard.title} has been deleted`; msg = `${folders[0].dashboard.title} has been deleted`;
} else { } else {
msg = `${folderCount} folder${ msg = `${folderCount} folder${folderCount === 1 ? '' : 's'} has been deleted`;
folderCount === 1 ? '' : 's'
} has been deleted`;
} }
} else if (dashCount > 0) { } else if (dashCount > 0) {
header = `Dashboard${dashCount === 1 ? '' : 's'} Deleted`; header = `Dashboard${dashCount === 1 ? '' : 's'} Deleted`;
@ -188,9 +169,7 @@ export class ManageDashboardsCtrl {
if (dashCount === 1) { if (dashCount === 1) {
msg = `${dashboards[0].dashboard.title} has been deleted`; msg = `${dashboards[0].dashboard.title} has been deleted`;
} else { } else {
msg = `${dashCount} dashboard${ msg = `${dashCount} dashboard${dashCount === 1 ? '' : 's'} has been deleted`;
dashCount === 1 ? '' : 's'
} has been deleted`;
} }
} }
@ -231,9 +210,7 @@ export class ManageDashboardsCtrl {
getTags() { getTags() {
return this.searchSrv.getDashboardTags().then(results => { return this.searchSrv.getDashboardTags().then(results => {
this.tagFilterOptions = [ this.tagFilterOptions = [{ term: 'Filter By Tag', disabled: true }].concat(results);
{ term: 'Filter By Tag', disabled: true },
].concat(results);
this.selectedTagFilter = this.tagFilterOptions[0]; this.selectedTagFilter = this.tagFilterOptions[0];
}); });
} }
@ -312,8 +289,7 @@ export class ManageDashboardsCtrl {
export function manageDashboardsDirective() { export function manageDashboardsDirective() {
return { return {
restrict: 'E', restrict: 'E',
templateUrl: templateUrl: 'public/app/core/components/manage_dashboards/manage_dashboards.html',
'public/app/core/components/manage_dashboards/manage_dashboards.html',
controller: ManageDashboardsCtrl, controller: ManageDashboardsCtrl,
bindToController: true, bindToController: true,
controllerAs: 'ctrl', controllerAs: 'ctrl',

View File

@ -63,9 +63,7 @@ export class OrgSwitchCtrl {
setUsingOrg(org) { setUsingOrg(org) {
return this.backendSrv.post('/api/user/using/' + org.orgId).then(() => { return this.backendSrv.post('/api/user/using/' + org.orgId).then(() => {
const re = /orgId=\d+/gi; const re = /orgId=\d+/gi;
this.setWindowLocationHref( this.setWindowLocationHref(this.getWindowLocationHref().replace(re, 'orgId=' + org.orgId));
this.getWindowLocationHref().replace(re, 'orgId=' + org.orgId)
);
}); });
} }

View File

@ -17,8 +17,7 @@ var template = `
/** @ngInject */ /** @ngInject */
export function queryPartEditorDirective($compile, templateSrv) { export function queryPartEditorDirective($compile, templateSrv) {
var paramTemplate = var paramTemplate = '<input type="text" class="hide input-mini tight-form-func-param"></input>';
'<input type="text" class="hide input-mini tight-form-func-param"></input>';
return { return {
restrict: 'E', restrict: 'E',
@ -102,9 +101,7 @@ export function queryPartEditorDirective($compile, templateSrv) {
} }
$scope.$apply(function() { $scope.$apply(function() {
$scope $scope.handleEvent({ $event: { name: 'get-param-options' } }).then(function(result) {
.handleEvent({ $event: { name: 'get-param-options' } })
.then(function(result) {
var dynamicOptions = _.map(result, function(op) { var dynamicOptions = _.map(result, function(op) {
return op.value; return op.value;
}); });
@ -136,9 +133,7 @@ export function queryPartEditorDirective($compile, templateSrv) {
} }
$scope.showActionsMenu = function() { $scope.showActionsMenu = function() {
$scope $scope.handleEvent({ $event: { name: 'get-part-actions' } }).then(res => {
.handleEvent({ $event: { name: 'get-part-actions' } })
.then(res => {
$scope.partActions = res; $scope.partActions = res;
}); });
}; };
@ -157,12 +152,8 @@ export function queryPartEditorDirective($compile, templateSrv) {
$('<span>, </span>').appendTo($paramsContainer); $('<span>, </span>').appendTo($paramsContainer);
} }
var paramValue = templateSrv.highlightVariablesAsHtml( var paramValue = templateSrv.highlightVariablesAsHtml(part.params[index]);
part.params[index] var $paramLink = $('<a class="graphite-func-param-link pointer">' + paramValue + '</a>');
);
var $paramLink = $(
'<a class="graphite-func-param-link pointer">' + paramValue + '</a>'
);
var $input = $(paramTemplate); var $input = $(paramTemplate);
$paramLink.appendTo($paramsContainer); $paramLink.appendTo($paramsContainer);

View File

@ -17,12 +17,7 @@ export class SearchCtrl {
initialFolderFilterTitle: string; initialFolderFilterTitle: string;
/** @ngInject */ /** @ngInject */
constructor( constructor($scope, private $location, private $timeout, private searchSrv: SearchSrv) {
$scope,
private $location,
private $timeout,
private searchSrv: SearchSrv
) {
appEvents.on('show-dash-search', this.openSearch.bind(this), $scope); appEvents.on('show-dash-search', this.openSearch.bind(this), $scope);
appEvents.on('hide-dash-search', this.closeSearch.bind(this), $scope); appEvents.on('hide-dash-search', this.closeSearch.bind(this), $scope);
@ -75,9 +70,7 @@ export class SearchCtrl {
if (currentItem) { if (currentItem) {
if (currentItem.dashboardIndex !== undefined) { if (currentItem.dashboardIndex !== undefined) {
const selectedDash = this.results[currentItem.folderIndex].items[ const selectedDash = this.results[currentItem.folderIndex].items[currentItem.dashboardIndex];
currentItem.dashboardIndex
];
if (selectedDash) { if (selectedDash) {
this.$location.search({}); this.$location.search({});
@ -105,9 +98,7 @@ export class SearchCtrl {
if (currentItem) { if (currentItem) {
if (currentItem.dashboardIndex !== undefined) { if (currentItem.dashboardIndex !== undefined) {
this.results[currentItem.folderIndex].items[ this.results[currentItem.folderIndex].items[currentItem.dashboardIndex].selected = false;
currentItem.dashboardIndex
].selected = false;
} else { } else {
this.results[currentItem.folderIndex].selected = false; this.results[currentItem.folderIndex].selected = false;
} }
@ -123,10 +114,7 @@ export class SearchCtrl {
this.selectedIndex = (newIndex %= max) < 0 ? newIndex + max : newIndex; this.selectedIndex = (newIndex %= max) < 0 ? newIndex + max : newIndex;
const selectedItem = flattenedResult[this.selectedIndex]; const selectedItem = flattenedResult[this.selectedIndex];
if ( if (selectedItem.dashboardIndex === undefined && this.results[selectedItem.folderIndex].id === 0) {
selectedItem.dashboardIndex === undefined &&
this.results[selectedItem.folderIndex].id === 0
) {
this.moveSelection(direction); this.moveSelection(direction);
return; return;
} }
@ -137,9 +125,7 @@ export class SearchCtrl {
return; return;
} }
this.results[selectedItem.folderIndex].items[ this.results[selectedItem.folderIndex].items[selectedItem.dashboardIndex].selected = true;
selectedItem.dashboardIndex
].selected = true;
return; return;
} }
@ -167,9 +153,7 @@ export class SearchCtrl {
queryHasNoFilters() { queryHasNoFilters() {
var query = this.query; var query = this.query;
return ( return query.query === '' && query.starred === false && query.tag.length === 0;
query.query === '' && query.starred === false && query.tag.length === 0
);
} }
filterByTag(tag) { filterByTag(tag) {

View File

@ -13,25 +13,12 @@ export class SideMenuCtrl {
isOpenMobile: boolean; isOpenMobile: boolean;
/** @ngInject */ /** @ngInject */
constructor( constructor(private $scope, private $rootScope, private $location, private contextSrv, private $timeout) {
private $scope,
private $rootScope,
private $location,
private contextSrv,
private $timeout
) {
this.isSignedIn = contextSrv.isSignedIn; this.isSignedIn = contextSrv.isSignedIn;
this.user = contextSrv.user; this.user = contextSrv.user;
this.mainLinks = _.filter( this.mainLinks = _.filter(config.bootData.navTree, item => !item.hideFromMenu);
config.bootData.navTree, this.bottomNav = _.filter(config.bootData.navTree, item => item.hideFromMenu);
item => !item.hideFromMenu this.loginUrl = 'login?redirect=' + encodeURIComponent(this.$location.path());
);
this.bottomNav = _.filter(
config.bootData.navTree,
item => item.hideFromMenu
);
this.loginUrl =
'login?redirect=' + encodeURIComponent(this.$location.path());
if (contextSrv.user.orgCount > 1) { if (contextSrv.user.orgCount > 1) {
let profileNode = _.find(this.bottomNav, { id: 'profile' }); let profileNode = _.find(this.bottomNav, { id: 'profile' });
@ -41,8 +28,7 @@ export class SideMenuCtrl {
} }
this.$scope.$on('$routeChangeSuccess', () => { this.$scope.$on('$routeChangeSuccess', () => {
this.loginUrl = this.loginUrl = 'login?redirect=' + encodeURIComponent(this.$location.path());
'login?redirect=' + encodeURIComponent(this.$location.path());
}); });
} }

View File

@ -30,9 +30,7 @@ export class TeamPickerCtrl {
searchGroups(query: string) { searchGroups(query: string) {
return Promise.resolve( return Promise.resolve(
this.backendSrv this.backendSrv.get('/api/teams/search?perpage=10&page=1&query=' + query).then(result => {
.get('/api/teams/search?perpage=10&page=1&query=' + query)
.then(result => {
return _.map(result.teams, ug => { return _.map(result.teams, ug => {
return { text: ug.name, value: ug }; return { text: ug.name, value: ug };
}); });

View File

@ -26,9 +26,7 @@ export class UserPickerCtrl {
searchUsers(query: string) { searchUsers(query: string) {
return Promise.resolve( return Promise.resolve(
this.backendSrv this.backendSrv.get('/api/users/search?perpage=10&page=1&query=' + query).then(result => {
.get('/api/users/search?perpage=10&page=1&query=' + query)
.then(result => {
return _.map(result.users, user => { return _.map(result.users, user => {
return { text: user.login + ' - ' + user.email, value: user }; return { text: user.login + ' - ' + user.email, value: user };
}); });

View File

@ -28,10 +28,7 @@ export class InspectCtrl {
} }
if (model.error.config && model.error.config.params) { if (model.error.config && model.error.config.params) {
$scope.request_parameters = _.map(model.error.config.params, function( $scope.request_parameters = _.map(model.error.config.params, function(value, key) {
value,
key
) {
return { key: key, value: value }; return { key: key, value: value };
}); });
} }
@ -46,14 +43,9 @@ export class InspectCtrl {
$scope.editor.index = 2; $scope.editor.index = 2;
if (_.isString(model.error.config.data)) { if (_.isString(model.error.config.data)) {
$scope.request_parameters = this.getParametersFromQueryString( $scope.request_parameters = this.getParametersFromQueryString(model.error.config.data);
model.error.config.data
);
} else { } else {
$scope.request_parameters = _.map(model.error.config.data, function( $scope.request_parameters = _.map(model.error.config.data, function(value, key) {
value,
key
) {
return { key: key, value: angular.toJson(value, true) }; return { key: key, value: angular.toJson(value, true) };
}); });
} }

View File

@ -16,9 +16,7 @@ export class InvitedCtrl {
}; };
$scope.init = function() { $scope.init = function() {
backendSrv backendSrv.get('/api/user/invite/' + $routeParams.code).then(function(invite) {
.get('/api/user/invite/' + $routeParams.code)
.then(function(invite) {
$scope.formModel.name = invite.name; $scope.formModel.name = invite.name;
$scope.formModel.email = invite.email; $scope.formModel.email = invite.email;
$scope.formModel.username = invite.email; $scope.formModel.username = invite.email;
@ -34,9 +32,7 @@ export class InvitedCtrl {
return; return;
} }
backendSrv backendSrv.post('/api/user/invite/complete', $scope.formModel).then(function() {
.post('/api/user/invite/complete', $scope.formModel)
.then(function() {
window.location.href = config.appSubUrl + '/'; window.location.href = config.appSubUrl + '/';
}); });
}; };

View File

@ -5,8 +5,7 @@ export class JsonEditorCtrl {
/** @ngInject */ /** @ngInject */
constructor($scope) { constructor($scope) {
$scope.json = angular.toJson($scope.object, true); $scope.json = angular.toJson($scope.object, true);
$scope.canUpdate = $scope.canUpdate = $scope.updateHandler !== void 0 && $scope.contextSrv.isEditor;
$scope.updateHandler !== void 0 && $scope.contextSrv.isEditor;
$scope.update = function() { $scope.update = function() {
var newObject = angular.fromJson($scope.json); var newObject = angular.fromJson($scope.json);

View File

@ -48,9 +48,7 @@ export class LoginCtrl {
return; return;
} }
backendSrv backendSrv.post('/api/user/signup', $scope.formModel).then(function(result) {
.post('/api/user/signup', $scope.formModel)
.then(function(result) {
if (result.status === 'SignUpCreated') { if (result.status === 'SignUpCreated') {
$location.path('/signup').search({ email: $scope.formModel.email }); $location.path('/signup').search({ email: $scope.formModel.email });
} else { } else {

View File

@ -17,10 +17,7 @@ export class ResetPasswordCtrl {
main: { main: {
icon: 'gicon gicon-branding', icon: 'gicon gicon-branding',
subTitle: 'Reset your Grafana password', subTitle: 'Reset your Grafana password',
breadcrumbs: [ breadcrumbs: [{ title: 'Login', url: '/login' }, { title: 'Reset Password' }],
{ title: 'Login', url: '/login' },
{ title: 'Reset Password' },
],
}, },
}; };
@ -28,9 +25,7 @@ export class ResetPasswordCtrl {
if (!$scope.sendResetForm.$valid) { if (!$scope.sendResetForm.$valid) {
return; return;
} }
backendSrv backendSrv.post('/api/user/password/send-reset-email', $scope.formModel).then(function() {
.post('/api/user/password/send-reset-email', $scope.formModel)
.then(function() {
$scope.mode = 'email-sent'; $scope.mode = 'email-sent';
}); });
}; };
@ -45,9 +40,7 @@ export class ResetPasswordCtrl {
return; return;
} }
backendSrv backendSrv.post('/api/user/password/reset', $scope.formModel).then(function() {
.post('/api/user/password/reset', $scope.formModel)
.then(function() {
$location.path('login'); $location.path('login');
}); });
}; };

View File

@ -5,12 +5,7 @@ import coreModule from '../core_module';
export class SignUpCtrl { export class SignUpCtrl {
/** @ngInject */ /** @ngInject */
constructor( constructor(private $scope: any, private backendSrv: any, $location: any, contextSrv: any) {
private $scope: any,
private backendSrv: any,
$location: any,
contextSrv: any
) {
contextSrv.sidemenu = false; contextSrv.sidemenu = false;
$scope.ctrl = this; $scope.ctrl = this;
@ -44,12 +39,9 @@ export class SignUpCtrl {
return; return;
} }
this.backendSrv this.backendSrv.post('/api/user/signup/step2', this.$scope.formModel).then(rsp => {
.post('/api/user/signup/step2', this.$scope.formModel)
.then(rsp => {
if (rsp.code === 'redirect-to-select-org') { if (rsp.code === 'redirect-to-select-org') {
window.location.href = window.location.href = config.appSubUrl + '/profile/select-org?signup=1';
config.appSubUrl + '/profile/select-org?signup=1';
} else { } else {
window.location.href = config.appSubUrl + '/'; window.location.href = config.appSubUrl + '/';
} }

View File

@ -118,14 +118,7 @@ function editorCheckbox($compile, $interpolate) {
var model = $interpolate(attrs.model)(scope); var model = $interpolate(attrs.model)(scope);
var ngchange = attrs.change ? ' ng-change="' + attrs.change + '"' : ''; var ngchange = attrs.change ? ' ng-change="' + attrs.change + '"' : '';
var tip = attrs.tip ? ' <tip>' + attrs.tip + '</tip>' : ''; var tip = attrs.tip ? ' <tip>' + attrs.tip + '</tip>' : '';
var label = var label = '<label for="' + scope.$id + model + '" class="checkbox-label">' + text + tip + '</label>';
'<label for="' +
scope.$id +
model +
'" class="checkbox-label">' +
text +
tip +
'</label>';
var template = var template =
'<input class="cr1" id="' + '<input class="cr1" id="' +
@ -155,12 +148,7 @@ function editorCheckbox($compile, $interpolate) {
function gfDropdown($parse, $compile, $timeout) { function gfDropdown($parse, $compile, $timeout) {
function buildTemplate(items, placement?) { function buildTemplate(items, placement?) {
var upclass = placement === 'top' ? 'dropup' : ''; var upclass = placement === 'top' ? 'dropup' : '';
var ul = [ var ul = ['<ul class="dropdown-menu ' + upclass + '" role="menu" aria-labelledby="drop1">', '</ul>'];
'<ul class="dropdown-menu ' +
upclass +
'" role="menu" aria-labelledby="drop1">',
'</ul>',
];
for (let index = 0; index < items.length; index++) { for (let index = 0; index < items.length; index++) {
let item = items[index]; let item = items[index];
@ -172,9 +160,7 @@ function gfDropdown($parse, $compile, $timeout) {
var li = var li =
'<li' + '<li' +
(item.submenu && item.submenu.length (item.submenu && item.submenu.length ? ' class="dropdown-submenu"' : '') +
? ' class="dropdown-submenu"'
: '') +
'>' + '>' +
'<a tabindex="-1" ng-href="' + '<a tabindex="-1" ng-href="' +
(item.href || '') + (item.href || '') +
@ -205,9 +191,7 @@ function gfDropdown($parse, $compile, $timeout) {
items = getter(scope); items = getter(scope);
$timeout(function() { $timeout(function() {
var placement = iElement.data('placement'); var placement = iElement.data('placement');
var dropdown = angular.element( var dropdown = angular.element(buildTemplate(items, placement).join(''));
buildTemplate(items, placement).join('')
);
dropdown.insertAfter(iElement); dropdown.insertAfter(iElement);
$compile(iElement.next('ul.dropdown-menu'))(scope); $compile(iElement.next('ul.dropdown-menu'))(scope);
}); });

View File

@ -47,10 +47,7 @@ function rebuildOnChange($animate) {
} }
} }
scope.$watch(attrs.property, function rebuildOnChangeAction( scope.$watch(attrs.property, function rebuildOnChangeAction(value, oldValue) {
value,
oldValue
) {
if (childScope && value !== oldValue) { if (childScope && value !== oldValue) {
cleanUp(); cleanUp();
} }
@ -58,9 +55,7 @@ function rebuildOnChange($animate) {
if (!childScope && (value || attrs.showNull)) { if (!childScope && (value || attrs.showNull)) {
transclude(function(clone, newScope) { transclude(function(clone, newScope) {
childScope = newScope; childScope = newScope;
clone[clone.length++] = document.createComment( clone[clone.length++] = document.createComment(' end rebuild on change ');
' end rebuild on change '
);
block = { clone: clone }; block = { clone: clone };
$animate.enter(clone, elem.parent(), elem); $animate.enter(clone, elem.parent(), elem);
}); });

View File

@ -14,12 +14,7 @@ export class LiveSrv {
getWebSocketUrl() { getWebSocketUrl() {
var l = window.location; var l = window.location;
return ( return (l.protocol === 'https:' ? 'wss://' : 'ws://') + l.host + config.appSubUrl + '/ws';
(l.protocol === 'https:' ? 'wss://' : 'ws://') +
l.host +
config.appSubUrl +
'/ws'
);
} }
getConnection() { getConnection() {

View File

@ -29,21 +29,9 @@ export class Profiler {
); );
$rootScope.onAppEvent('refresh', this.refresh.bind(this), $rootScope); $rootScope.onAppEvent('refresh', this.refresh.bind(this), $rootScope);
$rootScope.onAppEvent( $rootScope.onAppEvent('dashboard-fetch-end', this.dashboardFetched.bind(this), $rootScope);
'dashboard-fetch-end', $rootScope.onAppEvent('dashboard-initialized', this.dashboardInitialized.bind(this), $rootScope);
this.dashboardFetched.bind(this), $rootScope.onAppEvent('panel-initialized', this.panelInitialized.bind(this), $rootScope);
$rootScope
);
$rootScope.onAppEvent(
'dashboard-initialized',
this.dashboardInitialized.bind(this),
$rootScope
);
$rootScope.onAppEvent(
'panel-initialized',
this.panelInitialized.bind(this),
$rootScope
);
} }
refresh() { refresh() {
@ -70,21 +58,12 @@ export class Profiler {
dashboardInitialized() { dashboardInitialized() {
setTimeout(() => { setTimeout(() => {
console.log( console.log('Dashboard::Performance Total Digests: ' + this.digestCounter);
'Dashboard::Performance Total Digests: ' + this.digestCounter console.log('Dashboard::Performance Total Watchers: ' + this.getTotalWatcherCount());
); console.log('Dashboard::Performance Total ScopeCount: ' + this.scopeCount);
console.log(
'Dashboard::Performance Total Watchers: ' + this.getTotalWatcherCount()
);
console.log(
'Dashboard::Performance Total ScopeCount: ' + this.scopeCount
);
var timeTaken = var timeTaken = this.timings.lastPanelInitializedAt - this.timings.dashboardLoadStart;
this.timings.lastPanelInitializedAt - this.timings.dashboardLoadStart; console.log('Dashboard::Performance All panels initialized in ' + timeTaken + ' ms');
console.log(
'Dashboard::Performance All panels initialized in ' + timeTaken + ' ms'
);
// measure digest performance // measure digest performance
var rootDigestStart = window.performance.now(); var rootDigestStart = window.performance.now();
@ -92,10 +71,7 @@ export class Profiler {
this.$rootScope.$apply(); this.$rootScope.$apply();
} }
console.log( console.log('Dashboard::Performance Root Digest ' + (window.performance.now() - rootDigestStart) / 30);
'Dashboard::Performance Root Digest ' +
(window.performance.now() - rootDigestStart) / 30
);
}, 3000); }, 3000);
} }

View File

@ -18,9 +18,7 @@ export class LoadDashboardCtrl {
return; return;
} }
dashboardLoaderSrv dashboardLoaderSrv.loadDashboard($routeParams.type, $routeParams.slug).then(function(result) {
.loadDashboard($routeParams.type, $routeParams.slug)
.then(function(result) {
if ($routeParams.keepRows) { if ($routeParams.keepRows) {
result.meta.keepRows = true; result.meta.keepRows = true;
} }

View File

@ -64,8 +64,7 @@ function setupAngularRoutes($routeProvider, $locationProvider) {
pageClass: 'page-dashboard', pageClass: 'page-dashboard',
}) })
.when('/dashboard/import', { .when('/dashboard/import', {
templateUrl: templateUrl: 'public/app/features/dashboard/partials/dashboard_import.html',
'public/app/features/dashboard/partials/dashboard_import.html',
controller: 'DashboardImportCtrl', controller: 'DashboardImportCtrl',
controllerAs: 'ctrl', controllerAs: 'ctrl',
}) })
@ -95,20 +94,17 @@ function setupAngularRoutes($routeProvider, $locationProvider) {
controllerAs: 'ctrl', controllerAs: 'ctrl',
}) })
.when('/dashboards/folder/:folderId/:slug/permissions', { .when('/dashboards/folder/:folderId/:slug/permissions', {
templateUrl: templateUrl: 'public/app/features/dashboard/partials/folder_permissions.html',
'public/app/features/dashboard/partials/folder_permissions.html',
controller: 'FolderPermissionsCtrl', controller: 'FolderPermissionsCtrl',
controllerAs: 'ctrl', controllerAs: 'ctrl',
}) })
.when('/dashboards/folder/:folderId/:slug/settings', { .when('/dashboards/folder/:folderId/:slug/settings', {
templateUrl: templateUrl: 'public/app/features/dashboard/partials/folder_settings.html',
'public/app/features/dashboard/partials/folder_settings.html',
controller: 'FolderSettingsCtrl', controller: 'FolderSettingsCtrl',
controllerAs: 'ctrl', controllerAs: 'ctrl',
}) })
.when('/dashboards/folder/:folderId/:slug', { .when('/dashboards/folder/:folderId/:slug', {
templateUrl: templateUrl: 'public/app/features/dashboard/partials/folder_dashboards.html',
'public/app/features/dashboard/partials/folder_dashboards.html',
controller: 'FolderDashboardsCtrl', controller: 'FolderDashboardsCtrl',
controllerAs: 'ctrl', controllerAs: 'ctrl',
}) })
@ -281,22 +277,19 @@ function setupAngularRoutes($routeProvider, $locationProvider) {
resolve: loadAlertingBundle, resolve: loadAlertingBundle,
}) })
.when('/alerting/notifications', { .when('/alerting/notifications', {
templateUrl: templateUrl: 'public/app/features/alerting/partials/notifications_list.html',
'public/app/features/alerting/partials/notifications_list.html',
controller: 'AlertNotificationsListCtrl', controller: 'AlertNotificationsListCtrl',
controllerAs: 'ctrl', controllerAs: 'ctrl',
resolve: loadAlertingBundle, resolve: loadAlertingBundle,
}) })
.when('/alerting/notification/new', { .when('/alerting/notification/new', {
templateUrl: templateUrl: 'public/app/features/alerting/partials/notification_edit.html',
'public/app/features/alerting/partials/notification_edit.html',
controller: 'AlertNotificationEditCtrl', controller: 'AlertNotificationEditCtrl',
controllerAs: 'ctrl', controllerAs: 'ctrl',
resolve: loadAlertingBundle, resolve: loadAlertingBundle,
}) })
.when('/alerting/notification/:id/edit', { .when('/alerting/notification/:id/edit', {
templateUrl: templateUrl: 'public/app/features/alerting/partials/notification_edit.html',
'public/app/features/alerting/partials/notification_edit.html',
controller: 'AlertNotificationEditCtrl', controller: 'AlertNotificationEditCtrl',
controllerAs: 'ctrl', controllerAs: 'ctrl',
resolve: loadAlertingBundle, resolve: loadAlertingBundle,

View File

@ -38,15 +38,9 @@ export class AlertSrv {
this.$rootScope this.$rootScope
); );
appEvents.on('alert-warning', options => appEvents.on('alert-warning', options => this.set(options[0], options[1], 'warning', 5000));
this.set(options[0], options[1], 'warning', 5000) appEvents.on('alert-success', options => this.set(options[0], options[1], 'success', 3000));
); appEvents.on('alert-error', options => this.set(options[0], options[1], 'error', 7000));
appEvents.on('alert-success', options =>
this.set(options[0], options[1], 'success', 3000)
);
appEvents.on('alert-error', options =>
this.set(options[0], options[1], 'error', 7000)
);
appEvents.on('confirm-modal', this.showConfirmModal.bind(this)); appEvents.on('confirm-modal', this.showConfirmModal.bind(this));
} }
@ -114,8 +108,7 @@ export class AlertSrv {
}; };
scope.updateConfirmText = function(value) { scope.updateConfirmText = function(value) {
scope.confirmTextValid = scope.confirmTextValid = payload.confirmText.toLowerCase() === value.toLowerCase();
payload.confirmText.toLowerCase() === value.toLowerCase();
}; };
scope.title = payload.title; scope.title = payload.title;

View File

@ -11,13 +11,7 @@ export class BackendSrv {
private noBackendCache: boolean; private noBackendCache: boolean;
/** @ngInject */ /** @ngInject */
constructor( constructor(private $http, private alertSrv, private $q, private $timeout, private contextSrv) {}
private $http,
private alertSrv,
private $q,
private $timeout,
private contextSrv
) {}
get(url, params?) { get(url, params?) {
return this.request({ method: 'GET', url: url, params: params }); return this.request({ method: 'GET', url: url, params: params });
@ -109,11 +103,7 @@ export class BackendSrv {
}, },
err => { err => {
// handle unauthorized // handle unauthorized
if ( if (err.status === 401 && this.contextSrv.user.isSignedIn && firstAttempt) {
err.status === 401 &&
this.contextSrv.user.isSignedIn &&
firstAttempt
) {
return this.loginPing().then(() => { return this.loginPing().then(() => {
options.retry = 1; options.retry = 1;
return this.request(options); return this.request(options);
@ -295,17 +285,14 @@ export class BackendSrv {
const tasks = []; const tasks = [];
for (let slug of dashboardSlugs) { for (let slug of dashboardSlugs) {
tasks.push( tasks.push(this.createTask(this.moveDashboard.bind(this), true, slug, toFolder));
this.createTask(this.moveDashboard.bind(this), true, slug, toFolder)
);
} }
return this.executeInOrder(tasks, []).then(result => { return this.executeInOrder(tasks, []).then(result => {
return { return {
totalCount: result.length, totalCount: result.length,
successCount: _.filter(result, { succeeded: true }).length, successCount: _.filter(result, { succeeded: true }).length,
alreadyInFolderCount: _.filter(result, { alreadyInFolder: true }) alreadyInFolderCount: _.filter(result, { alreadyInFolder: true }).length,
.length,
}; };
}); });
} }
@ -316,10 +303,7 @@ export class BackendSrv {
this.getDashboard('db', slug).then(fullDash => { this.getDashboard('db', slug).then(fullDash => {
const model = new DashboardModel(fullDash.dashboard, fullDash.meta); const model = new DashboardModel(fullDash.dashboard, fullDash.meta);
if ( if ((!fullDash.meta.folderId && toFolder.id === 0) || fullDash.meta.folderId === toFolder.id) {
(!fullDash.meta.folderId && toFolder.id === 0) ||
fullDash.meta.folderId === toFolder.id
) {
deferred.resolve({ alreadyInFolder: true }); deferred.resolve({ alreadyInFolder: true });
return; return;
} }

View File

@ -51,10 +51,7 @@ export class ContextSrv {
} }
isGrafanaVisible() { isGrafanaVisible() {
return !!( return !!(document.visibilityState === undefined || document.visibilityState === 'visible');
document.visibilityState === undefined ||
document.visibilityState === 'visible'
);
} }
toggleSideMenu() { toggleSideMenu() {

View File

@ -25,10 +25,7 @@ class DynamicDirectiveSrv {
} }
if (!directiveInfo.fn.registered) { if (!directiveInfo.fn.registered) {
coreModule.directive( coreModule.directive(attrs.$normalize(directiveInfo.name), directiveInfo.fn);
attrs.$normalize(directiveInfo.name),
directiveInfo.fn
);
directiveInfo.fn.registered = true; directiveInfo.fn.registered = true;
} }
@ -36,10 +33,7 @@ class DynamicDirectiveSrv {
}) })
.catch(err => { .catch(err => {
console.log('Plugin load:', err); console.log('Plugin load:', err);
this.$rootScope.appEvent('alert-error', [ this.$rootScope.appEvent('alert-error', ['Plugin error', err.toString()]);
'Plugin error',
err.toString(),
]);
}); });
} }

View File

@ -19,9 +19,7 @@ export class GlobalEventSrv {
const appSubUrl = this.appSubUrl; const appSubUrl = this.appSubUrl;
const stripExtraChars = appSubUrl.endsWith('/') ? 1 : 0; const stripExtraChars = appSubUrl.endsWith('/') ? 1 : 0;
const urlWithoutBase = const urlWithoutBase =
url.length > 0 && url.indexOf(appSubUrl) === 0 url.length > 0 && url.indexOf(appSubUrl) === 0 ? url.slice(appSubUrl.length - stripExtraChars) : url;
? url.slice(appSubUrl.length - stripExtraChars)
: url;
return urlWithoutBase; return urlWithoutBase;
} }

View File

@ -88,10 +88,7 @@ function applyFunctions(obj, scope, propsConfig?) {
* ensures that when function is called from a React component * ensures that when function is called from a React component
* the Angular digest cycle is run * the Angular digest cycle is run
*/ */
prev[key] = prev[key] = angular.isFunction(value) && config.wrapApply !== false ? applied(value, scope) : value;
angular.isFunction(value) && config.wrapApply !== false
? applied(value, scope)
: value;
return prev; return prev;
}, {}); }, {});
@ -167,8 +164,7 @@ function findAttribute(attrs, propName) {
// get watch depth of prop (string or array) // get watch depth of prop (string or array)
function getPropWatchDepth(defaultWatch, prop) { function getPropWatchDepth(defaultWatch, prop) {
var customWatchDepth = var customWatchDepth = Array.isArray(prop) && angular.isObject(prop[1]) && prop[1].watchDepth;
Array.isArray(prop) && angular.isObject(prop[1]) && prop[1].watchDepth;
return customWatchDepth || defaultWatch; return customWatchDepth || defaultWatch;
} }
@ -205,9 +201,7 @@ var reactComponent = function($injector) {
}; };
// If there are props, re-render when they change // If there are props, re-render when they change
attrs.props attrs.props ? watchProps(attrs.watchDepth, scope, [attrs.props], renderMyComponent) : renderMyComponent();
? watchProps(attrs.watchDepth, scope, [attrs.props], renderMyComponent)
: renderMyComponent();
// cleanup when scope is destroyed // cleanup when scope is destroyed
scope.$on('$destroy', function() { scope.$on('$destroy', function() {
@ -215,10 +209,7 @@ var reactComponent = function($injector) {
ReactDOM.unmountComponentAtNode(elem[0]); ReactDOM.unmountComponentAtNode(elem[0]);
} else { } else {
scope.$eval(attrs.onScopeDestroy, { scope.$eval(attrs.onScopeDestroy, {
unmountComponent: ReactDOM.unmountComponentAtNode.bind( unmountComponent: ReactDOM.unmountComponentAtNode.bind(this, elem[0]),
this,
elem[0]
),
}); });
} }
}); });
@ -282,20 +273,11 @@ var reactDirective = function($injector) {
// watch each property name and trigger an update whenever something changes, // watch each property name and trigger an update whenever something changes,
// to update scope.props with new values // to update scope.props with new values
var propExpressions = props.map(function(prop) { var propExpressions = props.map(function(prop) {
return Array.isArray(prop) return Array.isArray(prop) ? [attrs[getPropName(prop)], getPropConfig(prop)] : attrs[prop];
? [attrs[getPropName(prop)], getPropConfig(prop)]
: attrs[prop];
}); });
// If we don't have any props, then our watch statement won't fire. // If we don't have any props, then our watch statement won't fire.
props.length props.length ? watchProps(attrs.watchDepth, scope, propExpressions, renderMyComponent) : renderMyComponent();
? watchProps(
attrs.watchDepth,
scope,
propExpressions,
renderMyComponent
)
: renderMyComponent();
// cleanup when scope is destroyed // cleanup when scope is destroyed
scope.$on('$destroy', function() { scope.$on('$destroy', function() {
@ -303,10 +285,7 @@ var reactDirective = function($injector) {
ReactDOM.unmountComponentAtNode(elem[0]); ReactDOM.unmountComponentAtNode(elem[0]);
} else { } else {
scope.$eval(attrs.onScopeDestroy, { scope.$eval(attrs.onScopeDestroy, {
unmountComponent: ReactDOM.unmountComponentAtNode.bind( unmountComponent: ReactDOM.unmountComponentAtNode.bind(this, elem[0]),
this,
elem[0]
),
}); });
} }
}); });

View File

@ -1,10 +1,4 @@
import { import { describe, beforeEach, it, expect, angularMocks } from 'test/lib/common';
describe,
beforeEach,
it,
expect,
angularMocks,
} from 'test/lib/common';
import 'app/core/services/backend_srv'; import 'app/core/services/backend_srv';
describe('backend_srv', function() { describe('backend_srv', function() {

View File

@ -20,12 +20,9 @@ describe('DateMath', () => {
expect(dateMath.parse('now&1d')).toBe(undefined); expect(dateMath.parse('now&1d')).toBe(undefined);
}); });
it( it('should return undefined if I pass a unit besides' + spans.toString(), () => {
'should return undefined if I pass a unit besides' + spans.toString(),
() => {
expect(dateMath.parse('now+5f')).toBe(undefined); expect(dateMath.parse('now+5f')).toBe(undefined);
} });
);
it('should return undefined if rounding unit is not 1', () => { it('should return undefined if rounding unit is not 1', () => {
expect(dateMath.parse('now/2y')).toBe(undefined); expect(dateMath.parse('now/2y')).toBe(undefined);
@ -51,17 +48,7 @@ describe('DateMath', () => {
it('now/d on a utc dashboard should be start of the current day in UTC time', () => { it('now/d on a utc dashboard should be start of the current day in UTC time', () => {
var today = new Date(); var today = new Date();
var expected = new Date( var expected = new Date(Date.UTC(today.getUTCFullYear(), today.getUTCMonth(), today.getUTCDate(), 0, 0, 0, 0));
Date.UTC(
today.getUTCFullYear(),
today.getUTCMonth(),
today.getUTCDate(),
0,
0,
0,
0
)
);
var startOfDay = dateMath.parse('now/d', false, 'utc').valueOf(); var startOfDay = dateMath.parse('now/d', false, 'utc').valueOf();
expect(startOfDay).toBe(expected.getTime()); expect(startOfDay).toBe(expected.getTime());
@ -82,15 +69,11 @@ describe('DateMath', () => {
var thenEx = anchor + '||-5' + span; var thenEx = anchor + '||-5' + span;
it('should return 5' + span + ' ago', () => { it('should return 5' + span + ' ago', () => {
expect(dateMath.parse(nowEx).format(format)).toEqual( expect(dateMath.parse(nowEx).format(format)).toEqual(now.subtract(5, span).format(format));
now.subtract(5, span).format(format)
);
}); });
it('should return 5' + span + ' before ' + anchor, () => { it('should return 5' + span + ' before ' + anchor, () => {
expect(dateMath.parse(thenEx).format(format)).toEqual( expect(dateMath.parse(thenEx).format(format)).toEqual(anchored.subtract(5, span).format(format));
anchored.subtract(5, span).format(format)
);
}); });
}); });
@ -109,15 +92,11 @@ describe('DateMath', () => {
_.each(spans, span => { _.each(spans, span => {
it('should round now to the beginning of the ' + span, function() { it('should round now to the beginning of the ' + span, function() {
expect(dateMath.parse('now/' + span).format(format)).toEqual( expect(dateMath.parse('now/' + span).format(format)).toEqual(now.startOf(span).format(format));
now.startOf(span).format(format)
);
}); });
it('should round now to the end of the ' + span, function() { it('should round now to the end of the ' + span, function() {
expect(dateMath.parse('now/' + span, true).format(format)).toEqual( expect(dateMath.parse('now/' + span, true).format(format)).toEqual(now.endOf(span).format(format));
now.endOf(span).format(format)
);
}); });
}); });

View File

@ -34,8 +34,7 @@ describe('unit format menu', function() {
function describeValueFormat(desc, value, tickSize, tickDecimals, result) { function describeValueFormat(desc, value, tickSize, tickDecimals, result) {
describe('value format: ' + desc, function() { describe('value format: ' + desc, function() {
it('should translate ' + value + ' as ' + result, function() { it('should translate ' + value + ' as ' + result, function() {
var scaledDecimals = var scaledDecimals = tickDecimals - Math.floor(Math.log(tickSize) / Math.LN10);
tickDecimals - Math.floor(Math.log(tickSize) / Math.LN10);
var str = kbn.valueFormats[desc](value, tickDecimals, scaledDecimals); var str = kbn.valueFormats[desc](value, tickDecimals, scaledDecimals);
expect(str).toBe(result); expect(str).toBe(result);
}); });
@ -342,14 +341,10 @@ describe('duration', function() {
}); });
it('too many decimals', function() { it('too many decimals', function() {
var str = kbn.toDuration(38898367008, 20, 'millisecond'); var str = kbn.toDuration(38898367008, 20, 'millisecond');
expect(str).toBe( expect(str).toBe('1 year, 2 months, 3 weeks, 4 days, 5 hours, 6 minutes, 7 seconds, 8 milliseconds');
'1 year, 2 months, 3 weeks, 4 days, 5 hours, 6 minutes, 7 seconds, 8 milliseconds'
);
}); });
it('floating point error', function() { it('floating point error', function() {
var str = kbn.toDuration(36993906007, 8, 'millisecond'); var str = kbn.toDuration(36993906007, 8, 'millisecond');
expect(str).toBe( expect(str).toBe('1 year, 2 months, 0 weeks, 3 days, 4 hours, 5 minutes, 6 seconds, 7 milliseconds');
'1 year, 2 months, 0 weeks, 3 days, 4 hours, 5 minutes, 6 seconds, 7 milliseconds'
);
}); });
}); });

View File

@ -567,9 +567,5 @@ function createCtrlWithStubs(searchResponse: any, tags?: any) {
}, },
}; };
return new ManageDashboardsCtrl( return new ManageDashboardsCtrl({}, { getNav: () => {} }, <SearchSrv>searchSrvStub);
{},
{ getNav: () => {} },
<SearchSrv>searchSrvStub
);
} }

View File

@ -25,8 +25,7 @@ describe('OrgSwitcher', () => {
const orgSwitcherCtrl = new OrgSwitchCtrl(backendSrvStub); const orgSwitcherCtrl = new OrgSwitchCtrl(backendSrvStub);
orgSwitcherCtrl.getWindowLocationHref = () => orgSwitcherCtrl.getWindowLocationHref = () => 'http://localhost:3000?orgId=1&from=now-3h&to=now';
'http://localhost:3000?orgId=1&from=now-3h&to=now';
orgSwitcherCtrl.setWindowLocationHref = href => (expectedHref = href); orgSwitcherCtrl.setWindowLocationHref = href => (expectedHref = href);
return orgSwitcherCtrl.setUsingOrg({ orgId: 2 }); return orgSwitcherCtrl.setUsingOrg({ orgId: 2 });
@ -37,9 +36,7 @@ describe('OrgSwitcher', () => {
}); });
it('should switch orgId in url', () => { it('should switch orgId in url', () => {
expect(expectedHref).toBe( expect(expectedHref).toBe('http://localhost:3000?orgId=2&from=now-3h&to=now');
'http://localhost:3000?orgId=2&from=now-3h&to=now'
);
}); });
}); });
}); });

View File

@ -5,10 +5,7 @@ import moment from 'moment';
describe('rangeUtil', () => { describe('rangeUtil', () => {
describe('Can get range grouped list of ranges', () => { describe('Can get range grouped list of ranges', () => {
it('when custom settings should return default range list', () => { it('when custom settings should return default range list', () => {
var groups = rangeUtil.getRelativeTimesList( var groups = rangeUtil.getRelativeTimesList({ time_options: [] }, 'Last 5 minutes');
{ time_options: [] },
'Last 5 minutes'
);
expect(_.keys(groups).length).toBe(4); expect(_.keys(groups).length).toBe(4);
expect(groups[3][0].active).toBe(true); expect(groups[3][0].active).toBe(true);
}); });

View File

@ -6,12 +6,7 @@ describe('SearchCtrl', () => {
search: (options: any) => {}, search: (options: any) => {},
getDashboardTags: () => {}, getDashboardTags: () => {},
}; };
let ctrl = new SearchCtrl( let ctrl = new SearchCtrl({ $on: () => {} }, {}, {}, <SearchSrv>searchSrvStub);
{ $on: () => {} },
{},
{},
<SearchSrv>searchSrvStub
);
describe('Given an empty result', () => { describe('Given an empty result', () => {
beforeEach(() => { beforeEach(() => {

View File

@ -35,10 +35,7 @@ describe('SearchSrv', () => {
backendSrvMock.search = jest backendSrvMock.search = jest
.fn() .fn()
.mockReturnValueOnce( .mockReturnValueOnce(
Promise.resolve([ Promise.resolve([{ id: 2, title: 'second but first' }, { id: 1, title: 'first but second' }])
{ id: 2, title: 'second but first' },
{ id: 1, title: 'first but second' },
])
) )
.mockReturnValue(Promise.resolve([])); .mockReturnValue(Promise.resolve([]));
@ -64,14 +61,10 @@ describe('SearchSrv', () => {
beforeEach(() => { beforeEach(() => {
backendSrvMock.search = jest backendSrvMock.search = jest
.fn() .fn()
.mockReturnValueOnce( .mockReturnValueOnce(Promise.resolve([{ id: 2, title: 'two' }, { id: 1, title: 'one' }]))
Promise.resolve([{ id: 2, title: 'two' }, { id: 1, title: 'one' }])
)
.mockReturnValue(Promise.resolve([])); .mockReturnValue(Promise.resolve([]));
impressionSrv.getDashboardOpened = jest impressionSrv.getDashboardOpened = jest.fn().mockReturnValue([4, 5, 1, 2, 3]);
.fn()
.mockReturnValue([4, 5, 1, 2, 3]);
return searchSrv.search({ query: '' }).then(res => { return searchSrv.search({ query: '' }).then(res => {
results = res; results = res;
@ -90,9 +83,7 @@ describe('SearchSrv', () => {
let results; let results;
beforeEach(() => { beforeEach(() => {
backendSrvMock.search = jest backendSrvMock.search = jest.fn().mockReturnValue(Promise.resolve([{ id: 1, title: 'starred' }]));
.fn()
.mockReturnValue(Promise.resolve([{ id: 1, title: 'starred' }]));
return searchSrv.search({ query: '' }).then(res => { return searchSrv.search({ query: '' }).then(res => {
results = res; results = res;
@ -112,14 +103,9 @@ describe('SearchSrv', () => {
backendSrvMock.search = jest backendSrvMock.search = jest
.fn() .fn()
.mockReturnValueOnce( .mockReturnValueOnce(
Promise.resolve([ Promise.resolve([{ id: 1, title: 'starred and recent', isStarred: true }, { id: 2, title: 'recent' }])
{ id: 1, title: 'starred and recent', isStarred: true },
{ id: 2, title: 'recent' },
])
) )
.mockReturnValue( .mockReturnValue(Promise.resolve([{ id: 1, title: 'starred and recent' }]));
Promise.resolve([{ id: 1, title: 'starred and recent' }])
);
impressionSrv.getDashboardOpened = jest.fn().mockReturnValue([1, 2]); impressionSrv.getDashboardOpened = jest.fn().mockReturnValue([1, 2]);
return searchSrv.search({ query: '' }).then(res => { return searchSrv.search({ query: '' }).then(res => {

View File

@ -199,9 +199,7 @@ describe('TimeSeries', function() {
describe('series option overrides, bars, true & lines false', function() { describe('series option overrides, bars, true & lines false', function() {
beforeEach(function() { beforeEach(function() {
series.alias = 'test'; series.alias = 'test';
series.applySeriesOverrides([ series.applySeriesOverrides([{ alias: 'test', bars: true, lines: false }]);
{ alias: 'test', bars: true, lines: false },
]);
}); });
it('should disable lines, and enable bars', function() { it('should disable lines, and enable bars', function() {
@ -213,9 +211,7 @@ describe('TimeSeries', function() {
describe('series option overrides, linewidth, stack', function() { describe('series option overrides, linewidth, stack', function() {
beforeEach(function() { beforeEach(function() {
series.alias = 'test'; series.alias = 'test';
series.applySeriesOverrides([ series.applySeriesOverrides([{ alias: 'test', linewidth: 5, stack: false }]);
{ alias: 'test', linewidth: 5, stack: false },
]);
}); });
it('should disable stack, and set lineWidth', function() { it('should disable stack, and set lineWidth', function() {
@ -227,9 +223,7 @@ describe('TimeSeries', function() {
describe('series option overrides, dashes and lineWidth', function() { describe('series option overrides, dashes and lineWidth', function() {
beforeEach(function() { beforeEach(function() {
series.alias = 'test'; series.alias = 'test';
series.applySeriesOverrides([ series.applySeriesOverrides([{ alias: 'test', linewidth: 5, dashes: true }]);
{ alias: 'test', linewidth: 5, dashes: true },
]);
}); });
it('should enable dashes, set dashes lineWidth to 5 and lines lineWidth to 0', function() { it('should enable dashes, set dashes lineWidth to 5 and lines lineWidth to 0', function() {
@ -253,9 +247,7 @@ describe('TimeSeries', function() {
describe('series option overrides, pointradius, steppedLine', function() { describe('series option overrides, pointradius, steppedLine', function() {
beforeEach(function() { beforeEach(function() {
series.alias = 'test'; series.alias = 'test';
series.applySeriesOverrides([ series.applySeriesOverrides([{ alias: 'test', pointradius: 5, steppedLine: true }]);
{ alias: 'test', pointradius: 5, steppedLine: true },
]);
}); });
it('should set pointradius, and set steppedLine', function() { it('should set pointradius, and set steppedLine', function() {

View File

@ -1,11 +1,4 @@
import { import { describe, beforeEach, it, expect, angularMocks, sinon } from 'test/lib/common';
describe,
beforeEach,
it,
expect,
angularMocks,
sinon,
} from 'test/lib/common';
import 'app/core/directives/value_select_dropdown'; import 'app/core/directives/value_select_dropdown';
describe('SelectDropdownCtrl', function() { describe('SelectDropdownCtrl', function() {

View File

@ -4,31 +4,17 @@ import { saveAs } from 'file-saver';
const DEFAULT_DATETIME_FORMAT = 'YYYY-MM-DDTHH:mm:ssZ'; const DEFAULT_DATETIME_FORMAT = 'YYYY-MM-DDTHH:mm:ssZ';
export function exportSeriesListToCsv( export function exportSeriesListToCsv(seriesList, dateTimeFormat = DEFAULT_DATETIME_FORMAT, excel = false) {
seriesList,
dateTimeFormat = DEFAULT_DATETIME_FORMAT,
excel = false
) {
var text = (excel ? 'sep=;\n' : '') + 'Series;Time;Value\n'; var text = (excel ? 'sep=;\n' : '') + 'Series;Time;Value\n';
_.each(seriesList, function(series) { _.each(seriesList, function(series) {
_.each(series.datapoints, function(dp) { _.each(series.datapoints, function(dp) {
text += text += series.alias + ';' + moment(dp[1]).format(dateTimeFormat) + ';' + dp[0] + '\n';
series.alias +
';' +
moment(dp[1]).format(dateTimeFormat) +
';' +
dp[0] +
'\n';
}); });
}); });
saveSaveBlob(text, 'grafana_data_export.csv'); saveSaveBlob(text, 'grafana_data_export.csv');
} }
export function exportSeriesListToCsvColumns( export function exportSeriesListToCsvColumns(seriesList, dateTimeFormat = DEFAULT_DATETIME_FORMAT, excel = false) {
seriesList,
dateTimeFormat = DEFAULT_DATETIME_FORMAT,
excel = false
) {
var text = (excel ? 'sep=;\n' : '') + 'Time;'; var text = (excel ? 'sep=;\n' : '') + 'Time;';
// add header // add header
_.each(seriesList, function(series) { _.each(seriesList, function(series) {

View File

@ -22,12 +22,7 @@ export default function flatten(target, opts): any {
maxDepth = currentDepth + 1; maxDepth = currentDepth + 1;
} }
if ( if (!isarray && isobject && Object.keys(value).length && currentDepth < maxDepth) {
!isarray &&
isobject &&
Object.keys(value).length &&
currentDepth < maxDepth
) {
++currentDepth; ++currentDepth;
return step(value, newKey); return step(value, newKey);
} }

View File

@ -168,9 +168,7 @@ kbn.calculateInterval = function(range, resolution, lowLimitInterval) {
lowLimitMs = kbn.interval_to_ms(lowLimitInterval); lowLimitMs = kbn.interval_to_ms(lowLimitInterval);
} }
intervalMs = kbn.round_interval( intervalMs = kbn.round_interval((range.to.valueOf() - range.from.valueOf()) / resolution);
(range.to.valueOf() - range.from.valueOf()) / resolution
);
if (lowLimitMs > intervalMs) { if (lowLimitMs > intervalMs) {
intervalMs = lowLimitMs; intervalMs = lowLimitMs;
} }
@ -184,9 +182,7 @@ kbn.calculateInterval = function(range, resolution, lowLimitInterval) {
kbn.describe_interval = function(str) { kbn.describe_interval = function(str) {
var matches = str.match(kbn.interval_regex); var matches = str.match(kbn.interval_regex);
if (!matches || !_.has(kbn.intervals_in_seconds, matches[2])) { if (!matches || !_.has(kbn.intervals_in_seconds, matches[2])) {
throw new Error( throw new Error('Invalid interval string, expecting a number followed by one of "Mwdhmsy"');
'Invalid interval string, expecting a number followed by one of "Mwdhmsy"'
);
} else { } else {
return { return {
sec: kbn.intervals_in_seconds[matches[2]], sec: kbn.intervals_in_seconds[matches[2]],
@ -209,11 +205,7 @@ kbn.interval_to_seconds = function(str) {
kbn.query_color_dot = function(color, diameter) { kbn.query_color_dot = function(color, diameter) {
return ( return (
'<div class="icon-circle" style="' + '<div class="icon-circle" style="' +
[ ['display:inline-block', 'color:' + color, 'font-size:' + diameter + 'px'].join(';') +
'display:inline-block',
'color:' + color,
'font-size:' + diameter + 'px',
].join(';') +
'"></div>' '"></div>'
); );
}; };
@ -253,23 +245,14 @@ kbn.toFixed = function(value, decimals) {
var decimalPos = formatted.indexOf('.'); var decimalPos = formatted.indexOf('.');
var precision = decimalPos === -1 ? 0 : formatted.length - decimalPos - 1; var precision = decimalPos === -1 ? 0 : formatted.length - decimalPos - 1;
if (precision < decimals) { if (precision < decimals) {
return ( return (precision ? formatted : formatted + '.') + String(factor).substr(1, decimals - precision);
(precision ? formatted : formatted + '.') +
String(factor).substr(1, decimals - precision)
);
} }
} }
return formatted; return formatted;
}; };
kbn.toFixedScaled = function( kbn.toFixedScaled = function(value, decimals, scaledDecimals, additionalDecimals, ext) {
value,
decimals,
scaledDecimals,
additionalDecimals,
ext
) {
if (scaledDecimals === null) { if (scaledDecimals === null) {
return kbn.toFixed(value, decimals) + ext; return kbn.toFixed(value, decimals) + ext;
} else { } else {
@ -346,9 +329,7 @@ kbn.formatBuilders.decimalSIPrefix = function(unit, offset) {
// offset is given, it starts the units at the given prefix; otherwise, the // offset is given, it starts the units at the given prefix; otherwise, the
// offset defaults to zero and the initial unit is not prefixed. // offset defaults to zero and the initial unit is not prefixed.
kbn.formatBuilders.binarySIPrefix = function(unit, offset) { kbn.formatBuilders.binarySIPrefix = function(unit, offset) {
var prefixes = ['', 'Ki', 'Mi', 'Gi', 'Ti', 'Pi', 'Ei', 'Zi', 'Yi'].slice( var prefixes = ['', 'Ki', 'Mi', 'Gi', 'Ti', 'Pi', 'Ei', 'Zi', 'Yi'].slice(offset);
offset
);
var units = prefixes.map(function(p) { var units = prefixes.map(function(p) {
return ' ' + p + unit; return ' ' + p + unit;
}); });
@ -525,11 +506,7 @@ kbn.valueFormats.pressurembar = kbn.formatBuilders.decimalSIPrefix('bar', -1);
kbn.valueFormats.pressurekbar = kbn.formatBuilders.decimalSIPrefix('bar', 1); kbn.valueFormats.pressurekbar = kbn.formatBuilders.decimalSIPrefix('bar', 1);
kbn.valueFormats.pressurehpa = kbn.formatBuilders.fixedUnit('hPa'); kbn.valueFormats.pressurehpa = kbn.formatBuilders.fixedUnit('hPa');
kbn.valueFormats.pressurehg = kbn.formatBuilders.fixedUnit('"Hg'); kbn.valueFormats.pressurehg = kbn.formatBuilders.fixedUnit('"Hg');
kbn.valueFormats.pressurepsi = kbn.formatBuilders.scaledUnits(1000, [ kbn.valueFormats.pressurepsi = kbn.formatBuilders.scaledUnits(1000, [' psi', ' ksi', ' Mpsi']);
' psi',
' ksi',
' Mpsi',
]);
// Force // Force
kbn.valueFormats.forceNm = kbn.formatBuilders.decimalSIPrefix('Nm'); kbn.valueFormats.forceNm = kbn.formatBuilders.decimalSIPrefix('Nm');
@ -602,31 +579,13 @@ kbn.valueFormats.ms = function(size, decimals, scaledDecimals) {
return kbn.toFixedScaled(size / 60000, decimals, scaledDecimals, 5, ' min'); return kbn.toFixedScaled(size / 60000, decimals, scaledDecimals, 5, ' min');
} else if (Math.abs(size) < 86400000) { } else if (Math.abs(size) < 86400000) {
// Less than one day, devide in hours // Less than one day, devide in hours
return kbn.toFixedScaled( return kbn.toFixedScaled(size / 3600000, decimals, scaledDecimals, 7, ' hour');
size / 3600000,
decimals,
scaledDecimals,
7,
' hour'
);
} else if (Math.abs(size) < 31536000000) { } else if (Math.abs(size) < 31536000000) {
// Less than one year, devide in days // Less than one year, devide in days
return kbn.toFixedScaled( return kbn.toFixedScaled(size / 86400000, decimals, scaledDecimals, 8, ' day');
size / 86400000,
decimals,
scaledDecimals,
8,
' day'
);
} }
return kbn.toFixedScaled( return kbn.toFixedScaled(size / 31536000000, decimals, scaledDecimals, 10, ' year');
size / 31536000000,
decimals,
scaledDecimals,
10,
' year'
);
}; };
kbn.valueFormats.s = function(size, decimals, scaledDecimals) { kbn.valueFormats.s = function(size, decimals, scaledDecimals) {
@ -636,33 +595,15 @@ kbn.valueFormats.s = function(size, decimals, scaledDecimals) {
// Less than 1 µs, devide in ns // Less than 1 µs, devide in ns
if (Math.abs(size) < 0.000001) { if (Math.abs(size) < 0.000001) {
return kbn.toFixedScaled( return kbn.toFixedScaled(size * 1e9, decimals, scaledDecimals - decimals, -9, ' ns');
size * 1e9,
decimals,
scaledDecimals - decimals,
-9,
' ns'
);
} }
// Less than 1 ms, devide in µs // Less than 1 ms, devide in µs
if (Math.abs(size) < 0.001) { if (Math.abs(size) < 0.001) {
return kbn.toFixedScaled( return kbn.toFixedScaled(size * 1e6, decimals, scaledDecimals - decimals, -6, ' µs');
size * 1e6,
decimals,
scaledDecimals - decimals,
-6,
' µs'
);
} }
// Less than 1 second, devide in ms // Less than 1 second, devide in ms
if (Math.abs(size) < 1) { if (Math.abs(size) < 1) {
return kbn.toFixedScaled( return kbn.toFixedScaled(size * 1e3, decimals, scaledDecimals - decimals, -3, ' ms');
size * 1e3,
decimals,
scaledDecimals - decimals,
-3,
' ms'
);
} }
if (Math.abs(size) < 60) { if (Math.abs(size) < 60) {
@ -678,22 +619,10 @@ kbn.valueFormats.s = function(size, decimals, scaledDecimals) {
return kbn.toFixedScaled(size / 86400, decimals, scaledDecimals, 5, ' day'); return kbn.toFixedScaled(size / 86400, decimals, scaledDecimals, 5, ' day');
} else if (Math.abs(size) < 31536000) { } else if (Math.abs(size) < 31536000) {
// Less than one year, devide in week // Less than one year, devide in week
return kbn.toFixedScaled( return kbn.toFixedScaled(size / 604800, decimals, scaledDecimals, 6, ' week');
size / 604800,
decimals,
scaledDecimals,
6,
' week'
);
} }
return kbn.toFixedScaled( return kbn.toFixedScaled(size / 3.15569e7, decimals, scaledDecimals, 7, ' year');
size / 3.15569e7,
decimals,
scaledDecimals,
7,
' year'
);
}; };
kbn.valueFormats['µs'] = function(size, decimals, scaledDecimals) { kbn.valueFormats['µs'] = function(size, decimals, scaledDecimals) {
@ -720,29 +649,11 @@ kbn.valueFormats.ns = function(size, decimals, scaledDecimals) {
} else if (Math.abs(size) < 1000000) { } else if (Math.abs(size) < 1000000) {
return kbn.toFixedScaled(size / 1000, decimals, scaledDecimals, 3, ' µs'); return kbn.toFixedScaled(size / 1000, decimals, scaledDecimals, 3, ' µs');
} else if (Math.abs(size) < 1000000000) { } else if (Math.abs(size) < 1000000000) {
return kbn.toFixedScaled( return kbn.toFixedScaled(size / 1000000, decimals, scaledDecimals, 6, ' ms');
size / 1000000,
decimals,
scaledDecimals,
6,
' ms'
);
} else if (Math.abs(size) < 60000000000) { } else if (Math.abs(size) < 60000000000) {
return kbn.toFixedScaled( return kbn.toFixedScaled(size / 1000000000, decimals, scaledDecimals, 9, ' s');
size / 1000000000,
decimals,
scaledDecimals,
9,
' s'
);
} else { } else {
return kbn.toFixedScaled( return kbn.toFixedScaled(size / 60000000000, decimals, scaledDecimals, 12, ' min');
size / 60000000000,
decimals,
scaledDecimals,
12,
' min'
);
} }
}; };
@ -758,21 +669,9 @@ kbn.valueFormats.m = function(size, decimals, scaledDecimals) {
} else if (Math.abs(size) < 10080) { } else if (Math.abs(size) < 10080) {
return kbn.toFixedScaled(size / 1440, decimals, scaledDecimals, 3, ' day'); return kbn.toFixedScaled(size / 1440, decimals, scaledDecimals, 3, ' day');
} else if (Math.abs(size) < 604800) { } else if (Math.abs(size) < 604800) {
return kbn.toFixedScaled( return kbn.toFixedScaled(size / 10080, decimals, scaledDecimals, 4, ' week');
size / 10080,
decimals,
scaledDecimals,
4,
' week'
);
} else { } else {
return kbn.toFixedScaled( return kbn.toFixedScaled(size / 5.25948e5, decimals, scaledDecimals, 5, ' year');
size / 5.25948e5,
decimals,
scaledDecimals,
5,
' year'
);
} }
}; };

View File

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

View File

@ -16,9 +16,7 @@ function outlineFixer() {
var set_css = function(css_text) { var set_css = function(css_text) {
// Handle setting of <style> element contents in IE8 // Handle setting of <style> element contents in IE8
!!style_element.styleSheet !!style_element.styleSheet ? (style_element.styleSheet.cssText = css_text) : (style_element.innerHTML = css_text);
? (style_element.styleSheet.cssText = css_text)
: (style_element.innerHTML = css_text);
}; };
d.getElementsByTagName('HEAD')[0].appendChild(style_element); d.getElementsByTagName('HEAD')[0].appendChild(style_element);

View File

@ -1,10 +1,6 @@
import coreModule from 'app/core/core_module'; import coreModule from 'app/core/core_module';
export function react2AngularDirective( export function react2AngularDirective(name: string, component: any, options: any) {
name: string,
component: any,
options: any
) {
coreModule.directive(name, [ coreModule.directive(name, [
'reactDirective', 'reactDirective',
reactDirective => { reactDirective => {

View File

@ -40,12 +40,7 @@ export function getScaledDecimals(decimals, tick_size) {
* @param noTicks Number of ticks * @param noTicks Number of ticks
* @param tickDecimals Tick decimal precision * @param tickDecimals Tick decimal precision
*/ */
export function getFlotTickSize( export function getFlotTickSize(min: number, max: number, noTicks: number, tickDecimals: number) {
min: number,
max: number,
noTicks: number,
tickDecimals: number
) {
var delta = (max - min) / noTicks, var delta = (max - min) / noTicks,
dec = -Math.floor(Math.log(delta) / Math.LN10), dec = -Math.floor(Math.log(delta) / Math.LN10),
maxDec = tickDecimals; maxDec = tickDecimals;

View File

@ -20,11 +20,7 @@ export class SemVersion {
isGtOrEq(version: string): boolean { isGtOrEq(version: string): boolean {
let compared = new SemVersion(version); let compared = new SemVersion(version);
return !( return !(this.major < compared.major || this.minor < compared.minor || this.patch < compared.patch);
this.major < compared.major ||
this.minor < compared.minor ||
this.patch < compared.patch
);
} }
isValid(): boolean { isValid(): boolean {

View File

@ -35,16 +35,11 @@ export class AdminEditOrgCtrl {
}; };
$scope.updateOrgUser = function(orgUser) { $scope.updateOrgUser = function(orgUser) {
backendSrv.patch( backendSrv.patch('/api/orgs/' + orgUser.orgId + '/users/' + orgUser.userId, orgUser);
'/api/orgs/' + orgUser.orgId + '/users/' + orgUser.userId,
orgUser
);
}; };
$scope.removeOrgUser = function(orgUser) { $scope.removeOrgUser = function(orgUser) {
backendSrv backendSrv.delete('/api/orgs/' + orgUser.orgId + '/users/' + orgUser.userId).then(function() {
.delete('/api/orgs/' + orgUser.orgId + '/users/' + orgUser.userId)
.then(function() {
$scope.getOrgUsers($scope.org.id); $scope.getOrgUsers($scope.org.id);
}); });
}; };
@ -53,6 +48,4 @@ export class AdminEditOrgCtrl {
} }
} }
angular angular.module('grafana.controllers').controller('AdminEditOrgCtrl', AdminEditOrgCtrl);
.module('grafana.controllers')
.controller('AdminEditOrgCtrl', AdminEditOrgCtrl);

View File

@ -30,9 +30,7 @@ export class AdminEditUserCtrl {
} }
var payload = { password: $scope.password }; var payload = { password: $scope.password };
backendSrv backendSrv.put('/api/admin/users/' + $scope.user_id + '/password', payload).then(function() {
.put('/api/admin/users/' + $scope.user_id + '/password', payload)
.then(function() {
$location.path('/admin/users'); $location.path('/admin/users');
}); });
}; };
@ -40,9 +38,7 @@ export class AdminEditUserCtrl {
$scope.updatePermissions = function() { $scope.updatePermissions = function() {
var payload = $scope.permissions; var payload = $scope.permissions;
backendSrv backendSrv.put('/api/admin/users/' + $scope.user_id + '/permissions', payload).then(function() {
.put('/api/admin/users/' + $scope.user_id + '/permissions', payload)
.then(function() {
$location.path('/admin/users'); $location.path('/admin/users');
}); });
}; };
@ -68,26 +64,17 @@ export class AdminEditUserCtrl {
return; return;
} }
backendSrv backendSrv.put('/api/users/' + $scope.user_id, $scope.user).then(function() {
.put('/api/users/' + $scope.user_id, $scope.user)
.then(function() {
$location.path('/admin/users'); $location.path('/admin/users');
}); });
}; };
$scope.updateOrgUser = function(orgUser) { $scope.updateOrgUser = function(orgUser) {
backendSrv backendSrv.patch('/api/orgs/' + orgUser.orgId + '/users/' + $scope.user_id, orgUser).then(function() {});
.patch(
'/api/orgs/' + orgUser.orgId + '/users/' + $scope.user_id,
orgUser
)
.then(function() {});
}; };
$scope.removeOrgUser = function(orgUser) { $scope.removeOrgUser = function(orgUser) {
backendSrv backendSrv.delete('/api/orgs/' + orgUser.orgId + '/users/' + $scope.user_id).then(function() {
.delete('/api/orgs/' + orgUser.orgId + '/users/' + $scope.user_id)
.then(function() {
$scope.getUserOrgs($scope.user_id); $scope.getUserOrgs($scope.user_id);
}); });
}; };
@ -120,9 +107,7 @@ export class AdminEditUserCtrl {
$scope.newOrg.loginOrEmail = $scope.user.login; $scope.newOrg.loginOrEmail = $scope.user.login;
backendSrv backendSrv.post('/api/orgs/' + orgInfo.id + '/users/', $scope.newOrg).then(function() {
.post('/api/orgs/' + orgInfo.id + '/users/', $scope.newOrg)
.then(function() {
$scope.getUserOrgs($scope.user_id); $scope.getUserOrgs($scope.user_id);
}); });
}; };
@ -131,6 +116,4 @@ export class AdminEditUserCtrl {
} }
} }
angular angular.module('grafana.controllers').controller('AdminEditUserCtrl', AdminEditUserCtrl);
.module('grafana.controllers')
.controller('AdminEditUserCtrl', AdminEditUserCtrl);

View File

@ -33,6 +33,4 @@ export class AdminListOrgsCtrl {
} }
} }
angular angular.module('grafana.controllers').controller('AdminListOrgsCtrl', AdminListOrgsCtrl);
.module('grafana.controllers')
.controller('AdminListOrgsCtrl', AdminListOrgsCtrl);

View File

@ -17,11 +17,7 @@ export default class AdminListUsersCtrl {
getUsers() { getUsers() {
this.backendSrv this.backendSrv
.get( .get(`/api/users/search?perpage=${this.perPage}&page=${this.page}&query=${this.query}`)
`/api/users/search?perpage=${this.perPage}&page=${this.page}&query=${
this.query
}`
)
.then(result => { .then(result => {
this.users = result.users; this.users = result.users;
this.page = result.page; this.page = result.page;

View File

@ -1,10 +1,7 @@
///<reference path="../../headers/common.d.ts" /> ///<reference path="../../headers/common.d.ts" />
import _ from 'lodash'; import _ from 'lodash';
import { import { QueryPartDef, QueryPart } from 'app/core/components/query_part/query_part';
QueryPartDef,
QueryPart,
} from 'app/core/components/query_part/query_part';
var alertQueryDef = new QueryPartDef({ var alertQueryDef = new QueryPartDef({
type: 'query', type: 'query',
@ -38,10 +35,7 @@ var evalFunctions = [
{ text: 'HAS NO VALUE', value: 'no_value' }, { text: 'HAS NO VALUE', value: 'no_value' },
]; ];
var evalOperators = [ var evalOperators = [{ text: 'OR', value: 'or' }, { text: 'AND', value: 'and' }];
{ text: 'OR', value: 'or' },
{ text: 'AND', value: 'and' },
];
var reducerTypes = [ var reducerTypes = [
{ text: 'avg()', value: 'avg' }, { text: 'avg()', value: 'avg' },
@ -63,10 +57,7 @@ var noDataModes = [
{ text: 'Ok', value: 'ok' }, { text: 'Ok', value: 'ok' },
]; ];
var executionErrorModes = [ var executionErrorModes = [{ text: 'Alerting', value: 'alerting' }, { text: 'Keep Last State', value: 'keep_state' }];
{ text: 'Alerting', value: 'alerting' },
{ text: 'Keep Last State', value: 'keep_state' },
];
function createReducerPart(model) { function createReducerPart(model) {
var def = new QueryPartDef({ type: model.type, defaultParams: [] }); var def = new QueryPartDef({ type: model.type, defaultParams: [] });

View File

@ -56,9 +56,7 @@ export class AlertListCtrl {
paused: alert.state !== 'paused', paused: alert.state !== 'paused',
}; };
this.backendSrv this.backendSrv.post(`/api/alerts/${alert.id}/pause`, payload).then(result => {
.post(`/api/alerts/${alert.id}/pause`, payload)
.then(result => {
alert.state = result.state; alert.state = result.state;
alert.stateModel = alertDef.getStateDisplayModel(result.state); alert.stateModel = alertDef.getStateDisplayModel(result.state);
}); });

View File

@ -57,10 +57,7 @@ export class AlertTabCtrl {
// set panel alert edit mode // set panel alert edit mode
this.$scope.$on('$destroy', () => { this.$scope.$on('$destroy', () => {
this.panelCtrl.events.off( this.panelCtrl.events.off('threshold-changed', thresholdChangedEventHandler);
'threshold-changed',
thresholdChangedEventHandler
);
this.panelCtrl.editingThresholds = false; this.panelCtrl.editingThresholds = false;
this.panelCtrl.render(); this.panelCtrl.render();
}); });
@ -80,16 +77,10 @@ export class AlertTabCtrl {
getAlertHistory() { getAlertHistory() {
this.backendSrv this.backendSrv
.get( .get(`/api/annotations?dashboardId=${this.panelCtrl.dashboard.id}&panelId=${this.panel.id}&limit=50`)
`/api/annotations?dashboardId=${this.panelCtrl.dashboard.id}&panelId=${
this.panel.id
}&limit=50`
)
.then(res => { .then(res => {
this.alertHistory = _.map(res, ah => { this.alertHistory = _.map(res, ah => {
ah.time = this.dashboardSrv ah.time = this.dashboardSrv.getCurrent().formatDate(ah.time, 'MMM D, YYYY HH:mm:ss');
.getCurrent()
.formatDate(ah.time, 'MMM D, YYYY HH:mm:ss');
ah.stateModel = alertDef.getStateDisplayModel(ah.newState); ah.stateModel = alertDef.getStateDisplayModel(ah.newState);
ah.info = alertDef.getAlertAnnotationInfo(ah); ah.info = alertDef.getAlertAnnotationInfo(ah);
return ah; return ah;
@ -316,9 +307,7 @@ export class AlertTabCtrl {
switch (evt.name) { switch (evt.name) {
case 'action': { case 'action': {
conditionModel.source.reducer.type = evt.action.value; conditionModel.source.reducer.type = evt.action.value;
conditionModel.reducerPart = alertDef.createReducerPart( conditionModel.reducerPart = alertDef.createReducerPart(conditionModel.source.reducer);
conditionModel.source.reducer
);
break; break;
} }
case 'get-part-actions': { case 'get-part-actions': {
@ -398,8 +387,7 @@ export class AlertTabCtrl {
clearHistory() { clearHistory() {
appEvents.emit('confirm-modal', { appEvents.emit('confirm-modal', {
title: 'Delete Alert History', title: 'Delete Alert History',
text: text: 'Are you sure you want to remove all history & annotations for this alert?',
'Are you sure you want to remove all history & annotations for this alert?',
icon: 'fa-trash', icon: 'fa-trash',
yesText: 'Yes', yesText: 'Yes',
onConfirm: () => { onConfirm: () => {

View File

@ -22,13 +22,7 @@ export class AlertNotificationEditCtrl {
}; };
/** @ngInject */ /** @ngInject */
constructor( constructor(private $routeParams, private backendSrv, private $location, private $templateCache, navModelSrv) {
private $routeParams,
private backendSrv,
private $location,
private $templateCache,
navModelSrv
) {
this.navModel = navModelSrv.getNav('alerting', 'channels', 0); this.navModel = navModelSrv.getNav('alerting', 'channels', 0);
this.isNew = !this.$routeParams.id; this.isNew = !this.$routeParams.id;
@ -39,10 +33,7 @@ export class AlertNotificationEditCtrl {
// add option templates // add option templates
for (let notifier of this.notifiers) { for (let notifier of this.notifiers) {
this.$templateCache.put( this.$templateCache.put(this.getNotifierTemplateId(notifier.type), notifier.optionsTemplate);
this.getNotifierTemplateId(notifier.type),
notifier.optionsTemplate
);
} }
if (!this.$routeParams.id) { if (!this.$routeParams.id) {
@ -51,9 +42,7 @@ export class AlertNotificationEditCtrl {
return _.defaults(this.model, this.defaults); return _.defaults(this.model, this.defaults);
} }
return this.backendSrv return this.backendSrv.get(`/api/alert-notifications/${this.$routeParams.id}`).then(result => {
.get(`/api/alert-notifications/${this.$routeParams.id}`)
.then(result => {
this.navModel.breadcrumbs.push({ text: result.name }); this.navModel.breadcrumbs.push({ text: result.name });
this.navModel.node = { text: result.name }; this.navModel.node = { text: result.name };
return result; return result;
@ -71,9 +60,7 @@ export class AlertNotificationEditCtrl {
} }
if (this.model.id) { if (this.model.id) {
this.backendSrv this.backendSrv.put(`/api/alert-notifications/${this.model.id}`, this.model).then(res => {
.put(`/api/alert-notifications/${this.model.id}`, this.model)
.then(res => {
this.model = res; this.model = res;
appEvents.emit('alert-success', ['Notification updated', '']); appEvents.emit('alert-success', ['Notification updated', '']);
}); });

View File

@ -4,10 +4,4 @@ import { EventManager } from './event_manager';
import { AnnotationEvent } from './event'; import { AnnotationEvent } from './event';
import { annotationTooltipDirective } from './annotation_tooltip'; import { annotationTooltipDirective } from './annotation_tooltip';
export { export { AnnotationsSrv, eventEditor, EventManager, AnnotationEvent, annotationTooltipDirective };
AnnotationsSrv,
eventEditor,
EventManager,
AnnotationEvent,
annotationTooltipDirective,
};

View File

@ -4,19 +4,12 @@ import coreModule from 'app/core/core_module';
import alertDef from '../alerting/alert_def'; import alertDef from '../alerting/alert_def';
/** @ngInject **/ /** @ngInject **/
export function annotationTooltipDirective( export function annotationTooltipDirective($sanitize, dashboardSrv, contextSrv, $compile) {
$sanitize,
dashboardSrv,
contextSrv,
$compile
) {
function sanitizeString(str) { function sanitizeString(str) {
try { try {
return $sanitize(str); return $sanitize(str);
} catch (err) { } catch (err) {
console.log( console.log('Could not sanitize annotation string, html escaping instead');
'Could not sanitize annotation string, html escaping instead'
);
return _.escape(str); return _.escape(str);
} }
} }
@ -39,9 +32,7 @@ export function annotationTooltipDirective(
if (event.alertId) { if (event.alertId) {
var stateModel = alertDef.getStateDisplayModel(event.newState); var stateModel = alertDef.getStateDisplayModel(event.newState);
titleStateClass = stateModel.stateClass; titleStateClass = stateModel.stateClass;
title = `<i class="icon-gf ${stateModel.iconClass}"></i> ${ title = `<i class="icon-gf ${stateModel.iconClass}"></i> ${stateModel.text}`;
stateModel.text
}`;
text = alertDef.getAlertAnnotationInfo(event); text = alertDef.getAlertAnnotationInfo(event);
if (event.text) { if (event.text) {
text = text + '<br />' + event.text; text = text + '<br />' + event.text;
@ -53,17 +44,13 @@ export function annotationTooltipDirective(
var header = `<div class="graph-annotation__header">`; var header = `<div class="graph-annotation__header">`;
if (event.login) { if (event.login) {
header += `<div class="graph-annotation__user" bs-tooltip="'Created by ${ header += `<div class="graph-annotation__user" bs-tooltip="'Created by ${event.login}'"><img src="${
event.login event.avatarUrl
}'"><img src="${event.avatarUrl}" /></div>`; }" /></div>`;
} }
header += ` header += `
<span class="graph-annotation__title ${titleStateClass}">${sanitizeString( <span class="graph-annotation__title ${titleStateClass}">${sanitizeString(title)}</span>
title <span class="graph-annotation__time">${dashboard.formatDate(event.min)}</span>
)}</span>
<span class="graph-annotation__time">${dashboard.formatDate(
event.min
)}</span>
`; `;
// Show edit icon only for users with at least Editor role // Show edit icon only for users with at least Editor role
@ -80,8 +67,7 @@ export function annotationTooltipDirective(
tooltip += '<div class="graph-annotation__body">'; tooltip += '<div class="graph-annotation__body">';
if (text) { if (text) {
tooltip += tooltip += '<div>' + sanitizeString(text.replace(/\n/g, '<br>')) + '</div>';
'<div>' + sanitizeString(text.replace(/\n/g, '<br>')) + '</div>';
} }
var tags = event.tags; var tags = event.tags;

View File

@ -10,19 +10,9 @@ export class AnnotationsSrv {
alertStatesPromise: any; alertStatesPromise: any;
/** @ngInject */ /** @ngInject */
constructor( constructor(private $rootScope, private $q, private datasourceSrv, private backendSrv, private timeSrv) {
private $rootScope,
private $q,
private datasourceSrv,
private backendSrv,
private timeSrv
) {
$rootScope.onAppEvent('refresh', this.clearCache.bind(this), $rootScope); $rootScope.onAppEvent('refresh', this.clearCache.bind(this), $rootScope);
$rootScope.onAppEvent( $rootScope.onAppEvent('dashboard-initialized', this.clearCache.bind(this), $rootScope);
'dashboard-initialized',
this.clearCache.bind(this),
$rootScope
);
} }
clearCache() { clearCache() {
@ -62,10 +52,7 @@ export class AnnotationsSrv {
err.message = err.data.message; err.message = err.data.message;
} }
console.log('AnnotationSrv.query error', err); console.log('AnnotationSrv.query error', err);
this.$rootScope.appEvent('alert-error', [ this.$rootScope.appEvent('alert-error', ['Annotation Query Failed', err.message || err]);
'Annotation Query Failed',
err.message || err,
]);
return []; return [];
}); });
} }
@ -88,12 +75,9 @@ export class AnnotationsSrv {
return this.alertStatesPromise; return this.alertStatesPromise;
} }
this.alertStatesPromise = this.backendSrv.get( this.alertStatesPromise = this.backendSrv.get('/api/alerts/states-for-dashboard', {
'/api/alerts/states-for-dashboard',
{
dashboardId: options.dashboard.id, dashboardId: options.dashboard.id,
} });
);
return this.alertStatesPromise; return this.alertStatesPromise;
} }

View File

@ -20,10 +20,7 @@ export class AnnotationsEditorCtrl {
hide: false, hide: false,
}; };
showOptions: any = [ showOptions: any = [{ text: 'All Panels', value: 0 }, { text: 'Specific Panels', value: 1 }];
{ text: 'All Panels', value: 0 },
{ text: 'Specific Panels', value: 1 },
];
/** @ngInject */ /** @ngInject */
constructor($scope, private datasourceSrv) { constructor($scope, private datasourceSrv) {
@ -38,9 +35,7 @@ export class AnnotationsEditorCtrl {
} }
datasourceChanged() { datasourceChanged() {
return this.datasourceSrv return this.datasourceSrv.get(this.currentAnnotation.datasource).then(ds => {
.get(this.currentAnnotation.datasource)
.then(ds => {
this.currentDatasource = ds; this.currentDatasource = ds;
}); });
} }

View File

@ -31,9 +31,7 @@ describe('Annotations', () => {
it('should cut regions to current time range', () => { it('should cut regions to current time range', () => {
const range = { from: 0, to: 8 }; const range = { from: 0, to: 8 };
testAnnotations = [{ id: 5, time: 4, regionId: 5 }]; testAnnotations = [{ id: 5, time: 4, regionId: 5 }];
const expectedAnnotations = [ const expectedAnnotations = [{ id: 5, regionId: 5, isRegion: true, time: 4, timeEnd: 7 }];
{ id: 5, regionId: 5, isRegion: true, time: 4, timeEnd: 7 },
];
let regions = makeRegions(testAnnotations, { range: range }); let regions = makeRegions(testAnnotations, { range: range });
expect(regions).toEqual(expectedAnnotations); expect(regions).toEqual(expectedAnnotations);
@ -49,11 +47,7 @@ describe('Annotations', () => {
{ id: 5, time: 5 }, { id: 5, time: 5 },
{ id: 5, time: 5 }, { id: 5, time: 5 },
]; ];
const expectedAnnotations = [ const expectedAnnotations = [{ id: 1, time: 1 }, { id: 2, time: 2 }, { id: 5, time: 5 }];
{ id: 1, time: 1 },
{ id: 2, time: 2 },
{ id: 5, time: 5 },
];
let deduplicated = dedupAnnotations(testAnnotations); let deduplicated = dedupAnnotations(testAnnotations);
expect(deduplicated).toEqual(expectedAnnotations); expect(deduplicated).toEqual(expectedAnnotations);
@ -67,11 +61,7 @@ describe('Annotations', () => {
{ id: 5, time: 5 }, { id: 5, time: 5 },
{ id: 5, time: 5 }, { id: 5, time: 5 },
]; ];
const expectedAnnotations = [ const expectedAnnotations = [{ id: 1, time: 1 }, { id: 2, time: 2 }, { id: 5, time: 5 }];
{ id: 1, time: 1 },
{ id: 2, time: 2 },
{ id: 5, time: 5 },
];
let deduplicated = dedupAnnotations(testAnnotations); let deduplicated = dedupAnnotations(testAnnotations);
expect(deduplicated).toEqual(expectedAnnotations); expect(deduplicated).toEqual(expectedAnnotations);

View File

@ -1,10 +1,4 @@
import { import { describe, beforeEach, it, expect, angularMocks } from 'test/lib/common';
describe,
beforeEach,
it,
expect,
angularMocks,
} from 'test/lib/common';
import '../annotations_srv'; import '../annotations_srv';
import helpers from 'test/specs/helpers'; import helpers from 'test/specs/helpers';
@ -33,10 +27,7 @@ describe('AnnotationsSrv', function() {
let translatedAnnotations; let translatedAnnotations;
beforeEach(() => { beforeEach(() => {
translatedAnnotations = ctx.service.translateQueryResult( translatedAnnotations = ctx.service.translateQueryResult(annotationSource, annotations);
annotationSource,
annotations
);
}); });
it('should set defaults', () => { it('should set defaults', () => {

View File

@ -6,11 +6,7 @@ import _ from 'lodash';
export class AclCtrl { export class AclCtrl {
dashboard: any; dashboard: any;
items: DashboardAcl[]; items: DashboardAcl[];
permissionOptions = [ permissionOptions = [{ value: 1, text: 'View' }, { value: 2, text: 'Edit' }, { value: 4, text: 'Admin' }];
{ value: 1, text: 'View' },
{ value: 2, text: 'Edit' },
{ value: 4, text: 'Admin' },
];
aclTypes = [ aclTypes = [
{ value: 'Group', text: 'Team' }, { value: 'Group', text: 'Team' },
{ value: 'User', text: 'User' }, { value: 'User', text: 'User' },
@ -38,25 +34,18 @@ export class AclCtrl {
} }
get(dashboardId: number) { get(dashboardId: number) {
return this.backendSrv return this.backendSrv.get(`/api/dashboards/id/${dashboardId}/acl`).then(result => {
.get(`/api/dashboards/id/${dashboardId}/acl`)
.then(result => {
this.items = _.map(result, this.prepareViewModel.bind(this)); this.items = _.map(result, this.prepareViewModel.bind(this));
this.sortItems(); this.sortItems();
}); });
} }
sortItems() { sortItems() {
this.items = _.orderBy( this.items = _.orderBy(this.items, ['sortRank', 'sortName'], ['desc', 'asc']);
this.items,
['sortRank', 'sortName'],
['desc', 'asc']
);
} }
prepareViewModel(item: DashboardAcl): DashboardAcl { prepareViewModel(item: DashboardAcl): DashboardAcl {
item.inherited = item.inherited = !this.dashboard.meta.isFolder && this.dashboard.id !== item.dashboardId;
!this.dashboard.meta.isFolder && this.dashboard.id !== item.dashboardId;
item.sortRank = 0; item.sortRank = 0;
if (item.userId > 0) { if (item.userId > 0) {
@ -71,9 +60,7 @@ export class AclCtrl {
item.sortRank = 20; item.sortRank = 20;
} else if (item.role) { } else if (item.role) {
item.icon = 'fa fa-fw fa-street-view'; item.icon = 'fa fa-fw fa-street-view';
item.nameHtml = this.$sce.trustAsHtml( item.nameHtml = this.$sce.trustAsHtml(`Everyone with <span class="query-keyword">${item.role}</span> Role`);
`Everyone with <span class="query-keyword">${item.role}</span> Role`
);
item.sortName = item.role; item.sortName = item.role;
item.sortRank = 30; item.sortRank = 30;
if (item.role === 'Viewer') { if (item.role === 'Viewer') {
@ -103,9 +90,7 @@ export class AclCtrl {
}); });
} }
return this.backendSrv return this.backendSrv.post(`/api/dashboards/id/${this.dashboard.id}/acl`, { items: updated }).then(() => {
.post(`/api/dashboards/id/${this.dashboard.id}/acl`, { items: updated })
.then(() => {
return this.dismiss(); return this.dismiss();
}); });
} }
@ -156,9 +141,7 @@ export class AclCtrl {
return ( return (
(origItem.role && newItem.role && origItem.role === newItem.role) || (origItem.role && newItem.role && origItem.role === newItem.role) ||
(origItem.userId && (origItem.userId && newItem.userId && origItem.userId === newItem.userId) ||
newItem.userId &&
origItem.userId === newItem.userId) ||
(origItem.teamId && newItem.teamId && origItem.teamId === newItem.teamId) (origItem.teamId && newItem.teamId && origItem.teamId === newItem.teamId)
); );
} }

View File

@ -1,11 +1,4 @@
import { import { describe, beforeEach, it, expect, sinon, angularMocks } from 'test/lib/common';
describe,
beforeEach,
it,
expect,
sinon,
angularMocks,
} from 'test/lib/common';
import { AclCtrl } from '../acl'; import { AclCtrl } from '../acl';
describe('AclCtrl', () => { describe('AclCtrl', () => {
@ -81,9 +74,7 @@ describe('AclCtrl', () => {
done(); done();
}); });
expect(backendSrv.post.getCall(0).args[0]).to.eql( expect(backendSrv.post.getCall(0).args[0]).to.eql('/api/dashboards/id/1/acl');
'/api/dashboards/id/1/acl'
);
expect(backendSrv.post.getCall(0).args[1].items[0].role).to.eql('Viewer'); expect(backendSrv.post.getCall(0).args[1].items[0].role).to.eql('Viewer');
expect(backendSrv.post.getCall(0).args[1].items[0].permission).to.eql(1); expect(backendSrv.post.getCall(0).args[1].items[0].permission).to.eql(1);
expect(backendSrv.post.getCall(0).args[1].items[1].role).to.eql('Editor'); expect(backendSrv.post.getCall(0).args[1].items[1].role).to.eql('Editor');

View File

@ -23,11 +23,7 @@ export class AdHocFiltersCtrl {
value: '-- remove filter --', value: '-- remove filter --',
}); });
this.buildSegmentModel(); this.buildSegmentModel();
this.$rootScope.onAppEvent( this.$rootScope.onAppEvent('template-variable-value-updated', this.buildSegmentModel.bind(this), $scope);
'template-variable-value-updated',
this.buildSegmentModel.bind(this),
$scope
);
} }
buildSegmentModel() { buildSegmentModel() {
@ -53,9 +49,7 @@ export class AdHocFiltersCtrl {
getOptions(segment, index) { getOptions(segment, index) {
if (segment.type === 'operator') { if (segment.type === 'operator') {
return this.$q.when( return this.$q.when(this.uiSegmentSrv.newOperators(['=', '!=', '<', '>', '=~', '!~']));
this.uiSegmentSrv.newOperators(['=', '!=', '<', '>', '=~', '!~'])
);
} }
if (segment.type === 'condition') { if (segment.type === 'condition') {
@ -107,13 +101,7 @@ export class AdHocFiltersCtrl {
this.segments.splice(index, 0, this.uiSegmentSrv.newCondition('AND')); this.segments.splice(index, 0, this.uiSegmentSrv.newCondition('AND'));
} }
this.segments.push(this.uiSegmentSrv.newOperator('=')); this.segments.push(this.uiSegmentSrv.newOperator('='));
this.segments.push( this.segments.push(this.uiSegmentSrv.newFake('select tag value', 'value', 'query-segment-value'));
this.uiSegmentSrv.newFake(
'select tag value',
'value',
'query-segment-value'
)
);
segment.type = 'key'; segment.type = 'key';
segment.cssClass = 'query-segment-key'; segment.cssClass = 'query-segment-key';
} }

View File

@ -8,12 +8,7 @@ export class CreateFolderCtrl {
validationError: any; validationError: any;
/** @ngInject **/ /** @ngInject **/
constructor( constructor(private backendSrv, private $location, private validationSrv, navModelSrv) {
private backendSrv,
private $location,
private validationSrv,
navModelSrv
) {
this.navModel = navModelSrv.getNav('dashboards', 'manage-dashboards', 0); this.navModel = navModelSrv.getNav('dashboards', 'manage-dashboards', 0);
} }
@ -25,9 +20,7 @@ export class CreateFolderCtrl {
return this.backendSrv.createDashboardFolder(this.title).then(result => { return this.backendSrv.createDashboardFolder(this.title).then(result => {
appEvents.emit('alert-success', ['Folder Created', 'OK']); appEvents.emit('alert-success', ['Folder Created', 'OK']);
var folderUrl = `/dashboards/folder/${result.dashboard.id}/${ var folderUrl = `/dashboards/folder/${result.dashboard.id}/${result.meta.slug}`;
result.meta.slug
}`;
this.$location.url(folderUrl); this.$location.url(folderUrl);
}); });
} }

View File

@ -66,9 +66,7 @@ export class DashboardCtrl implements PanelContainer {
// TODO refactor ViewStateSrv // TODO refactor ViewStateSrv
this.$scope.dashboard = dashboard; this.$scope.dashboard = dashboard;
this.dashboardViewState = this.dashboardViewStateSrv.create( this.dashboardViewState = this.dashboardViewStateSrv.create(this.$scope);
this.$scope
);
this.keybindingSrv.setupDashboardBindings(this.$scope, dashboard); this.keybindingSrv.setupDashboardBindings(this.$scope, dashboard);
@ -134,10 +132,7 @@ export class DashboardCtrl implements PanelContainer {
init(dashboard) { init(dashboard) {
this.$scope.onAppEvent('show-json-editor', this.showJsonEditor.bind(this)); this.$scope.onAppEvent('show-json-editor', this.showJsonEditor.bind(this));
this.$scope.onAppEvent( this.$scope.onAppEvent('template-variable-value-updated', this.templateVariableUpdated.bind(this));
'template-variable-value-updated',
this.templateVariableUpdated.bind(this)
);
this.setupDashboard(dashboard); this.setupDashboard(dashboard);
} }
} }

View File

@ -18,14 +18,7 @@ export class DashboardImportCtrl {
nameValidationError: any; nameValidationError: any;
/** @ngInject */ /** @ngInject */
constructor( constructor(private backendSrv, private validationSrv, navModelSrv, private $location, private $scope, $routeParams) {
private backendSrv,
private validationSrv,
navModelSrv,
private $location,
private $scope,
$routeParams
) {
this.navModel = navModelSrv.getNav('create', 'import'); this.navModel = navModelSrv.getNav('create', 'import');
this.step = 1; this.step = 1;
@ -76,8 +69,7 @@ export class DashboardImportCtrl {
}); });
if (sources.length === 0) { if (sources.length === 0) {
inputModel.info = inputModel.info = 'No data sources of type ' + input.pluginName + ' found';
'No data sources of type ' + input.pluginName + ' found';
} else if (!inputModel.info) { } else if (!inputModel.info) {
inputModel.info = 'Select a ' + input.pluginName + ' data source'; inputModel.info = 'Select a ' + input.pluginName + ' data source';
} }

View File

@ -394,10 +394,7 @@ export class DashboardMigrator {
} }
// Add special "row" panels if even one row is collapsed, repeated or has visible title // Add special "row" panels if even one row is collapsed, repeated or has visible title
const showRows = _.some( const showRows = _.some(old.rows, row => row.collapse || row.showTitle || row.repeat);
old.rows,
row => row.collapse || row.showTitle || row.repeat
);
for (let row of old.rows) { for (let row of old.rows) {
if (row.repeatIteration) { if (row.repeatIteration) {
@ -433,9 +430,7 @@ export class DashboardMigrator {
for (let panel of row.panels) { for (let panel of row.panels) {
panel.span = panel.span || DEFAULT_PANEL_SPAN; panel.span = panel.span || DEFAULT_PANEL_SPAN;
const panelWidth = Math.floor(panel.span) * widthFactor; const panelWidth = Math.floor(panel.span) * widthFactor;
const panelHeight = panel.height const panelHeight = panel.height ? getGridHeight(panel.height) : rowGridHeight;
? getGridHeight(panel.height)
: rowGridHeight;
let panelPos = rowArea.getPanelPosition(panelHeight, panelWidth); let panelPos = rowArea.getPanelPosition(panelHeight, panelWidth);
yPos = rowArea.yPos; yPos = rowArea.yPos;
@ -539,11 +534,7 @@ class RowArea {
} }
} }
if ( if (startPlace !== undefined && endPlace !== undefined && endPlace - startPlace >= panelWidth - 1) {
startPlace !== undefined &&
endPlace !== undefined &&
endPlace - startPlace >= panelWidth - 1
) {
const yPos = _.max(this.area.slice(startPlace)); const yPos = _.max(this.area.slice(startPlace));
place = { place = {
x: startPlace, x: startPlace,

View File

@ -75,10 +75,7 @@ export class DashboardModel {
this.version = data.version || 0; this.version = data.version || 0;
this.links = data.links || []; this.links = data.links || [];
this.gnetId = data.gnetId || null; this.gnetId = data.gnetId || null;
this.panels = _.map( this.panels = _.map(data.panels || [], panelData => new PanelModel(panelData));
data.panels || [],
panelData => new PanelModel(panelData)
);
this.initMeta(meta); this.initMeta(meta);
this.updateSchema(data); this.updateSchema(data);
@ -135,10 +132,7 @@ export class DashboardModel {
// make clone // make clone
var copy: any = {}; var copy: any = {};
for (var property in this) { for (var property in this) {
if ( if (DashboardModel.nonPersistedProperties[property] || !this.hasOwnProperty(property)) {
DashboardModel.nonPersistedProperties[property] ||
!this.hasOwnProperty(property)
) {
continue; continue;
} }
@ -147,10 +141,7 @@ export class DashboardModel {
// get variable save models // get variable save models
copy.templating = { copy.templating = {
list: _.map( list: _.map(this.templating.list, variable => (variable.getSaveModel ? variable.getSaveModel() : variable)),
this.templating.list,
variable => (variable.getSaveModel ? variable.getSaveModel() : variable)
),
}; };
// get panel save models // get panel save models
@ -261,10 +252,7 @@ export class DashboardModel {
if (!cleanUpOnly) { if (!cleanUpOnly) {
this.repeatPanel(panel, i); this.repeatPanel(panel, i);
} }
} else if ( } else if (panel.repeatPanelId && panel.repeatIteration !== this.iteration) {
panel.repeatPanelId &&
panel.repeatIteration !== this.iteration
) {
panelsToRemove.push(panel); panelsToRemove.push(panel);
} }
} }
@ -355,10 +343,7 @@ export class DashboardModel {
// set width based on how many are selected // set width based on how many are selected
// assumed the repeated panels should take up full row width // assumed the repeated panels should take up full row width
copy.gridPos.w = Math.max( copy.gridPos.w = Math.max(GRID_COLUMN_COUNT / selectedOptions.length, minWidth);
GRID_COLUMN_COUNT / selectedOptions.length,
minWidth
);
copy.gridPos.x = xPos; copy.gridPos.x = xPos;
copy.gridPos.y = yPos; copy.gridPos.y = yPos;
@ -382,11 +367,7 @@ export class DashboardModel {
panel.scopedVars[variable.name] = variableOption; panel.scopedVars[variable.name] = variableOption;
} }
for ( for (let optionIndex = 0; optionIndex < selectedOptions.length; optionIndex++) {
let optionIndex = 0;
optionIndex < selectedOptions.length;
optionIndex++
) {
let option = selectedOptions[optionIndex]; let option = selectedOptions[optionIndex];
let rowCopy = this.getRowRepeatClone(panel, optionIndex, panelIndex); let rowCopy = this.getRowRepeatClone(panel, optionIndex, panelIndex);
setScopedVars(rowCopy, option); setScopedVars(rowCopy, option);
@ -468,8 +449,7 @@ export class DashboardModel {
} }
removeRow(row: PanelModel, removePanels: boolean) { removeRow(row: PanelModel, removePanels: boolean) {
const needToogle = const needToogle = (!removePanels && row.collapsed) || (removePanels && !row.collapsed);
(!removePanels && row.collapsed) || (removePanels && !row.collapsed);
if (needToogle) { if (needToogle) {
this.toggleRow(row); this.toggleRow(row);
@ -488,18 +468,12 @@ export class DashboardModel {
return true; return true;
} }
var visibleVars = _.filter( var visibleVars = _.filter(this.templating.list, variable => variable.hide !== 2);
this.templating.list,
variable => variable.hide !== 2
);
if (visibleVars.length > 0) { if (visibleVars.length > 0) {
return true; return true;
} }
var visibleAnnotations = _.filter( var visibleAnnotations = _.filter(this.annotations.list, annotation => annotation.hide !== true);
this.annotations.list,
annotation => annotation.hide !== true
);
if (visibleAnnotations.length > 0) { if (visibleAnnotations.length > 0) {
return true; return true;
} }
@ -551,9 +525,7 @@ export class DashboardModel {
format = format || 'YYYY-MM-DD HH:mm:ss'; format = format || 'YYYY-MM-DD HH:mm:ss';
let timezone = this.getTimezone(); let timezone = this.getTimezone();
return timezone === 'browser' return timezone === 'browser' ? moment(date).format(format) : moment.utc(date).format(format);
? moment(date).format(format)
: moment.utc(date).format(format);
} }
destroy() { destroy() {
@ -593,11 +565,7 @@ export class DashboardModel {
const pushDownAmount = yMax - row.gridPos.y; const pushDownAmount = yMax - row.gridPos.y;
// push panels below down // push panels below down
for ( for (let panelIndex = insertPos; panelIndex < this.panels.length; panelIndex++) {
let panelIndex = insertPos;
panelIndex < this.panels.length;
panelIndex++
) {
this.panels[panelIndex].gridPos.y += pushDownAmount; this.panels[panelIndex].gridPos.y += pushDownAmount;
} }
@ -668,9 +636,7 @@ export class DashboardModel {
getRelativeTime(date) { getRelativeTime(date) {
date = moment.isMoment(date) ? date : moment(date); date = moment.isMoment(date) ? date : moment(date);
return this.timezone === 'browser' return this.timezone === 'browser' ? moment(date).fromNow() : moment.utc(date).fromNow();
? moment(date).fromNow()
: moment.utc(date).fromNow();
} }
getNextQueryLetter(panel) { getNextQueryLetter(panel) {

View File

@ -56,8 +56,7 @@ export class DashboardSrv {
this.$rootScope.appEvent('confirm-modal', { this.$rootScope.appEvent('confirm-modal', {
title: 'Plugin Dashboard', title: 'Plugin Dashboard',
text: err.data.message, text: err.data.message,
text2: text2: 'Your changes will be lost when you update the plugin. Use Save As to create custom version.',
'Your changes will be lost when you update the plugin. Use Save As to create custom version.',
yesText: 'Overwrite', yesText: 'Overwrite',
icon: 'fa-warning', icon: 'fa-warning',
altActionText: 'Save As', altActionText: 'Save As',
@ -115,16 +114,14 @@ export class DashboardSrv {
showSaveAsModal() { showSaveAsModal() {
this.$rootScope.appEvent('show-modal', { this.$rootScope.appEvent('show-modal', {
templateHtml: templateHtml: '<save-dashboard-as-modal dismiss="dismiss()"></save-dashboard-as-modal>',
'<save-dashboard-as-modal dismiss="dismiss()"></save-dashboard-as-modal>',
modalClass: 'modal--narrow', modalClass: 'modal--narrow',
}); });
} }
showSaveModal() { showSaveModal() {
this.$rootScope.appEvent('show-modal', { this.$rootScope.appEvent('show-modal', {
templateHtml: templateHtml: '<save-dashboard-modal dismiss="dismiss()"></save-dashboard-modal>',
'<save-dashboard-modal dismiss="dismiss()"></save-dashboard-modal>',
modalClass: 'modal--narrow', modalClass: 'modal--narrow',
}); });
} }
@ -133,15 +130,11 @@ export class DashboardSrv {
let promise; let promise;
if (isStarred) { if (isStarred) {
promise = this.backendSrv promise = this.backendSrv.delete('/api/user/stars/dashboard/' + dashboardId).then(() => {
.delete('/api/user/stars/dashboard/' + dashboardId)
.then(() => {
return false; return false;
}); });
} else { } else {
promise = this.backendSrv promise = this.backendSrv.post('/api/user/stars/dashboard/' + dashboardId).then(() => {
.post('/api/user/stars/dashboard/' + dashboardId)
.then(() => {
return true; return true;
}); });
} }

View File

@ -10,8 +10,7 @@ export class PanelLoader {
constructor(private $compile, private $rootScope) {} constructor(private $compile, private $rootScope) {}
load(elem, panel, dashboard): AttachedPanel { load(elem, panel, dashboard): AttachedPanel {
var template = var template = '<plugin-component type="panel" class="panel-height-helper"></plugin-component>';
'<plugin-component type="panel" class="panel-height-helper"></plugin-component>';
var panelScope = this.$rootScope.$new(); var panelScope = this.$rootScope.$new();
panelScope.panel = panel; panelScope.panel = panel;
panelScope.dashboard = dashboard; panelScope.dashboard = dashboard;

View File

@ -9,20 +9,14 @@ export class DashNavCtrl {
titleTooltip: string; titleTooltip: string;
/** @ngInject */ /** @ngInject */
constructor( constructor(private $scope, private dashboardSrv, private $location, public playlistSrv) {
private $scope,
private dashboardSrv,
private $location,
public playlistSrv
) {
appEvents.on('save-dashboard', this.saveDashboard.bind(this), $scope); appEvents.on('save-dashboard', this.saveDashboard.bind(this), $scope);
if (this.dashboard.meta.isSnapshot) { if (this.dashboard.meta.isSnapshot) {
var meta = this.dashboard.meta; var meta = this.dashboard.meta;
this.titleTooltip = 'Created: &nbsp;' + moment(meta.created).calendar(); this.titleTooltip = 'Created: &nbsp;' + moment(meta.created).calendar();
if (meta.expires) { if (meta.expires) {
this.titleTooltip += this.titleTooltip += '<br>Expires: &nbsp;' + moment(meta.expires).fromNow() + '<br>';
'<br>Expires: &nbsp;' + moment(meta.expires).fromNow() + '<br>';
} }
} }
} }
@ -50,9 +44,7 @@ export class DashNavCtrl {
} }
starDashboard() { starDashboard() {
this.dashboardSrv this.dashboardSrv.starDashboard(this.dashboard.id, this.dashboard.meta.isStarred).then(newState => {
.starDashboard(this.dashboard.id, this.dashboard.meta.isStarred)
.then(newState => {
this.dashboard.meta.isStarred = newState; this.dashboard.meta.isStarred = newState;
}); });
} }
@ -81,10 +73,7 @@ export class DashNavCtrl {
} }
addPanel() { addPanel() {
if ( if (this.dashboard.panels.length > 0 && this.dashboard.panels[0].type === 'add-panel') {
this.dashboard.panels.length > 0 &&
this.dashboard.panels[0].type === 'add-panel'
) {
this.dashboard.removePanel(this.dashboard.panels[0]); this.dashboard.removePanel(this.dashboard.panels[0]);
return; return;
} }

View File

@ -10,12 +10,7 @@ export class DashExportCtrl {
dismiss: () => void; dismiss: () => void;
/** @ngInject */ /** @ngInject */
constructor( constructor(private dashboardSrv, datasourceSrv, private $scope, private $rootScope) {
private dashboardSrv,
datasourceSrv,
private $scope,
private $rootScope
) {
this.exporter = new DashboardExporter(datasourceSrv); this.exporter = new DashboardExporter(datasourceSrv);
this.exporter.makeExportable(this.dashboardSrv.getCurrent()).then(dash => { this.exporter.makeExportable(this.dashboardSrv.getCurrent()).then(dash => {

View File

@ -120,8 +120,7 @@ export class DashboardExporter {
// templatize constants // templatize constants
for (let variable of saveModel.templating.list) { for (let variable of saveModel.templating.list) {
if (variable.type === 'constant') { if (variable.type === 'constant') {
var refName = var refName = 'VAR_' + variable.name.replace(' ', '_').toUpperCase();
'VAR_' + variable.name.replace(' ', '_').toUpperCase();
inputs.push({ inputs.push({
name: refName, name: refName,
type: 'constant', type: 'constant',

View File

@ -14,17 +14,9 @@ export class ExportDataModalCtrl {
fileExport.exportTableDataToCsv(this.data, this.excel); fileExport.exportTableDataToCsv(this.data, this.excel);
} else { } else {
if (this.asRows) { if (this.asRows) {
fileExport.exportSeriesListToCsv( fileExport.exportSeriesListToCsv(this.data, this.dateTimeFormat, this.excel);
this.data,
this.dateTimeFormat,
this.excel
);
} else { } else {
fileExport.exportSeriesListToCsvColumns( fileExport.exportSeriesListToCsvColumns(this.data, this.dateTimeFormat, this.excel);
this.data,
this.dateTimeFormat,
this.excel
);
} }
} }
@ -39,8 +31,7 @@ export class ExportDataModalCtrl {
export function exportDataModal() { export function exportDataModal() {
return { return {
restrict: 'E', restrict: 'E',
templateUrl: templateUrl: 'public/app/features/dashboard/export_data/export_data_modal.html',
'public/app/features/dashboard/export_data/export_data_modal.html',
controller: ExportDataModalCtrl, controller: ExportDataModalCtrl,
controllerAs: 'ctrl', controllerAs: 'ctrl',
scope: { scope: {
@ -51,6 +42,4 @@ export function exportDataModal() {
}; };
} }
angular angular.module('grafana.directives').directive('exportDataModal', exportDataModal);
.module('grafana.directives')
.directive('exportDataModal', exportDataModal);

View File

@ -11,10 +11,7 @@ export class FolderPageLoader {
subTitle: 'Manage folder dashboards & permissions', subTitle: 'Manage folder dashboards & permissions',
url: '', url: '',
text: '', text: '',
breadcrumbs: [ breadcrumbs: [{ title: 'Dashboards', url: '/dashboards' }, { title: ' ' }],
{ title: 'Dashboards', url: '/dashboards' },
{ title: ' ' },
],
children: [ children: [
{ {
active: activeChildId === 'manage-folder-dashboards', active: activeChildId === 'manage-folder-dashboards',
@ -41,21 +38,12 @@ export class FolderPageLoader {
}, },
}; };
return this.backendSrv return this.backendSrv.getDashboard('db', this.$routeParams.slug).then(result => {
.getDashboard('db', this.$routeParams.slug)
.then(result => {
const folderTitle = result.dashboard.title; const folderTitle = result.dashboard.title;
ctrl.navModel.main.text = ''; ctrl.navModel.main.text = '';
ctrl.navModel.main.breadcrumbs = [ ctrl.navModel.main.breadcrumbs = [{ title: 'Dashboards', url: '/dashboards' }, { title: folderTitle }];
{ title: 'Dashboards', url: '/dashboards' },
{ title: folderTitle },
];
const folderUrl = this.createFolderUrl( const folderUrl = this.createFolderUrl(folderId, result.meta.type, result.meta.slug);
folderId,
result.meta.type,
result.meta.slug
);
const dashTab = _.find(ctrl.navModel.main.children, { const dashTab = _.find(ctrl.navModel.main.children, {
id: 'manage-folder-dashboards', id: 'manage-folder-dashboards',

View File

@ -9,11 +9,7 @@ export class FolderPermissionsCtrl {
if (this.$routeParams.folderId && this.$routeParams.slug) { if (this.$routeParams.folderId && this.$routeParams.slug) {
this.folderId = $routeParams.folderId; this.folderId = $routeParams.folderId;
new FolderPageLoader(this.backendSrv, this.$routeParams).load( new FolderPageLoader(this.backendSrv, this.$routeParams).load(this, this.folderId, 'manage-folder-permissions');
this,
this.folderId,
'manage-folder-permissions'
);
} }
} }
} }

View File

@ -85,9 +85,7 @@ export class FolderPickerCtrl {
evt.preventDefault(); evt.preventDefault();
} }
return this.backendSrv return this.backendSrv.createDashboardFolder(this.newFolderName).then(result => {
.createDashboardFolder(this.newFolderName)
.then(result => {
appEvents.emit('alert-success', ['Folder Created', 'OK']); appEvents.emit('alert-success', ['Folder Created', 'OK']);
this.closeCreateFolder(); this.closeCreateFolder();
@ -147,8 +145,7 @@ export class FolderPickerCtrl {
export function folderPicker() { export function folderPicker() {
return { return {
restrict: 'E', restrict: 'E',
templateUrl: templateUrl: 'public/app/features/dashboard/folder_picker/folder_picker.html',
'public/app/features/dashboard/folder_picker/folder_picker.html',
controller: FolderPickerCtrl, controller: FolderPickerCtrl,
bindToController: true, bindToController: true,
controllerAs: 'ctrl', controllerAs: 'ctrl',

View File

@ -12,22 +12,12 @@ export class FolderSettingsCtrl {
hasChanged: boolean; hasChanged: boolean;
/** @ngInject */ /** @ngInject */
constructor( constructor(private backendSrv, navModelSrv, private $routeParams, private $location) {
private backendSrv,
navModelSrv,
private $routeParams,
private $location
) {
if (this.$routeParams.folderId && this.$routeParams.slug) { if (this.$routeParams.folderId && this.$routeParams.slug) {
this.folderId = $routeParams.folderId; this.folderId = $routeParams.folderId;
this.folderPageLoader = new FolderPageLoader( this.folderPageLoader = new FolderPageLoader(this.backendSrv, this.$routeParams);
this.backendSrv, this.folderPageLoader.load(this, this.folderId, 'manage-folder-settings').then(result => {
this.$routeParams
);
this.folderPageLoader
.load(this, this.folderId, 'manage-folder-settings')
.then(result => {
this.dashboard = result.dashboard; this.dashboard = result.dashboard;
this.meta = result.meta; this.meta = result.meta;
this.canSave = result.meta.canSave; this.canSave = result.meta.canSave;
@ -48,11 +38,7 @@ export class FolderSettingsCtrl {
return this.backendSrv return this.backendSrv
.saveDashboard(this.dashboard, { overwrite: false }) .saveDashboard(this.dashboard, { overwrite: false })
.then(result => { .then(result => {
var folderUrl = this.folderPageLoader.createFolderUrl( var folderUrl = this.folderPageLoader.createFolderUrl(this.folderId, this.meta.type, result.slug);
this.folderId,
this.meta.type,
result.slug
);
if (folderUrl !== this.$location.path()) { if (folderUrl !== this.$location.path()) {
this.$location.url(folderUrl + '/settings'); this.$location.url(folderUrl + '/settings');
} }
@ -64,8 +50,7 @@ export class FolderSettingsCtrl {
} }
titleChanged() { titleChanged() {
this.hasChanged = this.hasChanged = this.dashboard.title.toLowerCase() !== this.title.trim().toLowerCase();
this.dashboard.title.toLowerCase() !== this.title.trim().toLowerCase();
} }
delete(evt) { delete(evt) {
@ -81,10 +66,7 @@ export class FolderSettingsCtrl {
yesText: 'Delete', yesText: 'Delete',
onConfirm: () => { onConfirm: () => {
return this.backendSrv.deleteDashboard(this.meta.slug).then(() => { return this.backendSrv.deleteDashboard(this.meta.slug).then(() => {
appEvents.emit('alert-success', [ appEvents.emit('alert-success', ['Folder Deleted', `${this.dashboard.title} has been deleted`]);
'Folder Deleted',
`${this.dashboard.title} has been deleted`,
]);
this.$location.url('/dashboards'); this.$location.url('/dashboards');
}); });
}, },
@ -110,9 +92,7 @@ export class FolderSettingsCtrl {
if (err.data && err.data.status === 'name-exists') { if (err.data && err.data.status === 'name-exists') {
err.isHandled = true; err.isHandled = true;
appEvents.emit('alert-error', [ appEvents.emit('alert-error', ['A folder or dashboard with this name exists already.']);
'A folder or dashboard with this name exists already.',
]);
} }
} }
} }

View File

@ -5,12 +5,7 @@ import angular from 'angular';
import moment from 'moment'; import moment from 'moment';
import { DashboardModel } from '../dashboard_model'; import { DashboardModel } from '../dashboard_model';
import { import { HistoryListOpts, RevisionsModel, CalculateDiffOptions, HistorySrv } from './history_srv';
HistoryListOpts,
RevisionsModel,
CalculateDiffOptions,
HistorySrv,
} from './history_srv';
export class HistoryListCtrl { export class HistoryListCtrl {
appending: boolean; appending: boolean;
@ -46,11 +41,7 @@ export class HistoryListCtrl {
this.start = 0; this.start = 0;
this.canCompare = false; this.canCompare = false;
this.$rootScope.onAppEvent( this.$rootScope.onAppEvent('dashboard-saved', this.onDashboardSaved.bind(this), $scope);
'dashboard-saved',
this.onDashboardSaved.bind(this),
$scope
);
this.resetFromSource(); this.resetFromSource();
} }
@ -85,8 +76,7 @@ export class HistoryListCtrl {
formatBasicDate(date) { formatBasicDate(date) {
const now = this.dashboard.timezone === 'browser' ? moment() : moment.utc(); const now = this.dashboard.timezone === 'browser' ? moment() : moment.utc();
const then = const then = this.dashboard.timezone === 'browser' ? moment(date) : moment.utc(date);
this.dashboard.timezone === 'browser' ? moment(date) : moment.utc(date);
return then.from(now); return then.from(now);
} }
@ -168,9 +158,7 @@ export class HistoryListCtrl {
this.delta = { basic: '', json: '' }; this.delta = { basic: '', json: '' };
this.diff = 'basic'; this.diff = 'basic';
this.mode = 'list'; this.mode = 'list';
this.revisions = _.map(this.revisions, rev => this.revisions = _.map(this.revisions, rev => _.extend({}, rev, { checked: false }));
_.extend({}, rev, { checked: false })
);
this.canCompare = false; this.canCompare = false;
this.start = 0; this.start = 0;
this.isNewLatest = false; this.isNewLatest = false;
@ -199,10 +187,7 @@ export class HistoryListCtrl {
.then(response => { .then(response => {
this.$location.path('dashboard/db/' + response.slug); this.$location.path('dashboard/db/' + response.slug);
this.$route.reload(); this.$route.reload();
this.$rootScope.appEvent('alert-success', [ this.$rootScope.appEvent('alert-success', ['Dashboard restored', 'Restored from version ' + version]);
'Dashboard restored',
'Restored from version ' + version,
]);
}) })
.catch(() => { .catch(() => {
this.mode = 'list'; this.mode = 'list';
@ -224,6 +209,4 @@ export function dashboardHistoryDirective() {
}; };
} }
angular angular.module('grafana.directives').directive('gfDashboardHistory', dashboardHistoryDirective);
.module('grafana.directives')
.directive('gfDashboardHistory', dashboardHistoryDirective);

View File

@ -36,9 +36,7 @@ export class HistorySrv {
getHistoryList(dashboard: DashboardModel, options: HistoryListOpts) { getHistoryList(dashboard: DashboardModel, options: HistoryListOpts) {
const id = dashboard && dashboard.id ? dashboard.id : void 0; const id = dashboard && dashboard.id ? dashboard.id : void 0;
return id return id ? this.backendSrv.get(`api/dashboards/id/${id}/versions`, options) : this.$q.when([]);
? this.backendSrv.get(`api/dashboards/id/${id}/versions`, options)
: this.$q.when([]);
} }
calculateDiff(options: CalculateDiffOptions) { calculateDiff(options: CalculateDiffOptions) {
@ -48,9 +46,7 @@ export class HistorySrv {
restoreDashboard(dashboard: DashboardModel, version: number) { restoreDashboard(dashboard: DashboardModel, version: number) {
const id = dashboard && dashboard.id ? dashboard.id : void 0; const id = dashboard && dashboard.id ? dashboard.id : void 0;
const url = `api/dashboards/id/${id}/restore`; const url = `api/dashboards/id/${id}/restore`;
return id && _.isNumber(version) return id && _.isNumber(version) ? this.backendSrv.post(url, { version }) : this.$q.when({});
? this.backendSrv.post(url, { version })
: this.$q.when({});
} }
} }

View File

@ -16,24 +16,17 @@ export class MoveToFolderCtrl {
} }
save() { save() {
return this.backendSrv return this.backendSrv.moveDashboards(this.dashboards, this.folder).then(result => {
.moveDashboards(this.dashboards, this.folder)
.then(result => {
if (result.successCount > 0) { if (result.successCount > 0) {
const header = `Dashboard${ const header = `Dashboard${result.successCount === 1 ? '' : 's'} Moved`;
result.successCount === 1 ? '' : 's' const msg = `${result.successCount} dashboard${result.successCount === 1 ? '' : 's'} moved to ${
} Moved`; this.folder.title
const msg = `${result.successCount} dashboard${ }`;
result.successCount === 1 ? '' : 's'
} moved to ${this.folder.title}`;
appEvents.emit('alert-success', [header, msg]); appEvents.emit('alert-success', [header, msg]);
} }
if (result.totalCount === result.alreadyInFolderCount) { if (result.totalCount === result.alreadyInFolderCount) {
appEvents.emit('alert-error', [ appEvents.emit('alert-error', ['Error', `Dashboards already belongs to folder ${this.folder.title}`]);
'Error',
`Dashboards already belongs to folder ${this.folder.title}`,
]);
} }
this.dismiss(); this.dismiss();
@ -53,8 +46,7 @@ export class MoveToFolderCtrl {
export function moveToFolderModal() { export function moveToFolderModal() {
return { return {
restrict: 'E', restrict: 'E',
templateUrl: templateUrl: 'public/app/features/dashboard/move_to_folder_modal/move_to_folder.html',
'public/app/features/dashboard/move_to_folder_modal/move_to_folder.html',
controller: MoveToFolderCtrl, controller: MoveToFolderCtrl,
bindToController: true, bindToController: true,
controllerAs: 'ctrl', controllerAs: 'ctrl',

View File

@ -14,13 +14,7 @@ export class SettingsCtrl {
sections: any[]; sections: any[];
/** @ngInject */ /** @ngInject */
constructor( constructor(private $scope, private $location, private $rootScope, private backendSrv, private dashboardSrv) {
private $scope,
private $location,
private $rootScope,
private backendSrv,
private dashboardSrv
) {
// temp hack for annotations and variables editors // temp hack for annotations and variables editors
// that rely on inherited scope // that rely on inherited scope
$scope.dashboard = this.dashboard; $scope.dashboard = this.dashboard;
@ -36,11 +30,7 @@ export class SettingsCtrl {
this.buildSectionList(); this.buildSectionList();
this.onRouteUpdated(); this.onRouteUpdated();
$rootScope.onAppEvent( $rootScope.onAppEvent('$routeUpdate', this.onRouteUpdated.bind(this), $scope);
'$routeUpdate',
this.onRouteUpdated.bind(this),
$scope
);
} }
buildSectionList() { buildSectionList() {
@ -139,9 +129,7 @@ export class SettingsCtrl {
makeEditable() { makeEditable() {
this.dashboard.editable = true; this.dashboard.editable = true;
return this.dashboardSrv return this.dashboardSrv.saveDashboard({ makeEditable: true, overwrite: false }).then(() => {
.saveDashboard({ makeEditable: true, overwrite: false })
.then(() => {
// force refresh whole page // force refresh whole page
window.location.href = window.location.href; window.location.href = window.location.href;
}); });
@ -176,10 +164,7 @@ export class SettingsCtrl {
deleteDashboardConfirmed() { deleteDashboardConfirmed() {
this.backendSrv.deleteDashboard(this.dashboard.meta.slug).then(() => { this.backendSrv.deleteDashboard(this.dashboard.meta.slug).then(() => {
appEvents.emit('alert-success', [ appEvents.emit('alert-success', ['Dashboard Deleted', this.dashboard.title + ' has been deleted']);
'Dashboard Deleted',
this.dashboard.title + ' has been deleted',
]);
this.$location.url('/'); this.$location.url('/');
}); });
} }

View File

@ -4,15 +4,7 @@ import config from 'app/core/config';
export class ShareModalCtrl { export class ShareModalCtrl {
/** @ngInject */ /** @ngInject */
constructor( constructor($scope, $rootScope, $location, $timeout, timeSrv, templateSrv, linkSrv) {
$scope,
$rootScope,
$location,
$timeout,
timeSrv,
templateSrv,
linkSrv
) {
$scope.options = { $scope.options = {
forCurrent: true, forCurrent: true,
includeTemplateVars: true, includeTemplateVars: true,
@ -81,18 +73,12 @@ export class ShareModalCtrl {
$scope.shareUrl = linkSrv.addParamsToUrl(baseUrl, params); $scope.shareUrl = linkSrv.addParamsToUrl(baseUrl, params);
var soloUrl = baseUrl.replace( var soloUrl = baseUrl.replace(config.appSubUrl + '/dashboard/', config.appSubUrl + '/dashboard-solo/');
config.appSubUrl + '/dashboard/',
config.appSubUrl + '/dashboard-solo/'
);
delete params.fullscreen; delete params.fullscreen;
delete params.edit; delete params.edit;
soloUrl = linkSrv.addParamsToUrl(soloUrl, params); soloUrl = linkSrv.addParamsToUrl(soloUrl, params);
$scope.iframeHtml = $scope.iframeHtml = '<iframe src="' + soloUrl + '" width="450" height="200" frameborder="0"></iframe>';
'<iframe src="' +
soloUrl +
'" width="450" height="200" frameborder="0"></iframe>';
$scope.imageUrl = soloUrl.replace( $scope.imageUrl = soloUrl.replace(
config.appSubUrl + '/dashboard-solo/', config.appSubUrl + '/dashboard-solo/',
@ -109,6 +95,4 @@ export class ShareModalCtrl {
} }
} }
angular angular.module('grafana.controllers').controller('ShareModalCtrl', ShareModalCtrl);
.module('grafana.controllers')
.controller('ShareModalCtrl', ShareModalCtrl);

View File

@ -19,19 +19,10 @@ describe('DashboardImportCtrl', function() {
}; };
validationSrv = { validationSrv = {
validateNewDashboardOrFolderName: jest validateNewDashboardOrFolderName: jest.fn().mockReturnValue(Promise.resolve()),
.fn()
.mockReturnValue(Promise.resolve()),
}; };
ctx.ctrl = new DashboardImportCtrl( ctx.ctrl = new DashboardImportCtrl(backendSrv, validationSrv, navModelSrv, {}, {}, {});
backendSrv,
validationSrv,
navModelSrv,
{},
{},
{}
);
}); });
describe('when uploading json', function() { describe('when uploading json', function() {

View File

@ -54,10 +54,7 @@ describe('DashboardModel', function() {
{ {
type: 'table', type: 'table',
legend: true, legend: true,
styles: [ styles: [{ thresholds: ['10', '20', '30'] }, { thresholds: ['100', '200', '300'] }],
{ thresholds: ['10', '20', '30'] },
{ thresholds: ['100', '200', '300'] },
],
targets: [{ refId: 'A' }, {}], targets: [{ refId: 'A' }, {}],
}, },
], ],
@ -156,19 +153,13 @@ describe('DashboardModel', function() {
model.rows = [createRow({ collapse: false, height: 8 }, [[6], [6]])]; model.rows = [createRow({ collapse: false, height: 8 }, [[6], [6]])];
let dashboard = new DashboardModel(model); let dashboard = new DashboardModel(model);
let panelGridPos = getGridPositions(dashboard); let panelGridPos = getGridPositions(dashboard);
let expectedGrid = [ let expectedGrid = [{ x: 0, y: 0, w: 12, h: 8 }, { x: 12, y: 0, w: 12, h: 8 }];
{ x: 0, y: 0, w: 12, h: 8 },
{ x: 12, y: 0, w: 12, h: 8 },
];
expect(panelGridPos).toEqual(expectedGrid); expect(panelGridPos).toEqual(expectedGrid);
}); });
it('should add special "row" panel if row is collapsed', function() { it('should add special "row" panel if row is collapsed', function() {
model.rows = [ model.rows = [createRow({ collapse: true, height: 8 }, [[6], [6]]), createRow({ height: 8 }, [[12]])];
createRow({ collapse: true, height: 8 }, [[6], [6]]),
createRow({ height: 8 }, [[12]]),
];
let dashboard = new DashboardModel(model); let dashboard = new DashboardModel(model);
let panelGridPos = getGridPositions(dashboard); let panelGridPos = getGridPositions(dashboard);
let expectedGrid = [ let expectedGrid = [
@ -222,10 +213,7 @@ describe('DashboardModel', function() {
}); });
it('should add all rows if even one collapsed or titled row is present', function() { it('should add all rows if even one collapsed or titled row is present', function() {
model.rows = [ model.rows = [createRow({ collapse: true, height: 8 }, [[6], [6]]), createRow({ height: 8 }, [[12]])];
createRow({ collapse: true, height: 8 }, [[6], [6]]),
createRow({ height: 8 }, [[12]]),
];
let dashboard = new DashboardModel(model); let dashboard = new DashboardModel(model);
let panelGridPos = getGridPositions(dashboard); let panelGridPos = getGridPositions(dashboard);
let expectedGrid = [ let expectedGrid = [
@ -258,9 +246,7 @@ describe('DashboardModel', function() {
}); });
it('should place panel to the right side of panel having bigger height', function() { it('should place panel to the right side of panel having bigger height', function() {
model.rows = [ model.rows = [createRow({ height: 6 }, [[4], [2, 3], [4, 6], [2, 3], [2, 3]])];
createRow({ height: 6 }, [[4], [2, 3], [4, 6], [2, 3], [2, 3]]),
];
let dashboard = new DashboardModel(model); let dashboard = new DashboardModel(model);
let panelGridPos = getGridPositions(dashboard); let panelGridPos = getGridPositions(dashboard);
let expectedGrid = [ let expectedGrid = [
@ -275,9 +261,7 @@ describe('DashboardModel', function() {
}); });
it('should fill current row if it possible', function() { it('should fill current row if it possible', function() {
model.rows = [ model.rows = [createRow({ height: 9 }, [[4], [2, 3], [4, 6], [2, 3], [2, 3], [8, 3]])];
createRow({ height: 9 }, [[4], [2, 3], [4, 6], [2, 3], [2, 3], [8, 3]]),
];
let dashboard = new DashboardModel(model); let dashboard = new DashboardModel(model);
let panelGridPos = getGridPositions(dashboard); let panelGridPos = getGridPositions(dashboard);
let expectedGrid = [ let expectedGrid = [
@ -293,9 +277,7 @@ describe('DashboardModel', function() {
}); });
it('should fill current row if it possible (2)', function() { it('should fill current row if it possible (2)', function() {
model.rows = [ model.rows = [createRow({ height: 8 }, [[4], [2, 3], [4, 6], [2, 3], [2, 3], [8, 3]])];
createRow({ height: 8 }, [[4], [2, 3], [4, 6], [2, 3], [2, 3], [8, 3]]),
];
let dashboard = new DashboardModel(model); let dashboard = new DashboardModel(model);
let panelGridPos = getGridPositions(dashboard); let panelGridPos = getGridPositions(dashboard);
let expectedGrid = [ let expectedGrid = [
@ -311,9 +293,7 @@ describe('DashboardModel', function() {
}); });
it('should fill current row if panel height more than row height', function() { it('should fill current row if panel height more than row height', function() {
model.rows = [ model.rows = [createRow({ height: 6 }, [[4], [2, 3], [4, 8], [2, 3], [2, 3]])];
createRow({ height: 6 }, [[4], [2, 3], [4, 8], [2, 3], [2, 3]]),
];
let dashboard = new DashboardModel(model); let dashboard = new DashboardModel(model);
let panelGridPos = getGridPositions(dashboard); let panelGridPos = getGridPositions(dashboard);
let expectedGrid = [ let expectedGrid = [
@ -345,10 +325,7 @@ describe('DashboardModel', function() {
it('should add repeated row if repeat set', function() { it('should add repeated row if repeat set', function() {
model.rows = [ model.rows = [
createRow( createRow({ showTitle: true, title: 'Row', height: 8, repeat: 'server' }, [[6]]),
{ showTitle: true, title: 'Row', height: 8, repeat: 'server' },
[[6]]
),
createRow({ height: 8 }, [[12]]), createRow({ height: 8 }, [[12]]),
]; ];
let dashboard = new DashboardModel(model); let dashboard = new DashboardModel(model);
@ -369,10 +346,7 @@ describe('DashboardModel', function() {
it('should ignore repeated row', function() { it('should ignore repeated row', function() {
model.rows = [ model.rows = [
createRow( createRow({ showTitle: true, title: 'Row1', height: 8, repeat: 'server' }, [[6]]),
{ showTitle: true, title: 'Row1', height: 8, repeat: 'server' },
[[6]]
),
createRow( createRow(
{ {
showTitle: true, showTitle: true,

View File

@ -216,15 +216,11 @@ describe('DashboardModel', function() {
}); });
it('Should format timestamp with second resolution even if second format is passed as parameter', function() { it('Should format timestamp with second resolution even if second format is passed as parameter', function() {
expect(dashboard.formatDate(1234567890007, 'YYYY-MM-DD HH:mm:ss')).toBe( expect(dashboard.formatDate(1234567890007, 'YYYY-MM-DD HH:mm:ss')).toBe('2009-02-13 23:31:30');
'2009-02-13 23:31:30'
);
}); });
it('Should format timestamp with millisecond resolution if format is passed as parameter', function() { it('Should format timestamp with millisecond resolution if format is passed as parameter', function() {
expect( expect(dashboard.formatDate(1234567890007, 'YYYY-MM-DD HH:mm:ss.SSS')).toBe('2009-02-13 23:31:30.007');
dashboard.formatDate(1234567890007, 'YYYY-MM-DD HH:mm:ss.SSS')
).toBe('2009-02-13 23:31:30.007');
}); });
}); });

View File

@ -1,11 +1,4 @@
import { import { describe, beforeEach, it, sinon, expect, angularMocks } from 'test/lib/common';
describe,
beforeEach,
it,
sinon,
expect,
angularMocks,
} from 'test/lib/common';
import _ from 'lodash'; import _ from 'lodash';
import { HistoryListCtrl } from 'app/features/dashboard/history/history'; import { HistoryListCtrl } from 'app/features/dashboard/history/history';
@ -95,9 +88,7 @@ describe('HistoryListCtrl', function() {
}); });
it('should add a checked property to each revision', function() { it('should add a checked property to each revision', function() {
var actual = _.filter(ctx.ctrl.revisions, rev => var actual = _.filter(ctx.ctrl.revisions, rev => rev.hasOwnProperty('checked'));
rev.hasOwnProperty('checked')
);
expect(actual.length).to.be(4); expect(actual.length).to.be(4);
}); });
@ -139,18 +130,12 @@ describe('HistoryListCtrl', function() {
it('should listen for the `dashboard-saved` appEvent', function() { it('should listen for the `dashboard-saved` appEvent', function() {
expect($rootScope.onAppEvent.calledOnce).to.be(true); expect($rootScope.onAppEvent.calledOnce).to.be(true);
expect($rootScope.onAppEvent.getCall(0).args[0]).to.be( expect($rootScope.onAppEvent.getCall(0).args[0]).to.be('dashboard-saved');
'dashboard-saved'
);
}); });
it('should call `onDashboardSaved` when the appEvent is received', function() { it('should call `onDashboardSaved` when the appEvent is received', function() {
expect($rootScope.onAppEvent.getCall(0).args[1]).to.not.be( expect($rootScope.onAppEvent.getCall(0).args[1]).to.not.be(ctx.ctrl.onDashboardSaved);
ctx.ctrl.onDashboardSaved expect($rootScope.onAppEvent.getCall(0).args[1].toString).to.be(ctx.ctrl.onDashboardSaved.toString);
);
expect($rootScope.onAppEvent.getCall(0).args[1].toString).to.be(
ctx.ctrl.onDashboardSaved.toString
);
}); });
}); });
}); });

View File

@ -163,29 +163,8 @@ export function restore(version, restoredFrom?) {
to: 'now', to: 'now',
}, },
timepicker: { timepicker: {
refresh_intervals: [ refresh_intervals: ['5s', '10s', '30s', '1m', '5m', '15m', '30m', '1h', '2h', '1d'],
'5s', time_options: ['5m', '15m', '1h', '6h', '12h', '24h', '2d', '7d', '30d'],
'10s',
'30s',
'1m',
'5m',
'15m',
'30m',
'1h',
'2h',
'1d',
],
time_options: [
'5m',
'15m',
'1h',
'6h',
'12h',
'24h',
'2d',
'7d',
'30d',
],
}, },
timezone: 'utc', timezone: 'utc',
title: 'History Dashboard', title: 'History Dashboard',

View File

@ -1,10 +1,4 @@
import { import { describe, beforeEach, it, expect, angularMocks } from 'test/lib/common';
describe,
beforeEach,
it,
expect,
angularMocks,
} from 'test/lib/common';
import helpers from 'test/specs/helpers'; import helpers from 'test/specs/helpers';
import '../history/history_srv'; import '../history/history_srv';
@ -21,9 +15,7 @@ describe('historySrv', function() {
beforeEach( beforeEach(
angularMocks.inject(function($httpBackend) { angularMocks.inject(function($httpBackend) {
ctx.$httpBackend = $httpBackend; ctx.$httpBackend = $httpBackend;
$httpBackend $httpBackend.whenRoute('GET', 'api/dashboards/id/:id/versions').respond(versionsResponse);
.whenRoute('GET', 'api/dashboards/id/:id/versions')
.respond(versionsResponse);
$httpBackend $httpBackend
.whenRoute('POST', 'api/dashboards/id/:id/restore') .whenRoute('POST', 'api/dashboards/id/:id/restore')
.respond(function(method, url, data, headers, params) { .respond(function(method, url, data, headers, params) {
@ -76,9 +68,7 @@ describe('historySrv', function() {
let version = 6; let version = 6;
return wrapPromise( return wrapPromise(
ctx, ctx,
ctx.service ctx.service.restoreDashboard({ id: 1 }, version).then(function(response) {
.restoreDashboard({ id: 1 }, version)
.then(function(response) {
expect(response).to.eql(restoreResponse(version)); expect(response).to.eql(restoreResponse(version));
}) })
); );

View File

@ -232,16 +232,7 @@ describe('given dashboard with row repeat', function() {
it('should not repeat only row', function() { it('should not repeat only row', function() {
const panel_types = _.map(dashboard.panels, 'type'); const panel_types = _.map(dashboard.panels, 'type');
expect(panel_types).toEqual([ expect(panel_types).toEqual(['row', 'graph', 'graph', 'row', 'graph', 'graph', 'row', 'graph']);
'row',
'graph',
'graph',
'row',
'graph',
'graph',
'row',
'graph',
]);
}); });
it('should set scopedVars for each panel', function() { it('should set scopedVars for each panel', function() {
@ -262,17 +253,7 @@ describe('given dashboard with row repeat', function() {
}) })
); );
expect(scopedVars).toEqual([ expect(scopedVars).toEqual(['se1', 'se1', 'se1', 'se2', 'se2', 'se2', 'se3', 'se3', 'se3']);
'se1',
'se1',
'se1',
'se2',
'se2',
'se2',
'se3',
'se3',
'se3',
]);
}); });
it('should repeat only configured row', function() { it('should repeat only configured row', function() {

View File

@ -57,19 +57,11 @@ describe('saving dashboard as', () => {
expect(ctx.panel.thresholds).toBe(undefined); expect(ctx.panel.thresholds).toBe(undefined);
}); });
scenario( scenario('singlestat should keep threshold', { id: 1, type: 'singlestat', thresholds: { value: 3000 } }, ctx => {
'singlestat should keep threshold',
{ id: 1, type: 'singlestat', thresholds: { value: 3000 } },
ctx => {
expect(ctx.panel.thresholds).not.toBe(undefined); expect(ctx.panel.thresholds).not.toBe(undefined);
} });
);
scenario( scenario('table should keep threshold', { id: 1, type: 'table', thresholds: { value: 3000 } }, ctx => {
'table should keep threshold',
{ id: 1, type: 'table', thresholds: { value: 3000 } },
ctx => {
expect(ctx.panel.thresholds).not.toBe(undefined); expect(ctx.panel.thresholds).not.toBe(undefined);
} });
);
}); });

View File

@ -1,11 +1,4 @@
import { import { describe, beforeEach, it, expect, sinon, angularMocks } from 'test/lib/common';
describe,
beforeEach,
it,
expect,
sinon,
angularMocks,
} from 'test/lib/common';
import helpers from 'test/specs/helpers'; import helpers from 'test/specs/helpers';
import '../shareModalCtrl'; import '../shareModalCtrl';
import config from 'app/core/config'; import config from 'app/core/config';
@ -46,22 +39,17 @@ describe('ShareModalCtrl', function() {
ctx.scope.panel = { id: 22 }; ctx.scope.panel = { id: 22 };
ctx.scope.init(); ctx.scope.init();
expect(ctx.scope.shareUrl).to.be( expect(ctx.scope.shareUrl).to.be('http://server/#!/test?from=1000&to=2000&orgId=1&panelId=22&fullscreen');
'http://server/#!/test?from=1000&to=2000&orgId=1&panelId=22&fullscreen'
);
}); });
it('should generate render url', function() { it('should generate render url', function() {
ctx.$location.$$absUrl = ctx.$location.$$absUrl = 'http://dashboards.grafana.com/dashboard/db/my-dash';
'http://dashboards.grafana.com/dashboard/db/my-dash';
ctx.scope.panel = { id: 22 }; ctx.scope.panel = { id: 22 };
ctx.scope.init(); ctx.scope.init();
var base = var base = 'http://dashboards.grafana.com/render/dashboard-solo/db/my-dash';
'http://dashboards.grafana.com/render/dashboard-solo/db/my-dash'; var params = '?from=1000&to=2000&orgId=1&panelId=22&width=1000&height=500&tz=UTC';
var params =
'?from=1000&to=2000&orgId=1&panelId=22&width=1000&height=500&tz=UTC';
expect(ctx.scope.imageUrl).to.contain(base + params); expect(ctx.scope.imageUrl).to.contain(base + params);
}); });
@ -71,9 +59,7 @@ describe('ShareModalCtrl', function() {
ctx.scope.panel = null; ctx.scope.panel = null;
ctx.scope.init(); ctx.scope.init();
expect(ctx.scope.shareUrl).to.be( expect(ctx.scope.shareUrl).to.be('http://server/#!/test?from=1000&to=2000&orgId=1');
'http://server/#!/test?from=1000&to=2000&orgId=1'
);
}); });
it('should add theme when specified', function() { it('should add theme when specified', function() {
@ -82,9 +68,7 @@ describe('ShareModalCtrl', function() {
ctx.scope.panel = null; ctx.scope.panel = null;
ctx.scope.init(); ctx.scope.init();
expect(ctx.scope.shareUrl).to.be( expect(ctx.scope.shareUrl).to.be('http://server/#!/test?from=1000&to=2000&orgId=1&theme=light');
'http://server/#!/test?from=1000&to=2000&orgId=1&theme=light'
);
}); });
it('should remove fullscreen from image url when is first param in querystring and modeSharePanel is true', function() { it('should remove fullscreen from image url when is first param in querystring and modeSharePanel is true', function() {
@ -94,12 +78,8 @@ describe('ShareModalCtrl', function() {
ctx.scope.buildUrl(); ctx.scope.buildUrl();
expect(ctx.scope.shareUrl).to.contain( expect(ctx.scope.shareUrl).to.contain('?fullscreen&edit&from=1000&to=2000&orgId=1&panelId=1');
'?fullscreen&edit&from=1000&to=2000&orgId=1&panelId=1' expect(ctx.scope.imageUrl).to.contain('?from=1000&to=2000&orgId=1&panelId=1&width=1000&height=500&tz=UTC');
);
expect(ctx.scope.imageUrl).to.contain(
'?from=1000&to=2000&orgId=1&panelId=1&width=1000&height=500&tz=UTC'
);
}); });
it('should remove edit from image url when is first param in querystring and modeSharePanel is true', function() { it('should remove edit from image url when is first param in querystring and modeSharePanel is true', function() {
@ -109,12 +89,8 @@ describe('ShareModalCtrl', function() {
ctx.scope.buildUrl(); ctx.scope.buildUrl();
expect(ctx.scope.shareUrl).to.contain( expect(ctx.scope.shareUrl).to.contain('?edit&fullscreen&from=1000&to=2000&orgId=1&panelId=1');
'?edit&fullscreen&from=1000&to=2000&orgId=1&panelId=1' expect(ctx.scope.imageUrl).to.contain('?from=1000&to=2000&orgId=1&panelId=1&width=1000&height=500&tz=UTC');
);
expect(ctx.scope.imageUrl).to.contain(
'?from=1000&to=2000&orgId=1&panelId=1&width=1000&height=500&tz=UTC'
);
}); });
it('should include template variables in url', function() { it('should include template variables in url', function() {

View File

@ -1,11 +1,4 @@
import { import { describe, beforeEach, it, expect, sinon, angularMocks } from 'test/lib/common';
describe,
beforeEach,
it,
expect,
sinon,
angularMocks,
} from 'test/lib/common';
import helpers from 'test/specs/helpers'; import helpers from 'test/specs/helpers';
import '../time_srv'; import '../time_srv';
@ -55,24 +48,16 @@ describe('timeSrv', function() {
ctx.$location.search({ from: '20140410T052010', to: '20140520T031022' }); ctx.$location.search({ from: '20140410T052010', to: '20140520T031022' });
ctx.service.init(_dashboard); ctx.service.init(_dashboard);
var time = ctx.service.timeRange(true); var time = ctx.service.timeRange(true);
expect(time.from.valueOf()).to.equal( expect(time.from.valueOf()).to.equal(new Date('2014-04-10T05:20:10Z').getTime());
new Date('2014-04-10T05:20:10Z').getTime() expect(time.to.valueOf()).to.equal(new Date('2014-05-20T03:10:22Z').getTime());
);
expect(time.to.valueOf()).to.equal(
new Date('2014-05-20T03:10:22Z').getTime()
);
}); });
it('should handle formated dates without time', function() { it('should handle formated dates without time', function() {
ctx.$location.search({ from: '20140410', to: '20140520' }); ctx.$location.search({ from: '20140410', to: '20140520' });
ctx.service.init(_dashboard); ctx.service.init(_dashboard);
var time = ctx.service.timeRange(true); var time = ctx.service.timeRange(true);
expect(time.from.valueOf()).to.equal( expect(time.from.valueOf()).to.equal(new Date('2014-04-10T00:00:00Z').getTime());
new Date('2014-04-10T00:00:00Z').getTime() expect(time.to.valueOf()).to.equal(new Date('2014-05-20T00:00:00Z').getTime());
);
expect(time.to.valueOf()).to.equal(
new Date('2014-05-20T00:00:00Z').getTime()
);
}); });
it('should handle epochs', function() { it('should handle epochs', function() {

View File

@ -1,11 +1,4 @@
import { import { describe, beforeEach, it, expect, sinon, angularMocks } from 'test/lib/common';
describe,
beforeEach,
it,
expect,
sinon,
angularMocks,
} from 'test/lib/common';
import 'app/features/dashboard/unsavedChangesSrv'; import 'app/features/dashboard/unsavedChangesSrv';
import 'app/features/dashboard/dashboard_srv'; import 'app/features/dashboard/dashboard_srv';
@ -28,12 +21,7 @@ describe('unsavedChangesSrv', function() {
); );
beforeEach( beforeEach(
angularMocks.inject(function( angularMocks.inject(function(unsavedChangesSrv, $location, $rootScope, dashboardSrv) {
unsavedChangesSrv,
$location,
$rootScope,
dashboardSrv
) {
_unsavedChangesSrv = unsavedChangesSrv; _unsavedChangesSrv = unsavedChangesSrv;
_dashboardSrv = dashboardSrv; _dashboardSrv = dashboardSrv;
_rootScope = $rootScope; _rootScope = $rootScope;

Some files were not shown because too many files have changed in this diff Show More