18153b09ec731a4e5fa4e8b07ce4ea74448f2ae1
[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       for (const sourceId in drupalSettings.copyFieldValue) {
27         if (drupalSettings.copyFieldValue.hasOwnProperty(sourceId)) {
28           ids.push(sourceId);
29         }
30       }
31       if (ids.length) {
32         // Listen to value:copy events on all dependent fields.
33         // We have to use body and not document because of the way jQuery events
34         // bubble up the DOM tree.
35         $('body').once('copy-field-values').on('value:copy', this.valueTargetCopyHandler);
36         // Listen on all source elements.
37         $(`#${ids.join(', #')}`).once('copy-field-values').on('blur', this.valueSourceBlurHandler);
38       }
39     },
40     detach(context, settings, trigger) {
41       if (trigger === 'unload' && ids.length) {
42         $('body').removeOnce('copy-field-values').off('value:copy');
43         $(`#${ids.join(', #')}`).removeOnce('copy-field-values').off('blur');
44       }
45     },
46
47     /**
48      * Event handler that fill the target element with the specified value.
49      *
50      * @param {jQuery.Event} e
51      *   Event object.
52      * @param {string} value
53      *   Custom value from jQuery trigger.
54      */
55     valueTargetCopyHandler(e, value) {
56       const $target = $(e.target);
57       if ($target.val() === '') {
58         $target.val(value);
59       }
60     },
61
62     /**
63      * Handler for a Blur event on a source field.
64      *
65      * This event handler will trigger a 'value:copy' event on all dependent
66      * fields.
67      *
68      * @param {jQuery.Event} e
69      *   The event triggered.
70      */
71     valueSourceBlurHandler(e) {
72       const value = $(e.target).val();
73       const targetIds = drupalSettings.copyFieldValue[e.target.id];
74       $(`#${targetIds.join(', #')}`).trigger('value:copy', value);
75     },
76   };
77 }(jQuery, Drupal, drupalSettings));