88d5ce480be5298a7c60f4c249f1f394202635f2
[yaffs-website] / web / themes / contrib / bootstrap / js / modal.jquery.ui.bridge.js
1 /**
2  * @file
3  * Bootstrap Modals.
4  */
5 (function ($, Drupal, Bootstrap, Attributes, drupalSettings) {
6   'use strict';
7
8   /**
9    * Only process this once.
10    */
11   Bootstrap.once('modal.jquery.ui.bridge', function (settings) {
12     // RTL support.
13     var rtl = document.documentElement.getAttribute('dir').toLowerCase() === 'rtl';
14
15     // Override drupal.dialog button classes. This must be done on DOM ready
16     // since core/drupal.dialog technically depends on this file and has not
17     // yet set their default settings.
18     $(function () {
19       drupalSettings.dialog.buttonClass = 'btn';
20       drupalSettings.dialog.buttonPrimaryClass = 'btn-primary';
21     });
22
23     var relayEvent = function ($element, name, stopPropagation) {
24       return function (e) {
25         if (stopPropagation === void 0 || stopPropagation) {
26           e.stopPropagation();
27         }
28         var parts = name.split('.').filter(Boolean);
29         var type = parts.shift();
30         e.target = $element[0];
31         e.currentTarget = $element[0];
32         e.namespace = parts.join('.');
33         e.type = type;
34         $element.trigger(e);
35       };
36     };
37
38     /**
39      * Proxy $.fn.dialog to $.fn.modal.
40      */
41     Bootstrap.createPlugin('dialog', function (options) {
42       // When only options are passed, jQuery UI dialog treats this like a
43       // initialization method. Destroy any existing Bootstrap modal and
44       // recreate it using the contents of the dialog HTML.
45       if (arguments.length === 1 && typeof options === 'object') {
46         this.each(function () {
47           // This part gets a little tricky. Core can potentially already
48           // semi-process this "dialog" if was created using an Ajax command
49           // (i.e. prepareDialogButtons in drupal.ajax.js). Because of this,
50           // we cannot simply dump the existing dialog content into a newly
51           // created modal because that would destroy any existing event
52           // bindings. Instead, we have to create this in steps and "move"
53           // (append) the existing content as needed.
54           var $this = $(this);
55
56           // Create a new modal to get a complete template.
57           var $modal = $(Drupal.theme('bootstrapModal', {attributes: Attributes.create(this).remove('style')}));
58
59           // Store a reference to the content inside the existing dialog.
60           // This references the actual DOM node elements which will allow
61           // jQuery to "move" then when appending below. Using $.fn.children()
62           // does not return any text nodes present and $.fn.html() only returns
63           // a string representation of the content, which effectively destroys
64           // any prior event bindings or processing.
65           var $existing = $this.contents();
66
67           // Destroy any existing Bootstrap Modal data that may have been saved.
68           $this.removeData('bs.modal');
69
70           // Set the attributes of the dialog to that of the newly created modal.
71           $this.attr(Attributes.create($modal).toPlainObject());
72
73           // Append the newly created modal markup.
74           $this.append($modal.html());
75
76           // Move the existing HTML into the modal markup that was just appended.
77           $this.find('.modal-body').append($existing);
78         });
79
80         // Indicate that the modal is a jQuery UI dialog bridge.
81         options.jQueryUiBridge = true;
82
83         // Proxy just the options to the Bootstrap Modal plugin.
84         return $.fn.modal.apply(this, [options]);
85       }
86
87       // Otherwise, proxy all arguments to the Bootstrap Modal plugin.
88       return $.fn.modal.apply(this, arguments);
89     });
90
91     /**
92      * Extend the Bootstrap Modal plugin constructor class.
93      */
94     Bootstrap.extendPlugin('modal', function () {
95       var Modal = this;
96
97       return {
98         DEFAULTS: {
99           // By default, this option is disabled. It's only flagged when a modal
100           // was created using $.fn.dialog above.
101           jQueryUiBridge: false
102         },
103         prototype: {
104
105           /**
106            * Handler for $.fn.dialog('close').
107            */
108           close: function () {
109             var _this = this;
110
111             this.hide.apply(this, arguments);
112
113             // For some reason (likely due to the transition event not being
114             // registered properly), the backdrop doesn't always get removed
115             // after the above "hide" method is invoked . Instead, ensure the
116             // backdrop is removed after the transition duration by manually
117             // invoking the internal "hideModal" method shortly thereafter.
118             setTimeout(function () {
119               if (!_this.isShown && _this.$backdrop) {
120                 _this.hideModal();
121               }
122             }, (Modal.TRANSITION_DURATION !== void 0 ? Modal.TRANSITION_DURATION : 300) + 10);
123           },
124
125           /**
126            * Creates any necessary buttons from dialog options.
127            */
128           createButtons: function () {
129             this.$footer.find('.modal-buttons').remove();
130             var buttons = this.options.dialogOptions && this.options.dialogOptions.buttons || [];
131             if (buttons.length) {
132               var $buttons = $('<div class="modal-buttons"/>').appendTo(this.$footer);
133               for (var i = 0, l = buttons.length; i < l; i++) {
134                 var button = buttons[i];
135                 var $button = $(Drupal.theme('bootstrapModalDialogButton', button));
136                 if (typeof button.click === 'function') {
137                   $button.on('click', button.click);
138                 }
139                 $buttons.append($button);
140               }
141             }
142           },
143
144           /**
145            * Initializes the Bootstrap Modal.
146            */
147           init: function () {
148             // Relay necessary events.
149             if (this.options.jQueryUiBridge) {
150               this.$element.on('hide.bs.modal',   relayEvent(this.$element, 'dialogbeforeclose', false));
151               this.$element.on('hidden.bs.modal', relayEvent(this.$element, 'dialogclose', false));
152               this.$element.on('show.bs.modal',   relayEvent(this.$element, 'dialogcreate', false));
153               this.$element.on('shown.bs.modal',  relayEvent(this.$element, 'dialogopen', false));
154             }
155
156             // Create a footer if one doesn't exist.
157             // This is necessary in case dialog.ajax.js decides to add buttons.
158             if (!this.$footer[0]) {
159               this.$footer = $(Drupal.theme('bootstrapModalFooter', {}, true)).insertAfter(this.$dialogBody);
160             }
161
162             // Create buttons.
163             this.createButtons();
164
165             // Hide the footer if there are no children.
166             if (!this.$footer.children()[0]) {
167               this.$footer.hide();
168             }
169
170             // Now call the parent init method.
171             this.super();
172
173             // Handle autoResize option (this is a drupal.dialog option).
174             if (this.options.dialogOptions && this.options.dialogOptions.autoResize && this.options.dialogOptions.position) {
175               this.position(this.options.dialogOptions.position);
176             }
177
178             // If show is enabled and currently not shown, show it.
179             if (this.options.show && !this.isShown) {
180               this.show();
181             }
182           },
183
184           /**
185            * Handler for $.fn.dialog('instance').
186            */
187           instance: function () {
188             Bootstrap.unsupported('method', 'instance', arguments);
189           },
190
191           /**
192            * Handler for $.fn.dialog('isOpen').
193            */
194           isOpen: function () {
195             return !!this.isShown;
196           },
197
198           /**
199            * Maps dialog options to the modal.
200            *
201            * @param {Object} options
202            *   The options to map.
203            */
204           mapDialogOptions: function (options) {
205             var dialogOptions = {};
206             var mappedOptions = {};
207
208             // Handle CSS properties.
209             var cssUnitRegExp = /^([+-]?(?:\d+|\d*\.\d+))([a-z]*|%)?$/;
210             var parseCssUnit = function (value, defaultUnit) {
211               var parts = ('' + value).match(cssUnitRegExp);
212               return parts && parts[1] !== void 0 ? parts[1] + (parts[2] || defaultUnit || 'px') : null;
213             };
214             var styles = {};
215             var cssProperties = ['height', 'maxHeight', 'maxWidth', 'minHeight', 'minWidth', 'width'];
216             for (var i = 0, l = cssProperties.length; i < l; i++) {
217               var prop = cssProperties[i];
218               if (options[prop] !== void 0) {
219                 var value = parseCssUnit(options[prop]);
220                 if (value) {
221                   dialogOptions[prop] = value;
222                   styles[prop] = value;
223                 }
224               }
225             }
226
227             // Apply mapped CSS styles to the modal-content container.
228             this.$content.css(styles);
229
230             // Handle deprecated "dialogClass" option by merging it with "classes".
231             var classesMap = {
232               'ui-dialog': 'modal-content',
233               'ui-dialog-titlebar': 'modal-header',
234               'ui-dialog-title': 'modal-title',
235               'ui-dialog-titlebar-close': 'close',
236               'ui-dialog-content': 'modal-body',
237               'ui-dialog-buttonpane': 'modal-footer'
238             };
239             if (options.dialogClass) {
240               if (options.classes === void 0) {
241                 options.classes = {};
242               }
243               if (options.classes['ui-dialog'] === void 0) {
244                 options.classes['ui-dialog'] = '';
245               }
246               var dialogClass = options.classes['ui-dialog'].split(' ');
247               dialogClass.push(options.dialogClass);
248               options.classes['ui-dialog'] = dialogClass.join(' ');
249               delete options.dialogClass;
250             }
251
252
253             // Bind events.
254             var events = [
255               'beforeClose', 'close',
256               'create',
257               'drag', 'dragStart', 'dragStop',
258               'focus',
259               'open',
260               'resize', 'resizeStart', 'resizeStop'
261             ];
262             for (i = 0, l = events.length; i < l; i++) {
263               var event = events[i].toLowerCase();
264               if (options[event] === void 0 || typeof options[event] !== 'function') continue;
265               this.$element.on('dialog' + event, options[event]);
266             }
267
268             // Handle the reset of the options.
269             for (var name in options) {
270               if (!options.hasOwnProperty(name) || options[name] === void 0) continue;
271
272               switch (name) {
273                 case 'appendTo':
274                   Bootstrap.unsupported('option', name, options.appendTo);
275                   break;
276
277                 case 'autoOpen':
278                   mappedOptions.show = !!options.autoOpen;
279                   break;
280
281                 // This is really a drupal.dialog option, not jQuery UI.
282                 case 'autoResize':
283                   dialogOptions.autoResize = !!options.autoResize;
284                   break;
285
286                 case 'buttons':
287                   dialogOptions.buttons = options.buttons;
288                   break;
289
290                 case 'classes':
291                   dialogOptions.classes = options.classes;
292                   for (var key in options.classes) {
293                     if (options.classes.hasOwnProperty(key) && classesMap[key] !== void 0) {
294                       // Run through Attributes to sanitize classes.
295                       var attributes = Attributes.create().addClass(options.classes[key]).toPlainObject();
296                       var selector = '.' + classesMap[key];
297                       this.$element.find(selector).addClass(attributes['class']);
298                     }
299                   }
300                   break;
301
302                 case 'closeOnEscape':
303                   dialogOptions.closeOnEscape = options.closeOnEscape;
304                   mappedOptions.keyboard = !!options.closeOnEscape;
305                   this.$close[options.closeOnEscape ? 'show' : 'hide']();
306                   if (!options.closeOnEscape && options.modal) {
307                     mappedOptions.backdrop = options.modal = 'static';
308                   }
309                   break;
310
311                 case 'closeText':
312                   Bootstrap.unsupported('option', name, options.closeText);
313                   break;
314
315                 case 'draggable':
316                   dialogOptions.draggable = options.draggable;
317                   this.$content
318                     .draggable({
319                       handle: '.modal-header',
320                       drag: relayEvent(this.$element, 'dialogdrag'),
321                       start: relayEvent(this.$element, 'dialogdragstart'),
322                       end: relayEvent(this.$element, 'dialogdragend')
323                     })
324                     .draggable(options.draggable ? 'enable' : 'disable');
325                   break;
326
327                 case 'hide':
328                   if (options.hide === false || options.hide === true) {
329                     this.$element[options.hide ? 'addClass' : 'removeClass']('fade');
330                     mappedOptions.animation = options.hide;
331                   }
332                   else {
333                     Bootstrap.unsupported('option', name + ' (complex animation)', options.hide);
334                   }
335                   break;
336
337                 case 'modal':
338                   mappedOptions.backdrop = options.modal;
339                   dialogOptions.modal = !!options.modal;
340
341                   // If not a modal and no initial position, center it.
342                   if (!options.modal && !options.position) {
343                     this.position({ my: 'center', of: window });
344                   }
345                   break;
346
347                 case 'position':
348                   dialogOptions.position = options.position;
349                   this.position(options.position);
350                   break;
351
352                 // Resizable support (must initialize first).
353                 case 'resizable':
354                   dialogOptions.resizeable = options.resizable;
355                   this.$content
356                     .resizable({
357                       resize: relayEvent(this.$element, 'dialogresize'),
358                       start: relayEvent(this.$element, 'dialogresizestart'),
359                       end: relayEvent(this.$element, 'dialogresizeend')
360                     })
361                     .resizable(options.resizable ? 'enable' : 'disable');
362                   break;
363
364                 case 'show':
365                   if (options.show === false || options.show === true) {
366                     this.$element[options.show ? 'addClass' : 'removeClass']('fade');
367                     mappedOptions.animation = options.show;
368                   }
369                   else {
370                     Bootstrap.unsupported('option', name + ' (complex animation)', options.show);
371                   }
372                   break;
373
374                 case 'title':
375                   dialogOptions.title = options.title;
376                   this.$dialog.find('.modal-title').text(options.title);
377                   break;
378
379               }
380             }
381
382             // Add the supported dialog options to the mapped options.
383             mappedOptions.dialogOptions = dialogOptions;
384
385             return mappedOptions;
386           },
387
388           /**
389            * Handler for $.fn.dialog('moveToTop').
390            */
391           moveToTop: function () {
392             Bootstrap.unsupported('method', 'moveToTop', arguments);
393           },
394
395           /**
396            * Handler for $.fn.dialog('option').
397            */
398           option: function () {
399             var clone = {options: $.extend({}, this.options)};
400
401             // Apply the parent option method to the clone of current options.
402             this.super.apply(clone, arguments);
403
404             // Merge in the cloned mapped options.
405             $.extend(true, this.options, this.mapDialogOptions(clone.options));
406           },
407
408           position: function(position) {
409             // Reset modal styling.
410             this.$element.css({
411               bottom: 'initial',
412               overflow: 'visible',
413               right: 'initial'
414             });
415
416             // Position the modal.
417             this.$element.position(position);
418           },
419
420           /**
421            * Handler for $.fn.dialog('open').
422            */
423           open: function () {
424             this.show.apply(this, arguments);
425           },
426
427           /**
428            * Handler for $.fn.dialog('widget').
429            */
430           widget: function () {
431             return this.$element;
432           }
433         }
434       };
435     });
436
437     /**
438      * Extend Drupal theming functions.
439      */
440     $.extend(Drupal.theme, /** @lend Drupal.theme */ {
441
442       /**
443        * Renders a jQuery UI Dialog compatible button element.
444        *
445        * @param {Object} button
446        *   The button object passed in the dialog options.
447        *
448        * @return {String}
449        *   The modal dialog button markup.
450        *
451        * @see http://api.jqueryui.com/dialog/#option-buttons
452        * @see http://api.jqueryui.com/button/
453        */
454       bootstrapModalDialogButton: function (button) {
455         var attributes = Attributes.create();
456
457         var icon = '';
458         var iconPosition = button.iconPosition || 'beginning';
459         iconPosition = (iconPosition === 'end' && !rtl) || (iconPosition === 'beginning' && rtl) ? 'after' : 'before';
460         if (button.icon) {
461           var iconAttributes = Attributes.create()
462             .addClass(['ui-icon', button.icon])
463             .set('aria-hidden', 'true');
464           icon = '<span' + iconAttributes + '></span>';
465         }
466
467         // Value.
468         var value = button.text;
469         attributes.set('value', iconPosition === 'before' ? icon + value : value + icon);
470
471         // Handle disabled.
472         attributes[button.disabled ? 'set' :'remove']('disabled', 'disabled');
473
474         if (button.classes) {
475           attributes.addClass(Object.keys(button.classes).map(function(key) { return button.classes[key]; }));
476         }
477         if (button['class']) {
478           attributes.addClass(button['class']);
479         }
480
481         return Drupal.theme('button', attributes);
482       }
483
484     });
485
486   });
487
488
489 })(window.jQuery, window.Drupal, window.Drupal.bootstrap, window.Attributes, window.drupalSettings);