Updated Drupal to 8.6. This goes with the following updates because it's possible...
[yaffs-website] / web / core / modules / system / js / system.es6.js
1 /**
2  * @file
3  * System behaviors.
4  */
5
6 (function($, Drupal, drupalSettings) {
7   // Cache IDs in an array for ease of use.
8   const ids = [];
9
10   /**
11    * Attaches field copy behavior from input fields to other input fields.
12    *
13    * When a field is filled out, apply its value to other fields that will
14    * likely use the same value. In the installer this is used to populate the
15    * administrator email address with the same value as the site email address.
16    *
17    * @type {Drupal~behavior}
18    *
19    * @prop {Drupal~behaviorAttach} attach
20    *   Attaches the field copy behavior to an input field.
21    */
22   Drupal.behaviors.copyFieldValue = {
23     attach(context) {
24       // List of fields IDs on which to bind the event listener.
25       // Create an array of IDs to use with jQuery.
26       Object.keys(drupalSettings.copyFieldValue || {}).forEach(element => {
27         ids.push(element);
28       });
29
30       if (ids.length) {
31         // Listen to value:copy events on all dependent fields.
32         // We have to use body and not document because of the way jQuery events
33         // bubble up the DOM tree.
34         $('body')
35           .once('copy-field-values')
36           .on('value:copy', this.valueTargetCopyHandler);
37         // Listen on all source elements.
38         $(`#${ids.join(', #')}`)
39           .once('copy-field-values')
40           .on('blur', this.valueSourceBlurHandler);
41       }
42     },
43     detach(context, settings, trigger) {
44       if (trigger === 'unload' && ids.length) {
45         $('body')
46           .removeOnce('copy-field-values')
47           .off('value:copy');
48         $(`#${ids.join(', #')}`)
49           .removeOnce('copy-field-values')
50           .off('blur');
51       }
52     },
53
54     /**
55      * Event handler that fill the target element with the specified value.
56      *
57      * @param {jQuery.Event} e
58      *   Event object.
59      * @param {string} value
60      *   Custom value from jQuery trigger.
61      */
62     valueTargetCopyHandler(e, value) {
63       const $target = $(e.target);
64       if ($target.val() === '') {
65         $target.val(value);
66       }
67     },
68
69     /**
70      * Handler for a Blur event on a source field.
71      *
72      * This event handler will trigger a 'value:copy' event on all dependent
73      * fields.
74      *
75      * @param {jQuery.Event} e
76      *   The event triggered.
77      */
78     valueSourceBlurHandler(e) {
79       const value = $(e.target).val();
80       const targetIds = drupalSettings.copyFieldValue[e.target.id];
81       $(`#${targetIds.join(', #')}`).trigger('value:copy', value);
82     },
83   };
84 })(jQuery, Drupal, drupalSettings);