962dde39c3b6dfb32e8a5a38efaaa229679fbb27
[yaffs-website] / web / core / modules / system / js / system.date.es6.js
1 /**
2  * @file
3  * Provides date format preview feature.
4  */
5
6 (function ($, Drupal, drupalSettings) {
7   const dateFormats = drupalSettings.dateFormats;
8
9   /**
10    * Display the preview for date format entered.
11    *
12    * @type {Drupal~behavior}
13    *
14    * @prop {Drupal~behaviorAttach} attach
15    *   Attach behavior for previewing date formats on input elements.
16    */
17   Drupal.behaviors.dateFormat = {
18     attach(context) {
19       const $context = $(context);
20       const $source = $context.find('[data-drupal-date-formatter="source"]').once('dateFormat');
21       const $target = $context.find('[data-drupal-date-formatter="preview"]').once('dateFormat');
22       const $preview = $target.find('em');
23
24       // All elements have to exist.
25       if (!$source.length || !$target.length) {
26         return;
27       }
28
29       /**
30        * Event handler that replaces date characters with value.
31        *
32        * @param {jQuery.Event} e
33        *   The jQuery event triggered.
34        */
35       function dateFormatHandler(e) {
36         const baseValue = $(e.target).val() || '';
37         const dateString = baseValue.replace(/\\?(.?)/gi, (key, value) => dateFormats[key] ? dateFormats[key] : value);
38
39         $preview.html(dateString);
40         $target.toggleClass('js-hide', !dateString.length);
41       }
42
43       /**
44        * On given event triggers the date character replacement.
45        */
46       $source.on('keyup.dateFormat change.dateFormat input.dateFormat', dateFormatHandler)
47         // Initialize preview.
48         .trigger('keyup');
49     },
50   };
51 }(jQuery, Drupal, drupalSettings));