forked from getredash/redash
/
dashboard.js
414 lines (369 loc) · 11.5 KB
/
dashboard.js
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
import * as _ from 'underscore';
import PromiseRejectionError from '@/lib/promise-rejection-error';
import { durationHumanize } from '@/filters';
import template from './dashboard.html';
import shareDashboardTemplate from './share-dashboard.html';
import './dashboard.less';
function isWidgetPositionChanged(oldPosition, newPosition) {
const fields = ['col', 'row', 'sizeX', 'sizeY', 'autoHeight'];
oldPosition = _.pick(oldPosition, fields);
newPosition = _.pick(newPosition, fields);
return !!_.find(fields, key => newPosition[key] !== oldPosition[key]);
}
function getWidgetsWithChangedPositions(widgets) {
return _.filter(widgets, (widget) => {
if (!_.isObject(widget.$originalPosition)) {
return true;
}
return isWidgetPositionChanged(widget.$originalPosition, widget.options.position);
});
}
function DashboardCtrl(
$rootScope,
$routeParams,
$location,
$timeout,
$q,
$uibModal,
Title,
AlertDialog,
Dashboard,
currentUser,
clientConfig,
Events,
toastr,
) {
this.saveInProgress = false;
const saveDashboardLayout = (widgets) => {
if (!this.dashboard.canEdit()) {
return;
}
this.saveInProgress = true;
const showMessages = true;
return $q
.all(_.map(widgets, widget => widget.$save()))
.then(() => {
if (showMessages) {
toastr.success('Changes saved.');
}
// Update original widgets positions
_.each(widgets, (widget) => {
_.extend(widget.$originalPosition, widget.options.position);
});
})
.catch(() => {
if (showMessages) {
toastr.error('Error saving changes.');
}
})
.finally(() => {
this.saveInProgress = false;
});
};
this.layoutEditing = false;
this.isFullscreen = false;
this.refreshRate = null;
this.isGridDisabled = false;
this.updateGridItems = null;
this.showPermissionsControl = clientConfig.showPermissionsControl;
this.globalParameters = [];
this.refreshRates = clientConfig.dashboardRefreshIntervals.map(interval => ({
name: durationHumanize(interval),
rate: interval,
}));
this.setRefreshRate = (rate, load = true) => {
this.refreshRate = rate;
if (rate !== null) {
if (load) {
this.loadDashboard(true);
}
this.autoRefresh();
}
};
this.extractGlobalParameters = () => {
let globalParams = {};
this.dashboard.widgets.forEach((widget) => {
if (widget.getQuery()) {
widget
.getQuery()
.getParametersDefs()
.filter(p => p.global)
.forEach((param) => {
const defaults = {};
defaults[param.name] = _.create(Object.getPrototypeOf(param), param);
defaults[param.name].locals = [];
globalParams = _.defaults(globalParams, defaults);
globalParams[param.name].locals.push(param);
});
}
});
this.globalParameters = _.values(globalParams);
};
this.onGlobalParametersChange = () => {
this.globalParameters.forEach((global) => {
global.locals.forEach((local) => {
local.value = global.value;
});
});
};
const collectFilters = (dashboard, forceRefresh) => {
const queryResultPromises = _.compact(this.dashboard.widgets.map(widget => widget.getQueryResult(forceRefresh)))
.map(queryResult => queryResult.toPromise());
$q.all(queryResultPromises).then((queryResults) => {
const filters = {};
queryResults.forEach((queryResult) => {
const queryFilters = queryResult.getFilters();
queryFilters.forEach((queryFilter) => {
const hasQueryStringValue = _.has($location.search(), queryFilter.name);
if (!(hasQueryStringValue || dashboard.dashboard_filters_enabled)) {
// If dashboard filters not enabled, or no query string value given,
// skip filters linking.
return;
}
if (hasQueryStringValue) {
queryFilter.current = $location.search()[queryFilter.name];
}
if (!_.has(filters, queryFilter.name)) {
const filter = _.extend({}, queryFilter);
filters[filter.name] = filter;
filters[filter.name].originFilters = [];
}
// TODO: merge values.
filters[queryFilter.name].originFilters.push(queryFilter);
});
});
this.filters = _.values(filters);
this.filtersOnChange = (filter) => {
_.each(filter.originFilters, (originFilter) => {
originFilter.current = filter.current;
});
};
});
};
const renderDashboard = (dashboard, force) => {
Title.set(dashboard.name);
this.extractGlobalParameters();
collectFilters(dashboard, force);
};
this.loadDashboard = _.throttle((force) => {
Dashboard.get(
{ slug: $routeParams.dashboardSlug },
(dashboard) => {
this.dashboard = dashboard;
Events.record('view', 'dashboard', dashboard.id);
renderDashboard(dashboard, force);
if ($location.search().edit === true) {
$location.search('edit', null);
this.editLayout(true);
}
if ($location.search().refresh !== undefined) {
if (this.refreshRate === null) {
const refreshRate = Math.max(30, parseFloat($location.search().refresh));
this.setRefreshRate({
name: durationHumanize(refreshRate),
rate: refreshRate,
}, false);
}
}
},
(rejection) => {
const statusGroup = Math.floor(rejection.status / 100);
if (statusGroup === 5) {
// recoverable errors - all 5** (server is temporarily unavailable
// for some reason, but it should get up soon).
this.loadDashboard();
} else {
// all kind of 4** errors are not recoverable, so just display them
throw new PromiseRejectionError(rejection);
}
},
);
}, 1000);
this.loadDashboard();
this.autoRefresh = () => {
$timeout(() => {
this.loadDashboard(true);
}, this.refreshRate.rate * 1000).then(() => this.autoRefresh());
};
this.archiveDashboard = () => {
const archive = () => {
Events.record('archive', 'dashboard', this.dashboard.id);
this.dashboard.$delete(() => {
$rootScope.$broadcast('reloadDashboards');
});
};
const title = 'Archive Dashboard';
const message = `Are you sure you want to archive the "${this.dashboard.name}" dashboard?`;
const confirm = { class: 'btn-warning', title: 'Archive' };
AlertDialog.open(title, message, confirm).then(archive);
};
this.showManagePermissionsModal = () => {
$uibModal.open({
component: 'permissionsEditor',
resolve: {
aclUrl: { url: `api/dashboards/${this.dashboard.id}/acl` },
},
});
};
this.editLayout = (enableEditing, applyChanges) => {
if (!this.isGridDisabled) {
if (!enableEditing) {
if (applyChanges) {
const changedWidgets = getWidgetsWithChangedPositions(this.dashboard.widgets);
saveDashboardLayout(changedWidgets);
} else {
// Revert changes
const items = {};
_.each(this.dashboard.widgets, (widget) => {
_.extend(widget.options.position, widget.$originalPosition);
items[widget.id] = widget.options.position;
});
if (this.updateGridItems) {
this.updateGridItems(items);
}
}
}
this.layoutEditing = enableEditing;
}
};
this.saveName = () => {
Dashboard.save(
{ slug: this.dashboard.id, version: this.dashboard.version, name: this.dashboard.name },
(dashboard) => {
this.dashboard = dashboard;
$rootScope.$broadcast('reloadDashboards');
},
(error) => {
if (error.status === 403) {
toastr.error('Name update failed: Permission denied.');
} else if (error.status === 409) {
toastr.error(
'It seems like the dashboard has been modified by another user. ' +
'Please copy/backup your changes and reload this page.',
{ autoDismiss: false },
);
}
},
);
};
this.updateDashboardFiltersState = () => {
// / do something for humanity.
collectFilters(this.dashboard, false);
};
this.addWidget = () => {
$uibModal
.open({
component: 'addWidgetDialog',
resolve: {
dashboard: () => this.dashboard,
},
})
.result.then(() => {
this.extractGlobalParameters();
// Save position of newly added widget (but not entire layout)
const widget = _.last(this.dashboard.widgets);
if (_.isObject(widget)) {
return widget.$save();
}
});
};
this.removeWidget = () => {
this.extractGlobalParameters();
if (!this.layoutEditing) {
// We need to wait a bit while `angular` updates widgets, and only then save new layout
$timeout(() => {
const changedWidgets = getWidgetsWithChangedPositions(this.dashboard.widgets);
saveDashboardLayout(changedWidgets);
}, 50);
}
};
this.toggleFullscreen = () => {
this.isFullscreen = !this.isFullscreen;
document.querySelector('body').classList.toggle('headless');
if (this.isFullscreen) {
$location.search('fullscreen', true);
} else {
$location.search('fullscreen', null);
}
};
this.togglePublished = () => {
Events.record('toggle_published', 'dashboard', this.dashboard.id);
this.dashboard.is_draft = !this.dashboard.is_draft;
this.saveInProgress = true;
Dashboard.save(
{
slug: this.dashboard.id,
name: this.dashboard.name,
is_draft: this.dashboard.is_draft,
},
(dashboard) => {
this.saveInProgress = false;
this.dashboard.version = dashboard.version;
$rootScope.$broadcast('reloadDashboards');
},
);
};
if (_.has($location.search(), 'fullscreen')) {
this.toggleFullscreen();
}
this.openShareForm = () => {
$uibModal.open({
component: 'shareDashboard',
resolve: {
dashboard: this.dashboard,
},
});
};
}
const ShareDashboardComponent = {
template: shareDashboardTemplate,
bindings: {
resolve: '<',
close: '&',
dismiss: '&',
},
controller($http) {
'ngInject';
this.dashboard = this.resolve.dashboard;
this.toggleSharing = () => {
const url = `api/dashboards/${this.dashboard.id}/share`;
if (!this.dashboard.publicAccessEnabled) {
// disable
$http
.delete(url)
.success(() => {
this.dashboard.publicAccessEnabled = false;
delete this.dashboard.public_url;
})
.error(() => {
this.dashboard.publicAccessEnabled = true;
// TODO: show message
});
} else {
$http
.post(url)
.success((data) => {
this.dashboard.publicAccessEnabled = true;
this.dashboard.public_url = data.public_url;
})
.error(() => {
this.dashboard.publicAccessEnabled = false;
// TODO: show message
});
}
};
},
};
export default function init(ngModule) {
ngModule.component('shareDashboard', ShareDashboardComponent);
ngModule.component('dashboardPage', {
template,
controller: DashboardCtrl,
});
return {
'/dashboard/:dashboardSlug': {
template: '<dashboard-page></dashboard-page>',
reloadOnSearch: false,
},
};
}