Load home dashboard faster
[civicrm-core.git] / js / jquery / jquery.dashboard.js
1 /**
2 +--------------------------------------------------------------------+
3 | CiviCRM version 4.7 |
4 +--------------------------------------------------------------------+
5 | Copyright CiviCRM LLC (c) 2004-2016 |
6 +--------------------------------------------------------------------+
7 | This file is a part of CiviCRM. |
8 | |
9 | CiviCRM is free software; you can copy, modify, and distribute it |
10 | under the terms of the GNU Affero General Public License |
11 | Version 3, 19 November 2007 and the CiviCRM Licensing Exception. |
12 | |
13 | CiviCRM is distributed in the hope that it will be useful, but |
14 | WITHOUT ANY WARRANTY; without even the implied warranty of |
15 | MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. |
16 | See the GNU Affero General Public License for more details. |
17 | |
18 | You should have received a copy of the GNU Affero General Public |
19 | License and the CiviCRM Licensing Exception along |
20 | with this program; if not, contact CiviCRM LLC |
21 | at info[AT]civicrm[DOT]org. If you have questions about the |
22 | GNU Affero General Public License or the licensing of CiviCRM, |
23 | see the CiviCRM license FAQ at http://civicrm.org/licensing |
24 +--------------------------------------------------------------------+
25 *
26 * Copyright (C) 2009 Bevan Rudge
27 * Licensed to CiviCRM under the Academic Free License version 3.0.
28 *
29 * @file Defines the jQuery.dashboard() plugin.
30 *
31 * Uses jQuery 1.3, jQuery UI 1.6 and several jQuery UI extensions, most of all Sortable
32 * http://visualjquery.com/
33 * http://docs.jquery.com/UI/Sortable
34 * http://ui.jquery.com/download
35 * Sortable
36 * Draggable
37 * UI Core
38 *
39 * NOTE: This file is viewed as "legacy" and shouldn't be used to
40 * develop new functionality. Its lint problems are grandfathered
41 * (although if someone wants to cleanup+test, please feel welcome).
42 */
43 /* jshint ignore:start */
44 (function($) { // Create closure.
45 // Constructor for dashboard object.
46 $.fn.dashboard = function(options) {
47 // Public properties of dashboard.
48 var dashboard = {};
49 dashboard.element = this.empty();
50 dashboard.ready = false;
51 dashboard.columns = Array();
52 dashboard.widgets = Array();
53 // End of public properties of dashboard.
54
55 /**
56 * Public methods of dashboard.
57 */
58
59 // Saves the order of widgets for all columns including the widget.minimized status to options.ajaxCallbacks.saveColumns.
60 dashboard.saveColumns = function() {
61 // Update the display status of the empty placeholders.
62 for (var c in dashboard.columns) {
63 var col = dashboard.columns[c];
64 if ( typeof col == 'object' ) {
65 // Are there any visible children of the column (excluding the empty placeholder)?
66 if (col.element.children(':visible').not(col.emptyPlaceholder).length > 0) {
67 col.emptyPlaceholder.hide();
68 }
69 else {
70 col.emptyPlaceholder.show();
71 }
72 }
73 }
74
75 // Don't save any changes to the server unless the dashboard has finished initiating.
76 if (!dashboard.ready) {
77 return;
78 }
79
80 // Build a list of params to post to the server.
81 var params = {};
82
83 // For each column...
84 for (var c2 in dashboard.columns) {
85
86 // IDs of the sortable elements in this column.
87 var ids = (typeof dashboard.columns[c2] == 'object') ? dashboard.columns[c2].element.sortable('toArray') : undefined;
88
89 // For each id...
90 for (var w in ids) {
91 // Chop 'widget-' off of the front so that we have the real widget id.
92 var id = (typeof ids[w] == 'string') ? ids[w].substring('widget-'.length) : undefined;
93
94 // Add one flat property to the params object that will look like an array element to the PHP server.
95 // Unfortunately jQuery doesn't do this for us.
96 if ( typeof dashboard.widgets[id] == 'object' ) params['columns[' + c2 + '][' + id + ']'] = (dashboard.widgets[id].minimized ? '1' : '0');
97 }
98 }
99
100 // The ajaxCallback settings overwrite any duplicate properties.
101 $.extend(params, opts.ajaxCallbacks.saveColumns.data);
102 $.post(opts.ajaxCallbacks.saveColumns.url, params, function(response, status) {
103 invokeCallback(opts.callbacks.saveColumns, dashboard);
104 });
105 };
106
107 // Puts the dashboard into full screen mode, saving element for when the user exits full-screen mode.
108 // Does not add element to the DOM – this is the caller's responsibility.
109 // Does show and hide element though.
110 dashboard.enterFullscreen = function(element) {
111 // Hide the columns.
112 for (var c in dashboard.columns) {
113 if ( typeof dashboard.columns[c] == 'object' ) dashboard.columns[c].element.hide();
114 }
115
116 if (!dashboard.fullscreen) {
117 // Initialize.
118 var markup = '<a id="full-screen-header" class="full-screen-close-icon">' + opts.fullscreenHeaderInner + '</a>';
119 dashboard.fullscreen = {
120 headerElement: $(markup).prependTo(dashboard.element).click(dashboard.exitFullscreen).hide()
121 };
122 }
123
124 dashboard.fullscreen.headerElement.slideDown();
125 dashboard.fullscreen.currentElement = element.show();
126 dashboard.fullscreen.displayed = true;
127 invokeCallback(opts.callbacks.enterFullscreen, dashboard, dashboard.fullscreen.currentElement);
128 };
129
130 // Takes the dashboard out of full screen mode, hiding the active fullscreen element.
131 dashboard.exitFullscreen = function() {
132 if (!dashboard.fullscreen.displayed) {
133 return;
134 }
135
136 dashboard.fullscreen.headerElement.slideUp();
137 dashboard.fullscreen.currentElement.hide();
138 dashboard.fullscreen.displayed = false;
139
140 // Show the columns.
141 for (var c in dashboard.columns) {
142 if ( typeof dashboard.columns[c] == 'object' ) dashboard.columns[c].element.show();
143 }
144
145 invokeCallback(opts.callbacks.exitFullscreen, dashboard, dashboard.fullscreen.currentElement);
146 };
147 // End of public methods of dashboard.
148
149 /**
150 * Private properties of dashboard.
151 */
152
153 // Used to determine whether there are any incomplete ajax requests pending initialization of the dashboard.
154 var asynchronousRequestCounter = 0;
155
156 // Used to determine whether two resort events are resulting from the same UI event.
157 var currentReSortEvent = null;
158
159 // Merge in the caller's options with the defaults.
160 var opts = $.extend({}, $.fn.dashboard.defaults, options);
161
162 init(opts.widgetsByColumn);
163
164 return dashboard;
165 // End of constructor and private properties for dashboard object.
166
167 /**
168 * Private methods of dashboard.
169 */
170
171 // Initialize widget columns.
172 function init(widgets) {
173 var markup = '<li class="empty-placeholder">' + opts.emptyPlaceholderInner + '</li>';
174
175 // Build the dashboard in the DOM. For each column...
176 // (Don't iterate on widgets since this will break badly if the dataset has empty columns.)
177 var emptyDashboard = true;
178 for (var c = 0; c < opts.columns; c++) {
179 // Save the column to both the public scope for external accessibility and the local scope for readability.
180 var col = dashboard.columns[c] = {
181 initialWidgets: Array(),
182 element: $('<ul id="column-' + c + '" class="column column-' + c + '"></ul>').appendTo(dashboard.element)
183 };
184
185 // Add the empty placeholder now, hide it and save it.
186 col.emptyPlaceholder = $(markup).appendTo(col.element).hide();
187
188 // For each widget in this column.
189 for (var id in widgets[c]) {
190 var widgetID = id.split('-');
191 // Build a new widget object and save it to various publicly accessible places.
192 col.initialWidgets[id] = dashboard.widgets[widgetID[1]] = widget({
193 id: widgetID[1],
194 element: $('<li class="widget"></li>').appendTo(col.element),
195 initialColumn: col,
196 minimized: ( widgets[c][widgetID[1]] > 0 ? true : false )
197 });
198
199 //set empty Dashboard to false
200 emptyDashboard = false;
201 }
202 }
203
204 if ( emptyDashboard ) {
205 emptyDashboardCondition( );
206 }
207
208 invokeCallback(opts.callbacks.init, dashboard);
209 }
210
211 // function that is called when dashboard is empty
212 function emptyDashboardCondition( ) {
213 cj(".show-refresh").hide( );
214 cj("#empty-message").show( );
215 }
216
217 // Contructors for each widget call this when initialization has finished so that dashboard can complete it's intitialization.
218 function completeInit() {
219 // Don't do anything if any widgets are waiting for ajax requests to complete in order to finish initialization.
220 if (asynchronousRequestCounter > 0) {
221 return;
222 }
223
224 // Make widgets sortable across columns.
225 dashboard.sortableElement = $('.column').sortable({
226 connectWith: ['.column'],
227
228 // The class of the element by which widgets are draggable.
229 handle: '.widget-header',
230
231 // The class of placeholder elements (the 'ghost' widget showing where the dragged item would land if released now.)
232 placeholder: 'placeholder',
233 activate: function(event, ui) {
234 var h= cj(ui.item).height();
235 $('.placeholder').css('height', h +'px'); },
236
237 opacity: 0.2,
238
239 // Maks sure that only widgets are sortable, and not empty placeholders.
240 items: '> .widget',
241
242 forcePlaceholderSize: true,
243
244 // Callback functions.
245 update: resorted,
246 start: hideEmptyPlaceholders
247 });
248
249 // Update empty placeholders.
250 dashboard.saveColumns();
251 dashboard.ready = true;
252 invokeCallback(opts.callbacks.ready, dashboard);
253 }
254
255 // Callback for when any list has changed (and the user has finished resorting).
256 function resorted(e, ui) {
257 // Only do anything if we haven't already handled resorts based on changes from this UI DOM event.
258 // (resorted() gets invoked once for each list when an item is moved from one to another.)
259 if (!currentReSortEvent || e.originalEvent != currentReSortEvent) {
260 currentReSortEvent = e.originalEvent;
261 dashboard.saveColumns();
262 }
263 }
264
265 // Callback for when a user starts resorting a list. Hides all the empty placeholders.
266 function hideEmptyPlaceholders(e, ui) {
267 for (var c in dashboard.columns) {
268 if( (typeof dashboard.columns[c]) == 'object' ) dashboard.columns[c].emptyPlaceholder.hide();
269 }
270 }
271
272 // @todo use an event library to register, bind to and invoke events.
273 // @param callback is a function.
274 // @param theThis is the context given to that function when it executes. It becomes 'this' inside of that function.
275 function invokeCallback(callback, theThis, parameterOne) {
276 if (callback) {
277 callback.call(theThis, parameterOne);
278 }
279 }
280
281 /**
282 * widget object
283 * Private sub-class of dashboard
284 * Constructor starts
285 */
286 function widget(widget) {
287 // Merge default options with the options defined for this widget.
288 widget = $.extend({}, $.fn.dashboard.widget.defaults, widget);
289
290 /**
291 * Public methods of widget.
292 */
293
294 // Toggles the minimize() & maximize() methods.
295 widget.toggleMinimize = function() {
296 if (widget.minimized) {
297 widget.maximize();
298 }
299 else {
300 widget.minimize();
301 }
302
303 widget.hideSettings();
304 dashboard.saveColumns();
305 };
306 widget.minimize = function() {
307 $('.widget-content', widget.element).slideUp(opts.animationSpeed);
308 $(widget.controls.minimize.element).addClass( 'fa-caret-right' );
309 $(widget.controls.minimize.element).removeClass( 'fa-caret-down' );
310 widget.minimized = true;
311 };
312 widget.maximize = function() {
313 $('.widget-content', widget.element).slideDown(opts.animationSpeed);
314 $(widget.controls.minimize.element).removeClass( 'fa-caret-right' );
315 $(widget.controls.minimize.element).addClass( 'fa-caret-down' );
316 widget.minimized = false;
317 };
318
319 // Toggles whether the widget is in settings-display mode or not.
320 widget.toggleSettings = function() {
321 if (widget.settings.displayed) {
322 // Widgets always exit settings into maximized state.
323 widget.maximize();
324 widget.hideSettings();
325 invokeCallback(opts.widgetCallbacks.hideSettings, widget);
326 }
327 else {
328 widget.minimize();
329 widget.showSettings();
330 invokeCallback(opts.widgetCallbacks.showSettings, widget);
331 }
332 };
333 widget.showSettings = function() {
334 if (widget.settings.element) {
335 widget.settings.element.show();
336
337 // Settings are loaded via AJAX. Only execute the script if the settings have been loaded.
338 if (widget.settings.ready) {
339 getJavascript(widget.settings.script);
340 }
341 }
342 else {
343 // Settings have not been initialized. Do so now.
344 initSettings();
345 }
346 widget.settings.displayed = true;
347 };
348 widget.hideSettings = function() {
349 if (widget.settings.element) {
350 widget.settings.element.hide();
351 }
352 widget.settings.displayed = false;
353 };
354 widget.saveSettings = function() {
355 // Build list of parameters to POST to server.
356 var params = {};
357 // serializeArray() returns an array of objects. Process it.
358 var fields = widget.settings.element.serializeArray();
359 for (var i in fields) {
360 var field = fields[i];
361 // Put the values into flat object properties that PHP will parse into an array server-side.
362 // (Unfortunately jQuery doesn't do this)
363 params['settings[' + field.name + ']'] = field.value;
364 }
365
366 // Things get messy here.
367 // @todo Refactor to use currentState and targetedState properties to determine what needs
368 // to be done to get to any desired state on any UI or AJAX event – since these don't always
369 // match.
370 // E.g. When a user starts a new UI event before the Ajax event handler from a previous
371 // UI event gets invoked.
372
373 // Hide the settings first of all.
374 widget.toggleSettings();
375 // Save the real settings element so that we can restore the reference later.
376 var settingsElement = widget.settings.element;
377 // Empty the settings form.
378 widget.settings.innerElement.empty();
379 initThrobber();
380 // So that showSettings() and hideSettings() can do SOMETHING, without showing the empty settings form.
381 widget.settings.element = widget.throbber.hide();
382 widget.settings.ready = false;
383
384 // Save the settings to the server.
385 $.extend(params, opts.ajaxCallbacks.widgetSettings.data, { id: widget.id });
386 $.post(opts.ajaxCallbacks.widgetSettings.url, params, function(response, status) {
387 // Merge the response into widget.settings.
388 $.extend(widget.settings, response);
389 // Restore the reference to the real settings element.
390 widget.settings.element = settingsElement;
391 // Make sure the settings form is empty and add the updated settings form.
392 widget.settings.innerElement.empty().append(widget.settings.markup);
393 widget.settings.ready = true;
394
395 // Did the user already jump back into settings-display mode before we could finish reloading the settings form?
396 if (widget.settings.displayed) {
397 // Ooops! We had better take care of hiding the throbber and showing the settings form then.
398 widget.throbber.hide();
399 widget.showSettings();
400 invokeCallback(opts.widgetCallbacks.saveSettings, dashboard);
401 }
402 }, 'json');
403
404 // Don't let form submittal bubble up.
405 return false;
406 };
407
408 widget.enterFullscreen = function() {
409 // Make sure the widget actually supports full screen mode.
410 if (!widget.fullscreenUrl) {
411 return;
412 }
413 CRM.loadPage(widget.fullscreenUrl);
414 };
415
416 // Exit fullscreen mode.
417 widget.exitFullscreen = function() {
418 // This is just a wrapper for dashboard.exitFullscreen() which does the heavy lifting.
419 dashboard.exitFullscreen();
420 };
421
422 // Adds controls to a widget. id is for internal use and image file name in images/dashboard/ (a .gif).
423 widget.addControl = function(id, control) {
424 var markup = '<a class="crm-i ' + control.icon + '" alt="' + control.description + '" title="' + control.description + '"></a>';
425 control.element = $(markup).prependTo($('.widget-controls', widget.element)).click(control.callback);
426 };
427
428 // An external method used only by and from external scripts to reload content. Not invoked or used internally.
429 // The widget must provide the script that executes this, as well as the script that invokes it.
430 widget.reloadContent = function() {
431 getJavascript(widget.reloadContentScript);
432 invokeCallback(opts.widgetCallbacks.reloadContent, widget);
433 };
434
435 // Removes the widget from the dashboard, and saves columns.
436 widget.remove = function() {
437 if ( confirm( 'Are you sure you want to remove "' + widget.title + '"?') ) {
438 invokeCallback(opts.widgetCallbacks.remove, widget);
439 widget.element.fadeOut(opts.animationSpeed, function() {
440 $(this).remove();
441 dashboard.saveColumns();
442 });
443 }
444 };
445 // End public methods of widget.
446
447 /**
448 * Public properties of widget.
449 */
450
451 // Default controls. External script can add more with widget.addControls()
452 widget.controls = {
453 settings: {
454 description: ts('Configure this dashlet'),
455 callback: widget.toggleSettings,
456 icon: 'fa-wrench'
457 },
458 minimize: {
459 description: ts('Collapse or expand'),
460 callback: widget.toggleMinimize,
461 icon: 'fa-caret-down'
462 },
463 fullscreen: {
464 description: ts('View fullscreen'),
465 callback: widget.enterFullscreen,
466 icon: 'fa-expand'
467 },
468 close: {
469 description: ts('Remove from dashboard'),
470 callback: widget.remove,
471 icon: 'fa-times'
472 }
473 };
474 // End public properties of widget.
475
476 /**
477 * Private properties of widget.
478 */
479
480 // We're gonna 'fork' execution again, so let's tell the user to hold with us till the AJAX callback gets invoked.
481 var throbber = $(opts.throbberMarkup).appendTo(widget.element);
482 var params = $.extend({}, opts.ajaxCallbacks.getWidget.data, {id: widget.id});
483 $.getJSON(opts.ajaxCallbacks.getWidget.url, params, init);
484
485 // Help dashboard track whether we've got any outstanding requests on which initialization is pending.
486 asynchronousRequestCounter++;
487 return widget;
488 // End of private properties of widget.
489
490 /**
491 * Private methods of widget.
492 */
493
494 // Ajax callback for widget initialization.
495 function init(data, status) {
496 asynchronousRequestCounter--;
497 $.extend(widget, data);
498
499 // Delete controls that don't apply to this widget.
500 if (!widget.settings) {
501 delete widget.controls.settings;
502 }
503 if (!widget.fullscreenUrl) {
504 delete widget.controls.fullscreen;
505 }
506
507 widget.element.attr('id', 'widget-' + widget.id).addClass(widget.classes);
508 throbber.remove();
509 // Build and add the widget's DOM element.
510 $(widget.element).append(widgetHTML()).trigger('crmLoad');
511 // Save the content element so that external scripts can reload it easily.
512 widget.contentElement = $('.widget-content', widget.element);
513 $.each(widget.controls, widget.addControl);
514
515 // Switch the initial state so that it initializes to the correct state.
516 widget.minimized = !widget.minimized;
517 widget.toggleMinimize();
518 getJavascript(widget.initScript);
519 invokeCallback(opts.widgetCallbacks.get, widget);
520
521 // completeInit() is a private method of the dashboard. Let it complete initialization of the dashboard.
522 completeInit();
523 }
524
525 // Builds inner HTML for widgets.
526 function widgetHTML() {
527 var html = '';
528 html += '<div class="widget-wrapper">';
529 html += ' <div class="widget-controls"><h3 class="widget-header">' + widget.title + '</h3></div>';
530 html += ' <div class="widget-content crm-ajax-container">' + widget.content + '</div>';
531 html += '</div>';
532 return html;
533 }
534
535 // Initializes a widgets settings pane.
536 function initSettings() {
537 // Overwrite widget.settings (boolean).
538 initThrobber();
539 widget.settings = {
540 element: widget.throbber.show(),
541 ready: false
542 };
543
544 // Get the settings markup and script executables for this widget.
545 var params = $.extend({}, opts.ajaxCallbacks.widgetSettings.data, { id: widget.id });
546 $.getJSON(opts.ajaxCallbacks.widgetSettings.url, params, function(response, status) {
547 $.extend(widget.settings, response);
548 // Build and add the settings form to the DOM. Bind the form's submit event handler/callback.
549 widget.settings.element = $(widgetSettingsHTML()).appendTo($('.widget-wrapper', widget.element)).submit(widget.saveSettings);
550 // Bind the cancel button's event handler too.
551 widget.settings.cancelButton = $('.widget-settings-cancel', widget.settings.element).click(cancelEditSettings);
552 // Build and add the inner form elements from the HTML markup provided in the AJAX data.
553 widget.settings.innerElement = $('.widget-settings-inner', widget.settings.element).append(widget.settings.markup);
554 widget.settings.ready = true;
555
556 if (widget.settings.displayed) {
557 // If the user hasn't clicked away from the settings pane, then display the form.
558 widget.throbber.hide();
559 widget.showSettings();
560 }
561
562 getJavascript(widget.settings.initScript);
563 });
564 }
565
566 // Builds HTML for widget settings forms.
567 function widgetSettingsHTML() {
568 var html = '';
569 html += '<form class="widget-settings">';
570 html += ' <div class="widget-settings-inner"></div>';
571 html += ' <div class="widget-settings-buttons">';
572 html += ' <input id="' + widget.id + '-settings-save" class="widget-settings-save" value="Save" type="submit" />';
573 html += ' <input id="' + widget.id + '-settings-cancel" class="widget-settings-cancel" value="Cancel" type="submit" />';
574 html += ' </div>';
575 html += '</form>';
576 return html;
577 }
578
579 // Initializes a generic widget content throbber, for use by settings form and external scripts.
580 function initThrobber() {
581 if (!widget.throbber) {
582 widget.throbber = $(opts.throbberMarkup).appendTo($('.widget-wrapper', widget.element));
583 }
584 }
585
586 // Event handler/callback for cancel button clicks.
587 // @todo test this gets caught by all browsers when the cancel button is 'clicked' via the keyboard.
588 function cancelEditSettings() {
589 widget.toggleSettings();
590 return false;
591 }
592
593 // Helper function to execute external script on the server.
594 // @todo It would be nice to provide some context to the script. How?
595 function getJavascript(url) {
596 if (url) {
597 $.getScript(url);
598 }
599 }
600 }
601 };
602
603 // Public static properties of dashboard. Default settings.
604 $.fn.dashboard.defaults = {
605 columns: 2,
606 emptyPlaceholderInner: ts('There are no dashlets in this column of your dashboard.'),
607 fullscreenHeaderInner: ts('Back to dashboard mode'),
608 throbberMarkup: '<div class="crm-loading-element">' + ts('Loading') + '...</div>',
609 animationSpeed: 200,
610 callbacks: {},
611 widgetCallbacks: {}
612 };
613
614 // Default widget settings.
615 $.fn.dashboard.widget = {
616 defaults: {
617 minimized: false,
618 settings: false,
619 fullscreen: false
620 }
621 };
622 })(jQuery);