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