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
trim_trailing_whitespace = true
insert_final_newline = true
max_line_length = 120
insert_final_newline = true
[*.go]
indent_style = tab

View File

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

View File

@ -54,49 +54,40 @@ export class GrafanaApp {
moment.locale(config.bootData.user.locale);
app.config(
(
$locationProvider,
$controllerProvider,
$compileProvider,
$filterProvider,
$httpProvider,
$provide
) => {
// pre assing bindings before constructor calls
$compileProvider.preAssignBindingsEnabled(true);
app.config(($locationProvider, $controllerProvider, $compileProvider, $filterProvider, $httpProvider, $provide) => {
// pre assing bindings before constructor calls
$compileProvider.preAssignBindingsEnabled(true);
if (config.buildInfo.env !== 'development') {
$compileProvider.debugInfoEnabled(false);
}
$httpProvider.useApplyAsync(true);
this.registerFunctions.controller = $controllerProvider.register;
this.registerFunctions.directive = $compileProvider.directive;
this.registerFunctions.factory = $provide.factory;
this.registerFunctions.service = $provide.service;
this.registerFunctions.filter = $filterProvider.register;
$provide.decorator('$http', [
'$delegate',
'$templateCache',
function($delegate, $templateCache) {
var get = $delegate.get;
$delegate.get = function(url, config) {
if (url.match(/\.html$/)) {
// some template's already exist in the cache
if (!$templateCache.get(url)) {
url += '?v=' + new Date().getTime();
}
}
return get(url, config);
};
return $delegate;
},
]);
if (config.buildInfo.env !== 'development') {
$compileProvider.debugInfoEnabled(false);
}
);
$httpProvider.useApplyAsync(true);
this.registerFunctions.controller = $controllerProvider.register;
this.registerFunctions.directive = $compileProvider.directive;
this.registerFunctions.factory = $provide.factory;
this.registerFunctions.service = $provide.service;
this.registerFunctions.filter = $filterProvider.register;
$provide.decorator('$http', [
'$delegate',
'$templateCache',
function($delegate, $templateCache) {
var get = $delegate.get;
$delegate.get = function(url, config) {
if (url.match(/\.html$/)) {
// some template's already exist in the cache
if (!$templateCache.get(url)) {
url += '?v=' + new Date().getTime();
}
}
return get(url, config);
};
return $delegate;
},
]);
});
this.ngModuleDependencies = [
'grafana.core',
@ -111,14 +102,7 @@ export class GrafanaApp {
'react',
];
var module_types = [
'controllers',
'directives',
'factories',
'services',
'filters',
'routes',
];
var module_types = ['controllers', 'directives', 'factories', 'services', 'filters', 'routes'];
_.each(module_types, type => {
var moduleName = 'grafana.' + type;

View File

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

View File

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

View File

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

View File

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

View File

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

View File

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

View File

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

View File

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

View File

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

View File

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

View File

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

View File

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

View File

@ -26,13 +26,11 @@ export class UserPickerCtrl {
searchUsers(query: string) {
return Promise.resolve(
this.backendSrv
.get('/api/users/search?perpage=10&page=1&query=' + query)
.then(result => {
return _.map(result.users, user => {
return { text: user.login + ' - ' + user.email, value: user };
});
})
this.backendSrv.get('/api/users/search?perpage=10&page=1&query=' + query).then(result => {
return _.map(result.users, 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) {
$scope.request_parameters = _.map(model.error.config.params, function(
value,
key
) {
$scope.request_parameters = _.map(model.error.config.params, function(value, key) {
return { key: key, value: value };
});
}
@ -46,14 +43,9 @@ export class InspectCtrl {
$scope.editor.index = 2;
if (_.isString(model.error.config.data)) {
$scope.request_parameters = this.getParametersFromQueryString(
model.error.config.data
);
$scope.request_parameters = this.getParametersFromQueryString(model.error.config.data);
} else {
$scope.request_parameters = _.map(model.error.config.data, function(
value,
key
) {
$scope.request_parameters = _.map(model.error.config.data, function(value, key) {
return { key: key, value: angular.toJson(value, true) };
});
}

View File

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

View File

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

View File

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

View File

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

View File

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

View File

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

View File

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

View File

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

View File

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

View File

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

View File

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

View File

@ -38,15 +38,9 @@ export class AlertSrv {
this.$rootScope
);
appEvents.on('alert-warning', options =>
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-warning', options => 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('confirm-modal', this.showConfirmModal.bind(this));
}
@ -114,8 +108,7 @@ export class AlertSrv {
};
scope.updateConfirmText = function(value) {
scope.confirmTextValid =
payload.confirmText.toLowerCase() === value.toLowerCase();
scope.confirmTextValid = payload.confirmText.toLowerCase() === value.toLowerCase();
};
scope.title = payload.title;

View File

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

View File

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

View File

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

View File

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

View File

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

View File

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

View File

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

View File

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

View File

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

View File

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

View File

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

View File

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

View File

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

View File

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

View File

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

View File

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

View File

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

View File

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

View File

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

View File

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

View File

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

View File

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

View File

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

View File

@ -30,21 +30,17 @@ export class AdminEditUserCtrl {
}
var payload = { password: $scope.password };
backendSrv
.put('/api/admin/users/' + $scope.user_id + '/password', payload)
.then(function() {
$location.path('/admin/users');
});
backendSrv.put('/api/admin/users/' + $scope.user_id + '/password', payload).then(function() {
$location.path('/admin/users');
});
};
$scope.updatePermissions = function() {
var payload = $scope.permissions;
backendSrv
.put('/api/admin/users/' + $scope.user_id + '/permissions', payload)
.then(function() {
$location.path('/admin/users');
});
backendSrv.put('/api/admin/users/' + $scope.user_id + '/permissions', payload).then(function() {
$location.path('/admin/users');
});
};
$scope.create = function() {
@ -68,28 +64,19 @@ export class AdminEditUserCtrl {
return;
}
backendSrv
.put('/api/users/' + $scope.user_id, $scope.user)
.then(function() {
$location.path('/admin/users');
});
backendSrv.put('/api/users/' + $scope.user_id, $scope.user).then(function() {
$location.path('/admin/users');
});
};
$scope.updateOrgUser = function(orgUser) {
backendSrv
.patch(
'/api/orgs/' + orgUser.orgId + '/users/' + $scope.user_id,
orgUser
)
.then(function() {});
backendSrv.patch('/api/orgs/' + orgUser.orgId + '/users/' + $scope.user_id, orgUser).then(function() {});
};
$scope.removeOrgUser = function(orgUser) {
backendSrv
.delete('/api/orgs/' + orgUser.orgId + '/users/' + $scope.user_id)
.then(function() {
$scope.getUserOrgs($scope.user_id);
});
backendSrv.delete('/api/orgs/' + orgUser.orgId + '/users/' + $scope.user_id).then(function() {
$scope.getUserOrgs($scope.user_id);
});
};
$scope.orgsSearchCache = [];
@ -120,17 +107,13 @@ export class AdminEditUserCtrl {
$scope.newOrg.loginOrEmail = $scope.user.login;
backendSrv
.post('/api/orgs/' + orgInfo.id + '/users/', $scope.newOrg)
.then(function() {
$scope.getUserOrgs($scope.user_id);
});
backendSrv.post('/api/orgs/' + orgInfo.id + '/users/', $scope.newOrg).then(function() {
$scope.getUserOrgs($scope.user_id);
});
};
$scope.init();
}
}
angular
.module('grafana.controllers')
.controller('AdminEditUserCtrl', AdminEditUserCtrl);
angular.module('grafana.controllers').controller('AdminEditUserCtrl', AdminEditUserCtrl);

View File

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

View File

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

View File

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

View File

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

View File

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

View File

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

View File

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

View File

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

View File

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

View File

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

View File

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

View File

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

View File

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

View File

@ -1,11 +1,4 @@
import {
describe,
beforeEach,
it,
expect,
sinon,
angularMocks,
} from 'test/lib/common';
import { describe, beforeEach, it, expect, sinon, angularMocks } from 'test/lib/common';
import { AclCtrl } from '../acl';
describe('AclCtrl', () => {
@ -81,9 +74,7 @@ describe('AclCtrl', () => {
done();
});
expect(backendSrv.post.getCall(0).args[0]).to.eql(
'/api/dashboards/id/1/acl'
);
expect(backendSrv.post.getCall(0).args[0]).to.eql('/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].permission).to.eql(1);
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 --',
});
this.buildSegmentModel();
this.$rootScope.onAppEvent(
'template-variable-value-updated',
this.buildSegmentModel.bind(this),
$scope
);
this.$rootScope.onAppEvent('template-variable-value-updated', this.buildSegmentModel.bind(this), $scope);
}
buildSegmentModel() {
@ -53,9 +49,7 @@ export class AdHocFiltersCtrl {
getOptions(segment, index) {
if (segment.type === 'operator') {
return this.$q.when(
this.uiSegmentSrv.newOperators(['=', '!=', '<', '>', '=~', '!~'])
);
return this.$q.when(this.uiSegmentSrv.newOperators(['=', '!=', '<', '>', '=~', '!~']));
}
if (segment.type === 'condition') {
@ -107,13 +101,7 @@ export class AdHocFiltersCtrl {
this.segments.splice(index, 0, this.uiSegmentSrv.newCondition('AND'));
}
this.segments.push(this.uiSegmentSrv.newOperator('='));
this.segments.push(
this.uiSegmentSrv.newFake(
'select tag value',
'value',
'query-segment-value'
)
);
this.segments.push(this.uiSegmentSrv.newFake('select tag value', 'value', 'query-segment-value'));
segment.type = 'key';
segment.cssClass = 'query-segment-key';
}

View File

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

View File

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

View File

@ -18,14 +18,7 @@ export class DashboardImportCtrl {
nameValidationError: any;
/** @ngInject */
constructor(
private backendSrv,
private validationSrv,
navModelSrv,
private $location,
private $scope,
$routeParams
) {
constructor(private backendSrv, private validationSrv, navModelSrv, private $location, private $scope, $routeParams) {
this.navModel = navModelSrv.getNav('create', 'import');
this.step = 1;
@ -76,8 +69,7 @@ export class DashboardImportCtrl {
});
if (sources.length === 0) {
inputModel.info =
'No data sources of type ' + input.pluginName + ' found';
inputModel.info = 'No data sources of type ' + input.pluginName + ' found';
} else if (!inputModel.info) {
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
const showRows = _.some(
old.rows,
row => row.collapse || row.showTitle || row.repeat
);
const showRows = _.some(old.rows, row => row.collapse || row.showTitle || row.repeat);
for (let row of old.rows) {
if (row.repeatIteration) {
@ -433,9 +430,7 @@ export class DashboardMigrator {
for (let panel of row.panels) {
panel.span = panel.span || DEFAULT_PANEL_SPAN;
const panelWidth = Math.floor(panel.span) * widthFactor;
const panelHeight = panel.height
? getGridHeight(panel.height)
: rowGridHeight;
const panelHeight = panel.height ? getGridHeight(panel.height) : rowGridHeight;
let panelPos = rowArea.getPanelPosition(panelHeight, panelWidth);
yPos = rowArea.yPos;
@ -539,11 +534,7 @@ class RowArea {
}
}
if (
startPlace !== undefined &&
endPlace !== undefined &&
endPlace - startPlace >= panelWidth - 1
) {
if (startPlace !== undefined && endPlace !== undefined && endPlace - startPlace >= panelWidth - 1) {
const yPos = _.max(this.area.slice(startPlace));
place = {
x: startPlace,

View File

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

View File

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

View File

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

View File

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

View File

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

View File

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

View File

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

View File

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

View File

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

View File

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

View File

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

View File

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

View File

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

View File

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

View File

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

View File

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

View File

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

View File

@ -54,10 +54,7 @@ describe('DashboardModel', function() {
{
type: 'table',
legend: true,
styles: [
{ thresholds: ['10', '20', '30'] },
{ thresholds: ['100', '200', '300'] },
],
styles: [{ thresholds: ['10', '20', '30'] }, { thresholds: ['100', '200', '300'] }],
targets: [{ refId: 'A' }, {}],
},
],
@ -156,19 +153,13 @@ describe('DashboardModel', function() {
model.rows = [createRow({ collapse: false, height: 8 }, [[6], [6]])];
let dashboard = new DashboardModel(model);
let panelGridPos = getGridPositions(dashboard);
let expectedGrid = [
{ x: 0, y: 0, w: 12, h: 8 },
{ x: 12, y: 0, w: 12, h: 8 },
];
let expectedGrid = [{ x: 0, y: 0, w: 12, h: 8 }, { x: 12, y: 0, w: 12, h: 8 }];
expect(panelGridPos).toEqual(expectedGrid);
});
it('should add special "row" panel if row is collapsed', function() {
model.rows = [
createRow({ collapse: true, height: 8 }, [[6], [6]]),
createRow({ height: 8 }, [[12]]),
];
model.rows = [createRow({ collapse: true, height: 8 }, [[6], [6]]), createRow({ height: 8 }, [[12]])];
let dashboard = new DashboardModel(model);
let panelGridPos = getGridPositions(dashboard);
let expectedGrid = [
@ -222,10 +213,7 @@ describe('DashboardModel', function() {
});
it('should add all rows if even one collapsed or titled row is present', function() {
model.rows = [
createRow({ collapse: true, height: 8 }, [[6], [6]]),
createRow({ height: 8 }, [[12]]),
];
model.rows = [createRow({ collapse: true, height: 8 }, [[6], [6]]), createRow({ height: 8 }, [[12]])];
let dashboard = new DashboardModel(model);
let panelGridPos = getGridPositions(dashboard);
let expectedGrid = [
@ -258,9 +246,7 @@ describe('DashboardModel', function() {
});
it('should place panel to the right side of panel having bigger height', function() {
model.rows = [
createRow({ height: 6 }, [[4], [2, 3], [4, 6], [2, 3], [2, 3]]),
];
model.rows = [createRow({ height: 6 }, [[4], [2, 3], [4, 6], [2, 3], [2, 3]])];
let dashboard = new DashboardModel(model);
let panelGridPos = getGridPositions(dashboard);
let expectedGrid = [
@ -275,9 +261,7 @@ describe('DashboardModel', function() {
});
it('should fill current row if it possible', function() {
model.rows = [
createRow({ height: 9 }, [[4], [2, 3], [4, 6], [2, 3], [2, 3], [8, 3]]),
];
model.rows = [createRow({ height: 9 }, [[4], [2, 3], [4, 6], [2, 3], [2, 3], [8, 3]])];
let dashboard = new DashboardModel(model);
let panelGridPos = getGridPositions(dashboard);
let expectedGrid = [
@ -293,9 +277,7 @@ describe('DashboardModel', function() {
});
it('should fill current row if it possible (2)', function() {
model.rows = [
createRow({ height: 8 }, [[4], [2, 3], [4, 6], [2, 3], [2, 3], [8, 3]]),
];
model.rows = [createRow({ height: 8 }, [[4], [2, 3], [4, 6], [2, 3], [2, 3], [8, 3]])];
let dashboard = new DashboardModel(model);
let panelGridPos = getGridPositions(dashboard);
let expectedGrid = [
@ -311,9 +293,7 @@ describe('DashboardModel', function() {
});
it('should fill current row if panel height more than row height', function() {
model.rows = [
createRow({ height: 6 }, [[4], [2, 3], [4, 8], [2, 3], [2, 3]]),
];
model.rows = [createRow({ height: 6 }, [[4], [2, 3], [4, 8], [2, 3], [2, 3]])];
let dashboard = new DashboardModel(model);
let panelGridPos = getGridPositions(dashboard);
let expectedGrid = [
@ -345,10 +325,7 @@ describe('DashboardModel', function() {
it('should add repeated row if repeat set', function() {
model.rows = [
createRow(
{ showTitle: true, title: 'Row', height: 8, repeat: 'server' },
[[6]]
),
createRow({ showTitle: true, title: 'Row', height: 8, repeat: 'server' }, [[6]]),
createRow({ height: 8 }, [[12]]),
];
let dashboard = new DashboardModel(model);
@ -369,10 +346,7 @@ describe('DashboardModel', function() {
it('should ignore repeated row', function() {
model.rows = [
createRow(
{ showTitle: true, title: 'Row1', height: 8, repeat: 'server' },
[[6]]
),
createRow({ showTitle: true, title: 'Row1', height: 8, repeat: 'server' }, [[6]]),
createRow(
{
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() {
expect(dashboard.formatDate(1234567890007, 'YYYY-MM-DD HH:mm:ss')).toBe(
'2009-02-13 23:31:30'
);
expect(dashboard.formatDate(1234567890007, 'YYYY-MM-DD HH:mm:ss')).toBe('2009-02-13 23:31:30');
});
it('Should format timestamp with millisecond resolution if format is passed as parameter', function() {
expect(
dashboard.formatDate(1234567890007, 'YYYY-MM-DD HH:mm:ss.SSS')
).toBe('2009-02-13 23:31:30.007');
expect(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 {
describe,
beforeEach,
it,
sinon,
expect,
angularMocks,
} from 'test/lib/common';
import { describe, beforeEach, it, sinon, expect, angularMocks } from 'test/lib/common';
import _ from 'lodash';
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() {
var actual = _.filter(ctx.ctrl.revisions, rev =>
rev.hasOwnProperty('checked')
);
var actual = _.filter(ctx.ctrl.revisions, rev => rev.hasOwnProperty('checked'));
expect(actual.length).to.be(4);
});
@ -139,18 +130,12 @@ describe('HistoryListCtrl', function() {
it('should listen for the `dashboard-saved` appEvent', function() {
expect($rootScope.onAppEvent.calledOnce).to.be(true);
expect($rootScope.onAppEvent.getCall(0).args[0]).to.be(
'dashboard-saved'
);
expect($rootScope.onAppEvent.getCall(0).args[0]).to.be('dashboard-saved');
});
it('should call `onDashboardSaved` when the appEvent is received', function() {
expect($rootScope.onAppEvent.getCall(0).args[1]).to.not.be(
ctx.ctrl.onDashboardSaved
);
expect($rootScope.onAppEvent.getCall(0).args[1].toString).to.be(
ctx.ctrl.onDashboardSaved.toString
);
expect($rootScope.onAppEvent.getCall(0).args[1]).to.not.be(ctx.ctrl.onDashboardSaved);
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',
},
timepicker: {
refresh_intervals: [
'5s',
'10s',
'30s',
'1m',
'5m',
'15m',
'30m',
'1h',
'2h',
'1d',
],
time_options: [
'5m',
'15m',
'1h',
'6h',
'12h',
'24h',
'2d',
'7d',
'30d',
],
refresh_intervals: ['5s', '10s', '30s', '1m', '5m', '15m', '30m', '1h', '2h', '1d'],
time_options: ['5m', '15m', '1h', '6h', '12h', '24h', '2d', '7d', '30d'],
},
timezone: 'utc',
title: 'History Dashboard',

View File

@ -1,10 +1,4 @@
import {
describe,
beforeEach,
it,
expect,
angularMocks,
} from 'test/lib/common';
import { describe, beforeEach, it, expect, angularMocks } from 'test/lib/common';
import helpers from 'test/specs/helpers';
import '../history/history_srv';
@ -21,9 +15,7 @@ describe('historySrv', function() {
beforeEach(
angularMocks.inject(function($httpBackend) {
ctx.$httpBackend = $httpBackend;
$httpBackend
.whenRoute('GET', 'api/dashboards/id/:id/versions')
.respond(versionsResponse);
$httpBackend.whenRoute('GET', 'api/dashboards/id/:id/versions').respond(versionsResponse);
$httpBackend
.whenRoute('POST', 'api/dashboards/id/:id/restore')
.respond(function(method, url, data, headers, params) {
@ -76,11 +68,9 @@ describe('historySrv', function() {
let version = 6;
return wrapPromise(
ctx,
ctx.service
.restoreDashboard({ id: 1 }, version)
.then(function(response) {
expect(response).to.eql(restoreResponse(version));
})
ctx.service.restoreDashboard({ id: 1 }, version).then(function(response) {
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() {
const panel_types = _.map(dashboard.panels, 'type');
expect(panel_types).toEqual([
'row',
'graph',
'graph',
'row',
'graph',
'graph',
'row',
'graph',
]);
expect(panel_types).toEqual(['row', 'graph', 'graph', 'row', 'graph', 'graph', 'row', 'graph']);
});
it('should set scopedVars for each panel', function() {
@ -262,17 +253,7 @@ describe('given dashboard with row repeat', function() {
})
);
expect(scopedVars).toEqual([
'se1',
'se1',
'se1',
'se2',
'se2',
'se2',
'se3',
'se3',
'se3',
]);
expect(scopedVars).toEqual(['se1', 'se1', 'se1', 'se2', 'se2', 'se2', 'se3', 'se3', 'se3']);
});
it('should repeat only configured row', function() {

View File

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

View File

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

View File

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

View File

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

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