Updated to Drupal 8.5. Core Media not yet in use.
[yaffs-website] / web / core / misc / ajax.js
1 /**
2 * DO NOT EDIT THIS FILE.
3 * See the following change record for more information,
4 * https://www.drupal.org/node/2815083
5 * @preserve
6 **/
7 function _toConsumableArray(arr) { if (Array.isArray(arr)) { for (var i = 0, arr2 = Array(arr.length); i < arr.length; i++) { arr2[i] = arr[i]; } return arr2; } else { return Array.from(arr); } }
8
9 (function ($, window, Drupal, drupalSettings) {
10   Drupal.behaviors.AJAX = {
11     attach: function attach(context, settings) {
12       function loadAjaxBehavior(base) {
13         var elementSettings = settings.ajax[base];
14         if (typeof elementSettings.selector === 'undefined') {
15           elementSettings.selector = '#' + base;
16         }
17         $(elementSettings.selector).once('drupal-ajax').each(function () {
18           elementSettings.element = this;
19           elementSettings.base = base;
20           Drupal.ajax(elementSettings);
21         });
22       }
23
24       Object.keys(settings.ajax || {}).forEach(function (base) {
25         return loadAjaxBehavior(base);
26       });
27
28       Drupal.ajax.bindAjaxLinks(document.body);
29
30       $('.use-ajax-submit').once('ajax').each(function () {
31         var elementSettings = {};
32
33         elementSettings.url = $(this.form).attr('action');
34
35         elementSettings.setClick = true;
36
37         elementSettings.event = 'click';
38
39         elementSettings.progress = { type: 'throbber' };
40         elementSettings.base = $(this).attr('id');
41         elementSettings.element = this;
42
43         Drupal.ajax(elementSettings);
44       });
45     },
46     detach: function detach(context, settings, trigger) {
47       if (trigger === 'unload') {
48         Drupal.ajax.expired().forEach(function (instance) {
49           Drupal.ajax.instances[instance.instanceIndex] = null;
50         });
51       }
52     }
53   };
54
55   Drupal.AjaxError = function (xmlhttp, uri, customMessage) {
56     var statusCode = void 0;
57     var statusText = void 0;
58     var responseText = void 0;
59     if (xmlhttp.status) {
60       statusCode = '\n' + Drupal.t('An AJAX HTTP error occurred.') + '\n' + Drupal.t('HTTP Result Code: !status', { '!status': xmlhttp.status });
61     } else {
62       statusCode = '\n' + Drupal.t('An AJAX HTTP request terminated abnormally.');
63     }
64     statusCode += '\n' + Drupal.t('Debugging information follows.');
65     var pathText = '\n' + Drupal.t('Path: !uri', { '!uri': uri });
66     statusText = '';
67
68     try {
69       statusText = '\n' + Drupal.t('StatusText: !statusText', { '!statusText': $.trim(xmlhttp.statusText) });
70     } catch (e) {}
71
72     responseText = '';
73
74     try {
75       responseText = '\n' + Drupal.t('ResponseText: !responseText', { '!responseText': $.trim(xmlhttp.responseText) });
76     } catch (e) {}
77
78     responseText = responseText.replace(/<("[^"]*"|'[^']*'|[^'">])*>/gi, '');
79     responseText = responseText.replace(/[\n]+\s+/g, '\n');
80
81     var readyStateText = xmlhttp.status === 0 ? '\n' + Drupal.t('ReadyState: !readyState', { '!readyState': xmlhttp.readyState }) : '';
82
83     customMessage = customMessage ? '\n' + Drupal.t('CustomMessage: !customMessage', { '!customMessage': customMessage }) : '';
84
85     this.message = statusCode + pathText + statusText + customMessage + responseText + readyStateText;
86
87     this.name = 'AjaxError';
88   };
89
90   Drupal.AjaxError.prototype = new Error();
91   Drupal.AjaxError.prototype.constructor = Drupal.AjaxError;
92
93   Drupal.ajax = function (settings) {
94     if (arguments.length !== 1) {
95       throw new Error('Drupal.ajax() function must be called with one configuration object only');
96     }
97
98     var base = settings.base || false;
99     var element = settings.element || false;
100     delete settings.base;
101     delete settings.element;
102
103     if (!settings.progress && !element) {
104       settings.progress = false;
105     }
106
107     var ajax = new Drupal.Ajax(base, element, settings);
108     ajax.instanceIndex = Drupal.ajax.instances.length;
109     Drupal.ajax.instances.push(ajax);
110
111     return ajax;
112   };
113
114   Drupal.ajax.instances = [];
115
116   Drupal.ajax.expired = function () {
117     return Drupal.ajax.instances.filter(function (instance) {
118       return instance && instance.element !== false && !document.body.contains(instance.element);
119     });
120   };
121
122   Drupal.ajax.bindAjaxLinks = function (element) {
123     $(element).find('.use-ajax').once('ajax').each(function (i, ajaxLink) {
124       var $linkElement = $(ajaxLink);
125
126       var elementSettings = {
127         progress: { type: 'throbber' },
128         dialogType: $linkElement.data('dialog-type'),
129         dialog: $linkElement.data('dialog-options'),
130         dialogRenderer: $linkElement.data('dialog-renderer'),
131         base: $linkElement.attr('id'),
132         element: ajaxLink
133       };
134       var href = $linkElement.attr('href');
135
136       if (href) {
137         elementSettings.url = href;
138         elementSettings.event = 'click';
139       }
140       Drupal.ajax(elementSettings);
141     });
142   };
143
144   Drupal.Ajax = function (base, element, elementSettings) {
145     var defaults = {
146       event: element ? 'mousedown' : null,
147       keypress: true,
148       selector: base ? '#' + base : null,
149       effect: 'none',
150       speed: 'none',
151       method: 'replaceWith',
152       progress: {
153         type: 'throbber',
154         message: Drupal.t('Please wait...')
155       },
156       submit: {
157         js: true
158       }
159     };
160
161     $.extend(this, defaults, elementSettings);
162
163     this.commands = new Drupal.AjaxCommands();
164
165     this.instanceIndex = false;
166
167     if (this.wrapper) {
168       this.wrapper = '#' + this.wrapper;
169     }
170
171     this.element = element;
172
173     this.element_settings = elementSettings;
174
175     this.elementSettings = elementSettings;
176
177     if (this.element && this.element.form) {
178       this.$form = $(this.element.form);
179     }
180
181     if (!this.url) {
182       var $element = $(this.element);
183       if ($element.is('a')) {
184         this.url = $element.attr('href');
185       } else if (this.element && element.form) {
186         this.url = this.$form.attr('action');
187       }
188     }
189
190     var originalUrl = this.url;
191
192     this.url = this.url.replace(/\/nojs(\/|$|\?|#)/g, '/ajax$1');
193
194     if (drupalSettings.ajaxTrustedUrl[originalUrl]) {
195       drupalSettings.ajaxTrustedUrl[this.url] = true;
196     }
197
198     var ajax = this;
199
200     ajax.options = {
201       url: ajax.url,
202       data: ajax.submit,
203       beforeSerialize: function beforeSerialize(elementSettings, options) {
204         return ajax.beforeSerialize(elementSettings, options);
205       },
206       beforeSubmit: function beforeSubmit(formValues, elementSettings, options) {
207         ajax.ajaxing = true;
208         return ajax.beforeSubmit(formValues, elementSettings, options);
209       },
210       beforeSend: function beforeSend(xmlhttprequest, options) {
211         ajax.ajaxing = true;
212         return ajax.beforeSend(xmlhttprequest, options);
213       },
214       success: function success(response, status, xmlhttprequest) {
215         if (typeof response === 'string') {
216           response = $.parseJSON(response);
217         }
218
219         if (response !== null && !drupalSettings.ajaxTrustedUrl[ajax.url]) {
220           if (xmlhttprequest.getResponseHeader('X-Drupal-Ajax-Token') !== '1') {
221             var customMessage = Drupal.t('The response failed verification so will not be processed.');
222             return ajax.error(xmlhttprequest, ajax.url, customMessage);
223           }
224         }
225
226         return ajax.success(response, status);
227       },
228       complete: function complete(xmlhttprequest, status) {
229         ajax.ajaxing = false;
230         if (status === 'error' || status === 'parsererror') {
231           return ajax.error(xmlhttprequest, ajax.url);
232         }
233       },
234
235       dataType: 'json',
236       type: 'POST'
237     };
238
239     if (elementSettings.dialog) {
240       ajax.options.data.dialogOptions = elementSettings.dialog;
241     }
242
243     if (ajax.options.url.indexOf('?') === -1) {
244       ajax.options.url += '?';
245     } else {
246       ajax.options.url += '&';
247     }
248
249     var wrapper = 'drupal_' + (elementSettings.dialogType || 'ajax');
250     if (elementSettings.dialogRenderer) {
251       wrapper += '.' + elementSettings.dialogRenderer;
252     }
253     ajax.options.url += Drupal.ajax.WRAPPER_FORMAT + '=' + wrapper;
254
255     $(ajax.element).on(elementSettings.event, function (event) {
256       if (!drupalSettings.ajaxTrustedUrl[ajax.url] && !Drupal.url.isLocal(ajax.url)) {
257         throw new Error(Drupal.t('The callback URL is not local and not trusted: !url', { '!url': ajax.url }));
258       }
259       return ajax.eventResponse(this, event);
260     });
261
262     if (elementSettings.keypress) {
263       $(ajax.element).on('keypress', function (event) {
264         return ajax.keypressResponse(this, event);
265       });
266     }
267
268     if (elementSettings.prevent) {
269       $(ajax.element).on(elementSettings.prevent, false);
270     }
271   };
272
273   Drupal.ajax.WRAPPER_FORMAT = '_wrapper_format';
274
275   Drupal.Ajax.AJAX_REQUEST_PARAMETER = '_drupal_ajax';
276
277   Drupal.Ajax.prototype.execute = function () {
278     if (this.ajaxing) {
279       return;
280     }
281
282     try {
283       this.beforeSerialize(this.element, this.options);
284
285       return $.ajax(this.options);
286     } catch (e) {
287       this.ajaxing = false;
288       window.alert('An error occurred while attempting to process ' + this.options.url + ': ' + e.message);
289
290       return $.Deferred().reject();
291     }
292   };
293
294   Drupal.Ajax.prototype.keypressResponse = function (element, event) {
295     var ajax = this;
296
297     if (event.which === 13 || event.which === 32 && element.type !== 'text' && element.type !== 'textarea' && element.type !== 'tel' && element.type !== 'number') {
298       event.preventDefault();
299       event.stopPropagation();
300       $(element).trigger(ajax.elementSettings.event);
301     }
302   };
303
304   Drupal.Ajax.prototype.eventResponse = function (element, event) {
305     event.preventDefault();
306     event.stopPropagation();
307
308     var ajax = this;
309
310     if (ajax.ajaxing) {
311       return;
312     }
313
314     try {
315       if (ajax.$form) {
316         if (ajax.setClick) {
317           element.form.clk = element;
318         }
319
320         ajax.$form.ajaxSubmit(ajax.options);
321       } else {
322         ajax.beforeSerialize(ajax.element, ajax.options);
323         $.ajax(ajax.options);
324       }
325     } catch (e) {
326       ajax.ajaxing = false;
327       window.alert('An error occurred while attempting to process ' + ajax.options.url + ': ' + e.message);
328     }
329   };
330
331   Drupal.Ajax.prototype.beforeSerialize = function (element, options) {
332     if (this.$form) {
333       var settings = this.settings || drupalSettings;
334       Drupal.detachBehaviors(this.$form.get(0), settings, 'serialize');
335     }
336
337     options.data[Drupal.Ajax.AJAX_REQUEST_PARAMETER] = 1;
338
339     var pageState = drupalSettings.ajaxPageState;
340     options.data['ajax_page_state[theme]'] = pageState.theme;
341     options.data['ajax_page_state[theme_token]'] = pageState.theme_token;
342     options.data['ajax_page_state[libraries]'] = pageState.libraries;
343   };
344
345   Drupal.Ajax.prototype.beforeSubmit = function (formValues, element, options) {};
346
347   Drupal.Ajax.prototype.beforeSend = function (xmlhttprequest, options) {
348     if (this.$form) {
349       options.extraData = options.extraData || {};
350
351       options.extraData.ajax_iframe_upload = '1';
352
353       var v = $.fieldValue(this.element);
354       if (v !== null) {
355         options.extraData[this.element.name] = v;
356       }
357     }
358
359     $(this.element).prop('disabled', true);
360
361     if (!this.progress || !this.progress.type) {
362       return;
363     }
364
365     var progressIndicatorMethod = 'setProgressIndicator' + this.progress.type.slice(0, 1).toUpperCase() + this.progress.type.slice(1).toLowerCase();
366     if (progressIndicatorMethod in this && typeof this[progressIndicatorMethod] === 'function') {
367       this[progressIndicatorMethod].call(this);
368     }
369   };
370
371   Drupal.Ajax.prototype.setProgressIndicatorBar = function () {
372     var progressBar = new Drupal.ProgressBar('ajax-progress-' + this.element.id, $.noop, this.progress.method, $.noop);
373     if (this.progress.message) {
374       progressBar.setProgress(-1, this.progress.message);
375     }
376     if (this.progress.url) {
377       progressBar.startMonitoring(this.progress.url, this.progress.interval || 1500);
378     }
379     this.progress.element = $(progressBar.element).addClass('ajax-progress ajax-progress-bar');
380     this.progress.object = progressBar;
381     $(this.element).after(this.progress.element);
382   };
383
384   Drupal.Ajax.prototype.setProgressIndicatorThrobber = function () {
385     this.progress.element = $('<div class="ajax-progress ajax-progress-throbber"><div class="throbber">&nbsp;</div></div>');
386     if (this.progress.message) {
387       this.progress.element.find('.throbber').after('<div class="message">' + this.progress.message + '</div>');
388     }
389     $(this.element).after(this.progress.element);
390   };
391
392   Drupal.Ajax.prototype.setProgressIndicatorFullscreen = function () {
393     this.progress.element = $('<div class="ajax-progress ajax-progress-fullscreen">&nbsp;</div>');
394     $('body').after(this.progress.element);
395   };
396
397   Drupal.Ajax.prototype.success = function (response, status) {
398     var _this = this;
399
400     if (this.progress.element) {
401       $(this.progress.element).remove();
402     }
403     if (this.progress.object) {
404       this.progress.object.stopMonitoring();
405     }
406     $(this.element).prop('disabled', false);
407
408     var elementParents = $(this.element).parents('[data-drupal-selector]').addBack().toArray();
409
410     var focusChanged = false;
411     Object.keys(response || {}).forEach(function (i) {
412       if (response[i].command && _this.commands[response[i].command]) {
413         _this.commands[response[i].command](_this, response[i], status);
414         if (response[i].command === 'invoke' && response[i].method === 'focus') {
415           focusChanged = true;
416         }
417       }
418     });
419
420     if (!focusChanged && this.element && !$(this.element).data('disable-refocus')) {
421       var target = false;
422
423       for (var n = elementParents.length - 1; !target && n > 0; n--) {
424         target = document.querySelector('[data-drupal-selector="' + elementParents[n].getAttribute('data-drupal-selector') + '"]');
425       }
426
427       if (target) {
428         $(target).trigger('focus');
429       }
430     }
431
432     if (this.$form) {
433       var settings = this.settings || drupalSettings;
434       Drupal.attachBehaviors(this.$form.get(0), settings);
435     }
436
437     this.settings = null;
438   };
439
440   Drupal.Ajax.prototype.getEffect = function (response) {
441     var type = response.effect || this.effect;
442     var speed = response.speed || this.speed;
443
444     var effect = {};
445     if (type === 'none') {
446       effect.showEffect = 'show';
447       effect.hideEffect = 'hide';
448       effect.showSpeed = '';
449     } else if (type === 'fade') {
450       effect.showEffect = 'fadeIn';
451       effect.hideEffect = 'fadeOut';
452       effect.showSpeed = speed;
453     } else {
454       effect.showEffect = type + 'Toggle';
455       effect.hideEffect = type + 'Toggle';
456       effect.showSpeed = speed;
457     }
458
459     return effect;
460   };
461
462   Drupal.Ajax.prototype.error = function (xmlhttprequest, uri, customMessage) {
463     if (this.progress.element) {
464       $(this.progress.element).remove();
465     }
466     if (this.progress.object) {
467       this.progress.object.stopMonitoring();
468     }
469
470     $(this.wrapper).show();
471
472     $(this.element).prop('disabled', false);
473
474     if (this.$form) {
475       var settings = this.settings || drupalSettings;
476       Drupal.attachBehaviors(this.$form.get(0), settings);
477     }
478     throw new Drupal.AjaxError(xmlhttprequest, uri, customMessage);
479   };
480
481   Drupal.AjaxCommands = function () {};
482   Drupal.AjaxCommands.prototype = {
483     insert: function insert(ajax, response, status) {
484       var $wrapper = response.selector ? $(response.selector) : $(ajax.wrapper);
485       var method = response.method || ajax.method;
486       var effect = ajax.getEffect(response);
487       var settings = void 0;
488
489       var $newContentWrapped = $('<div></div>').html(response.data);
490       var $newContent = $newContentWrapped.contents();
491
492       if ($newContent.length !== 1 || $newContent.get(0).nodeType !== 1) {
493         $newContent = $newContentWrapped;
494       }
495
496       switch (method) {
497         case 'html':
498         case 'replaceWith':
499         case 'replaceAll':
500         case 'empty':
501         case 'remove':
502           settings = response.settings || ajax.settings || drupalSettings;
503           Drupal.detachBehaviors($wrapper.get(0), settings);
504       }
505
506       $wrapper[method]($newContent);
507
508       if (effect.showEffect !== 'show') {
509         $newContent.hide();
510       }
511
512       if ($newContent.find('.ajax-new-content').length > 0) {
513         $newContent.find('.ajax-new-content').hide();
514         $newContent.show();
515         $newContent.find('.ajax-new-content')[effect.showEffect](effect.showSpeed);
516       } else if (effect.showEffect !== 'show') {
517         $newContent[effect.showEffect](effect.showSpeed);
518       }
519
520       if ($newContent.parents('html').length > 0) {
521         settings = response.settings || ajax.settings || drupalSettings;
522         Drupal.attachBehaviors($newContent.get(0), settings);
523       }
524     },
525     remove: function remove(ajax, response, status) {
526       var settings = response.settings || ajax.settings || drupalSettings;
527       $(response.selector).each(function () {
528         Drupal.detachBehaviors(this, settings);
529       }).remove();
530     },
531     changed: function changed(ajax, response, status) {
532       var $element = $(response.selector);
533       if (!$element.hasClass('ajax-changed')) {
534         $element.addClass('ajax-changed');
535         if (response.asterisk) {
536           $element.find(response.asterisk).append(' <abbr class="ajax-changed" title="' + Drupal.t('Changed') + '">*</abbr> ');
537         }
538       }
539     },
540     alert: function alert(ajax, response, status) {
541       window.alert(response.text, response.title);
542     },
543     redirect: function redirect(ajax, response, status) {
544       window.location = response.url;
545     },
546     css: function css(ajax, response, status) {
547       $(response.selector).css(response.argument);
548     },
549     settings: function settings(ajax, response, status) {
550       var ajaxSettings = drupalSettings.ajax;
551
552       if (ajaxSettings) {
553         Drupal.ajax.expired().forEach(function (instance) {
554
555           if (instance.selector) {
556             var selector = instance.selector.replace('#', '');
557             if (selector in ajaxSettings) {
558               delete ajaxSettings[selector];
559             }
560           }
561         });
562       }
563
564       if (response.merge) {
565         $.extend(true, drupalSettings, response.settings);
566       } else {
567         ajax.settings = response.settings;
568       }
569     },
570     data: function data(ajax, response, status) {
571       $(response.selector).data(response.name, response.value);
572     },
573     invoke: function invoke(ajax, response, status) {
574       var $element = $(response.selector);
575       $element[response.method].apply($element, _toConsumableArray(response.args));
576     },
577     restripe: function restripe(ajax, response, status) {
578       $(response.selector).find('> tbody > tr:visible, > tr:visible').removeClass('odd even').filter(':even').addClass('odd').end().filter(':odd').addClass('even');
579     },
580     update_build_id: function update_build_id(ajax, response, status) {
581       $('input[name="form_build_id"][value="' + response.old + '"]').val(response.new);
582     },
583     add_css: function add_css(ajax, response, status) {
584       $('head').prepend(response.data);
585
586       var match = void 0;
587       var importMatch = /^@import url\("(.*)"\);$/igm;
588       if (document.styleSheets[0].addImport && importMatch.test(response.data)) {
589         importMatch.lastIndex = 0;
590         do {
591           match = importMatch.exec(response.data);
592           document.styleSheets[0].addImport(match[1]);
593         } while (match);
594       }
595     }
596   };
597 })(jQuery, window, Drupal, drupalSettings);