Commit 8fb0692d by Torkel Ödegaard

Merge remote-tracking branch 'origin/migrate-dashboard-files-to-ts'

parents 7e555091 972c3bc6
import './dashboard_ctrl'; import './dashboard_ctrl';
import './alerting_srv'; import './alerting_srv';
import './history/history'; import './history/history';
import './dashboardLoaderSrv'; import './dashboard_loader_srv';
import './dashnav/dashnav'; import './dashnav/dashnav';
import './submenu/submenu'; import './submenu/submenu';
import './save_as_modal'; import './save_as_modal';
import './save_modal'; import './save_modal';
import './shareModalCtrl'; import './shareModalCtrl';
import './shareSnapshotCtrl'; import './share_snapshot_ctrl';
import './dashboard_srv'; import './dashboard_srv';
import './view_state_srv'; import './view_state_srv';
import './validation_srv'; import './validation_srv';
import './time_srv'; import './time_srv';
import './unsavedChangesSrv'; import './unsaved_changes_srv';
import './unsaved_changes_modal'; import './unsaved_changes_modal';
import './timepicker/timepicker'; import './timepicker/timepicker';
import './upload'; import './upload';
......
define([
'angular',
'moment',
'lodash',
'jquery',
'app/core/utils/kbn',
'app/core/utils/datemath',
'app/core/services/impression_srv'
],
function (angular, moment, _, $, kbn, dateMath, impressionSrv) {
'use strict';
kbn = kbn.default;
impressionSrv = impressionSrv.default;
var module = angular.module('grafana.services');
module.service('dashboardLoaderSrv', function(backendSrv,
dashboardSrv,
datasourceSrv,
$http, $q, $timeout,
contextSrv, $routeParams,
$rootScope) {
var self = this;
this._dashboardLoadFailed = function(title, snapshot) {
snapshot = snapshot || false;
return {
meta: { canStar: false, isSnapshot: snapshot, canDelete: false, canSave: false, canEdit: false, dashboardNotFound: true },
dashboard: {title: title }
};
};
this.loadDashboard = function(type, slug) {
var promise;
if (type === 'script') {
promise = this._loadScriptedDashboard(slug);
} else if (type === 'snapshot') {
promise = backendSrv.get('/api/snapshots/' + $routeParams.slug)
.catch(function() {
return self._dashboardLoadFailed("Snapshot not found", true);
});
} else {
promise = backendSrv.getDashboard($routeParams.type, $routeParams.slug)
.then(function(result) {
if (result.meta.isFolder) {
$rootScope.appEvent("alert-error", ['Dashboard not found']);
throw new Error("Dashboard not found");
}
return result;
})
.catch(function() {
return self._dashboardLoadFailed("Not found");
});
}
promise.then(function(result) {
if (result.meta.dashboardNotFound !== true) {
impressionSrv.addDashboardImpression(result.dashboard.id);
}
return result;
});
return promise;
};
this._loadScriptedDashboard = function(file) {
var url = 'public/dashboards/'+file.replace(/\.(?!js)/,"/") + '?' + new Date().getTime();
return $http({ url: url, method: "GET" })
.then(this._executeScript).then(function(result) {
return { meta: { fromScript: true, canDelete: false, canSave: false, canStar: false}, dashboard: result.data };
}, function(err) {
console.log('Script dashboard error '+ err);
$rootScope.appEvent('alert-error', ["Script Error", "Please make sure it exists and returns a valid dashboard"]);
return self._dashboardLoadFailed('Scripted dashboard');
});
};
this._executeScript = function(result) {
var services = {
dashboardSrv: dashboardSrv,
datasourceSrv: datasourceSrv,
$q: $q,
};
/*jshint -W054 */
var script_func = new Function('ARGS','kbn','dateMath','_','moment','window','document','$','jQuery', 'services', result.data);
var script_result = script_func($routeParams, kbn, dateMath, _ , moment, window, document, $, $, services);
// Handle async dashboard scripts
if (_.isFunction(script_result)) {
var deferred = $q.defer();
script_result(function(dashboard) {
$timeout(function() {
deferred.resolve({ data: dashboard });
});
});
return deferred.promise;
}
return { data: script_result };
};
});
});
import angular from 'angular';
import moment from 'moment';
import _ from 'lodash';
import $ from 'jquery';
import kbn from 'app/core/utils/kbn';
import * as dateMath from 'app/core/utils/datemath';
import impressionSrv from 'app/core/services/impression_srv';
export class DashboardLoaderSrv {
/** @ngInject */
constructor(
private backendSrv,
private dashboardSrv,
private datasourceSrv,
private $http,
private $q,
private $timeout,
contextSrv,
private $routeParams,
private $rootScope
) {}
_dashboardLoadFailed(title, snapshot) {
snapshot = snapshot || false;
return {
meta: {
canStar: false,
isSnapshot: snapshot,
canDelete: false,
canSave: false,
canEdit: false,
dashboardNotFound: true,
},
dashboard: { title: title },
};
}
loadDashboard(type, slug) {
var promise;
if (type === 'script') {
promise = this._loadScriptedDashboard(slug);
} else if (type === 'snapshot') {
promise = this.backendSrv.get('/api/snapshots/' + this.$routeParams.slug).catch(() => {
return this._dashboardLoadFailed('Snapshot not found', true);
});
} else {
promise = this.backendSrv
.getDashboard(this.$routeParams.type, this.$routeParams.slug)
.then(result => {
if (result.meta.isFolder) {
this.$rootScope.appEvent('alert-error', ['Dashboard not found']);
throw new Error('Dashboard not found');
}
return result;
})
.catch(() => {
return this._dashboardLoadFailed('Not found', true);
});
}
promise.then(function(result) {
if (result.meta.dashboardNotFound !== true) {
impressionSrv.addDashboardImpression(result.dashboard.id);
}
return result;
});
return promise;
}
_loadScriptedDashboard(file) {
var url = 'public/dashboards/' + file.replace(/\.(?!js)/, '/') + '?' + new Date().getTime();
return this.$http({ url: url, method: 'GET' })
.then(this._executeScript)
.then(
function(result) {
return {
meta: {
fromScript: true,
canDelete: false,
canSave: false,
canStar: false,
},
dashboard: result.data,
};
},
function(err) {
console.log('Script dashboard error ' + err);
this.$rootScope.appEvent('alert-error', [
'Script Error',
'Please make sure it exists and returns a valid dashboard',
]);
return this._dashboardLoadFailed('Scripted dashboard');
}
);
}
_executeScript(result) {
var services = {
dashboardSrv: this.dashboardSrv,
datasourceSrv: this.datasourceSrv,
$q: this.$q,
};
/*jshint -W054 */
var script_func = new Function(
'ARGS',
'kbn',
'dateMath',
'_',
'moment',
'window',
'document',
'$',
'jQuery',
'services',
result.data
);
var script_result = script_func(this.$routeParams, kbn, dateMath, _, moment, window, document, $, $, services);
// Handle async dashboard scripts
if (_.isFunction(script_result)) {
var deferred = this.$q.defer();
script_result(dashboard => {
this.$timeout(() => {
deferred.resolve({ data: dashboard });
});
});
return deferred.promise;
}
return { data: script_result };
}
}
angular.module('grafana.services').service('dashboardLoaderSrv', DashboardLoaderSrv);
define([ import angular from 'angular';
'angular', import _ from 'lodash';
'lodash',
],
function (angular, _) {
'use strict';
var module = angular.module('grafana.controllers');
module.controller('ShareSnapshotCtrl', function($scope, $rootScope, $location, backendSrv, $timeout, timeSrv) {
export class ShareSnapshotCtrl {
constructor($scope, $rootScope, $location, backendSrv, $timeout, timeSrv) {
$scope.snapshot = { $scope.snapshot = {
name: $scope.dashboard.title, name: $scope.dashboard.title,
expires: 0, expires: 0,
...@@ -18,16 +12,16 @@ function (angular, _) { ...@@ -18,16 +12,16 @@ function (angular, _) {
$scope.step = 1; $scope.step = 1;
$scope.expireOptions = [ $scope.expireOptions = [
{text: '1 Hour', value: 60*60}, { text: '1 Hour', value: 60 * 60 },
{text: '1 Day', value: 60*60*24}, { text: '1 Day', value: 60 * 60 * 24 },
{text: '7 Days', value: 60*60*24*7}, { text: '7 Days', value: 60 * 60 * 24 * 7 },
{text: 'Never', value: 0}, { text: 'Never', value: 0 },
]; ];
$scope.accessOptions = [ $scope.accessOptions = [
{text: 'Anyone with the link', value: 1}, { text: 'Anyone with the link', value: 1 },
{text: 'Organization users', value: 2}, { text: 'Organization users', value: 2 },
{text: 'Public on the web', value: 3}, { text: 'Public on the web', value: 3 },
]; ];
$scope.init = function() { $scope.init = function() {
...@@ -42,7 +36,7 @@ function (angular, _) { ...@@ -42,7 +36,7 @@ function (angular, _) {
$scope.createSnapshot = function(external) { $scope.createSnapshot = function(external) {
$scope.dashboard.snapshot = { $scope.dashboard.snapshot = {
timestamp: new Date() timestamp: new Date(),
}; };
if (!external) { if (!external) {
...@@ -71,7 +65,8 @@ function (angular, _) { ...@@ -71,7 +65,8 @@ function (angular, _) {
var postUrl = external ? $scope.externalUrl + $scope.apiUrl : $scope.apiUrl; var postUrl = external ? $scope.externalUrl + $scope.apiUrl : $scope.apiUrl;
backendSrv.post(postUrl, cmdData).then(function(results) { backendSrv.post(postUrl, cmdData).then(
function(results) {
$scope.loading = false; $scope.loading = false;
if (external) { if (external) {
...@@ -91,9 +86,11 @@ function (angular, _) { ...@@ -91,9 +86,11 @@ function (angular, _) {
} }
$scope.step = 2; $scope.step = 2;
}, function() { },
function() {
$scope.loading = false; $scope.loading = false;
}); }
);
}; };
$scope.getSnapshotUrl = function() { $scope.getSnapshotUrl = function() {
...@@ -124,13 +121,14 @@ function (angular, _) { ...@@ -124,13 +121,14 @@ function (angular, _) {
name: annotation.name, name: annotation.name,
enable: annotation.enable, enable: annotation.enable,
iconColor: annotation.iconColor, iconColor: annotation.iconColor,
snapshotData: annotation.snapshotData snapshotData: annotation.snapshotData,
}; };
}).value(); })
.value();
// remove template queries // remove template queries
_.each(dash.templating.list, function(variable) { _.each(dash.templating.list, function(variable) {
variable.query = ""; variable.query = '';
variable.options = variable.current; variable.options = variable.current;
variable.refresh = false; variable.refresh = false;
}); });
...@@ -168,7 +166,7 @@ function (angular, _) { ...@@ -168,7 +166,7 @@ function (angular, _) {
cmdData.deleteKey = results.deleteKey; cmdData.deleteKey = results.deleteKey;
backendSrv.post('/api/snapshots/', cmdData); backendSrv.post('/api/snapshots/', cmdData);
}; };
}
}
}); angular.module('grafana.controllers').controller('ShareSnapshotCtrl', ShareSnapshotCtrl);
});
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 { Tracker } from 'app/features/dashboard/unsaved_changes_srv';
import 'app/features/dashboard/dashboard_srv'; import 'app/features/dashboard/dashboard_srv';
import { contextSrv } from 'app/core/core';
describe('unsavedChangesSrv', function() { describe('unsavedChangesSrv', function() {
var _unsavedChangesSrv;
var _dashboardSrv; var _dashboardSrv;
var _contextSrvStub = { isEditor: true }; var _contextSrvStub = { isEditor: true };
var _rootScope; var _rootScope;
var _location;
var _timeout;
var _window;
var tracker; var tracker;
var dash; var dash;
var scope; var scope;
...@@ -21,10 +24,12 @@ describe('unsavedChangesSrv', function() { ...@@ -21,10 +24,12 @@ describe('unsavedChangesSrv', function() {
); );
beforeEach( beforeEach(
angularMocks.inject(function(unsavedChangesSrv, $location, $rootScope, dashboardSrv) { angularMocks.inject(function($location, $rootScope, dashboardSrv, $timeout, $window) {
_unsavedChangesSrv = unsavedChangesSrv;
_dashboardSrv = dashboardSrv; _dashboardSrv = dashboardSrv;
_rootScope = $rootScope; _rootScope = $rootScope;
_location = $location;
_timeout = $timeout;
_window = $window;
}) })
); );
...@@ -42,7 +47,7 @@ describe('unsavedChangesSrv', function() { ...@@ -42,7 +47,7 @@ describe('unsavedChangesSrv', function() {
scope.appEvent = sinon.spy(); scope.appEvent = sinon.spy();
scope.onAppEvent = sinon.spy(); scope.onAppEvent = sinon.spy();
tracker = new _unsavedChangesSrv.Tracker(dash, scope); tracker = new Tracker(dash, scope, undefined, _location, _window, _timeout, contextSrv, _rootScope);
}); });
it('No changes should not have changes', function() { it('No changes should not have changes', function() {
......
define([ import angular from 'angular';
'angular', import _ from 'lodash';
'lodash',
], export class Tracker {
function(angular, _) { current: any;
'use strict'; originalPath: any;
scope: any;
var module = angular.module('grafana.services'); original: any;
next: any;
module.service('unsavedChangesSrv', function($rootScope, $q, $location, $timeout, contextSrv, dashboardSrv, $window) { $window: any;
function Tracker(dashboard, scope, originalCopyDelay) { /** @ngInject */
var self = this; constructor(
dashboard,
scope,
originalCopyDelay,
private $location,
$window,
private $timeout,
private contextSrv,
private $rootScope
) {
this.$location = $location;
this.$window = $window;
this.current = dashboard; this.current = dashboard;
this.originalPath = $location.path(); this.originalPath = $location.path();
this.scope = scope; this.scope = scope;
// register events // register events
scope.onAppEvent('dashboard-saved', function() { scope.onAppEvent('dashboard-saved', () => {
this.original = this.current.getSaveModelClone(); this.original = this.current.getSaveModelClone();
this.originalPath = $location.path(); this.originalPath = $location.path();
}.bind(this)); });
$window.onbeforeunload = function() { $window.onbeforeunload = () => {
if (self.ignoreChanges()) { return; } if (this.ignoreChanges()) {
if (self.hasChanges()) { return '';
return "There are unsaved changes to this dashboard";
} }
if (this.hasChanges()) {
return 'There are unsaved changes to this dashboard';
}
return '';
}; };
scope.$on("$locationChangeStart", function(event, next) { scope.$on('$locationChangeStart', (event, next) => {
// check if we should look for changes // check if we should look for changes
if (self.originalPath === $location.path()) { return true; } if (this.originalPath === $location.path()) {
if (self.ignoreChanges()) { return true; } return true;
}
if (this.ignoreChanges()) {
return true;
}
if (self.hasChanges()) { if (this.hasChanges()) {
event.preventDefault(); event.preventDefault();
self.next = next; this.next = next;
$timeout(function() { this.$timeout(() => {
self.open_modal(); this.open_modal();
}); });
} }
return false;
}); });
if (originalCopyDelay) { if (originalCopyDelay) {
$timeout(function() { this.$timeout(() => {
// wait for different services to patch the dashboard (missing properties) // wait for different services to patch the dashboard (missing properties)
self.original = dashboard.getSaveModelClone(); this.original = dashboard.getSaveModelClone();
}, originalCopyDelay); }, originalCopyDelay);
} else { } else {
self.original = dashboard.getSaveModelClone(); this.original = dashboard.getSaveModelClone();
} }
} }
var p = Tracker.prototype;
// for some dashboards and users // for some dashboards and users
// changes should be ignored // changes should be ignored
p.ignoreChanges = function() { ignoreChanges() {
if (!this.original) { return true; } if (!this.original) {
if (!contextSrv.isEditor) { return true; } return true;
if (!this.current || !this.current.meta) { return true; } }
if (!this.contextSrv.isEditor) {
return true;
}
if (!this.current || !this.current.meta) {
return true;
}
var meta = this.current.meta; var meta = this.current.meta;
return !meta.canSave || meta.fromScript || meta.fromFile; return !meta.canSave || meta.fromScript || meta.fromFile;
}; }
// remove stuff that should not count in diff // remove stuff that should not count in diff
p.cleanDashboardFromIgnoredChanges = function(dash) { cleanDashboardFromIgnoredChanges(dash) {
// ignore time and refresh // ignore time and refresh
dash.time = 0; dash.time = 0;
dash.refresh = 0; dash.refresh = 0;
...@@ -105,7 +128,7 @@ function(angular, _) { ...@@ -105,7 +128,7 @@ function(angular, _) {
return true; return true;
}); });
dash.panels = _.filter(dash.panels, function(panel) { dash.panels = _.filter(dash.panels, panel => {
if (panel.repeatPanelId) { if (panel.repeatPanelId) {
return false; return false;
} }
...@@ -128,9 +151,9 @@ function(angular, _) { ...@@ -128,9 +151,9 @@ function(angular, _) {
value.options = null; value.options = null;
value.filters = null; value.filters = null;
}); });
}; }
p.hasChanges = function() { hasChanges() {
var current = this.current.getSaveModelClone(); var current = this.current.getSaveModelClone();
var original = this.original; var original = this.original;
...@@ -148,42 +171,46 @@ function(angular, _) { ...@@ -148,42 +171,46 @@ function(angular, _) {
var originalJson = angular.toJson(original); var originalJson = angular.toJson(original);
return currentJson !== originalJson; return currentJson !== originalJson;
}; }
p.discardChanges = function() { discardChanges() {
this.original = null; this.original = null;
this.gotoNext(); this.gotoNext();
}; }
p.open_modal = function() { open_modal() {
$rootScope.appEvent('show-modal', { this.$rootScope.appEvent('show-modal', {
templateHtml: '<unsaved-changes-modal dismiss="dismiss()"></unsaved-changes-modal>', templateHtml: '<unsaved-changes-modal dismiss="dismiss()"></unsaved-changes-modal>',
modalClass: 'modal--narrow confirm-modal' modalClass: 'modal--narrow confirm-modal',
}); });
}; }
p.saveChanges = function() { saveChanges() {
var self = this; var self = this;
var cancel = $rootScope.$on('dashboard-saved', function() { var cancel = this.$rootScope.$on('dashboard-saved', () => {
cancel(); cancel();
$timeout(function() { this.$timeout(() => {
self.gotoNext(); self.gotoNext();
}); });
}); });
$rootScope.appEvent('save-dashboard'); this.$rootScope.appEvent('save-dashboard');
}; }
p.gotoNext = function() { gotoNext() {
var baseLen = $location.absUrl().length - $location.url().length; var baseLen = this.$location.absUrl().length - this.$location.url().length;
var nextUrl = this.next.substring(baseLen); var nextUrl = this.next.substring(baseLen);
$location.url(nextUrl); this.$location.url(nextUrl);
}; }
}
/** @ngInject */
export function unsavedChangesSrv($rootScope, $q, $location, $timeout, contextSrv, dashboardSrv, $window) {
this.Tracker = Tracker; this.Tracker = Tracker;
this.init = function(dashboard, scope) { this.init = function(dashboard, scope) {
this.tracker = new Tracker(dashboard, scope, 1000); this.tracker = new Tracker(dashboard, scope, 1000, $location, $window, $timeout, contextSrv, $rootScope);
return this.tracker; return this.tracker;
}; };
}); }
});
angular.module('grafana.services').service('unsavedChangesSrv', unsavedChangesSrv);
Markdown is supported
0% or
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!
Please register or to comment