94276f1e2302a8ec91ca8bfc1f019f6c20081216
[yaffs-website] / web / core / misc / date.es6.js
1 /**
2  * @file
3  * Polyfill for HTML5 date input.
4  */
5
6 (function($, Modernizr, Drupal) {
7   /**
8    * Attach datepicker fallback on date elements.
9    *
10    * @type {Drupal~behavior}
11    *
12    * @prop {Drupal~behaviorAttach} attach
13    *   Attaches the behavior. Accepts in `settings.date` an object listing
14    *   elements to process, keyed by the HTML ID of the form element containing
15    *   the human-readable value. Each element is an datepicker settings object.
16    * @prop {Drupal~behaviorDetach} detach
17    *   Detach the behavior destroying datepickers on effected elements.
18    */
19   Drupal.behaviors.date = {
20     attach(context, settings) {
21       const $context = $(context);
22       // Skip if date are supported by the browser.
23       if (Modernizr.inputtypes.date === true) {
24         return;
25       }
26       $context
27         .find('input[data-drupal-date-format]')
28         .once('datePicker')
29         .each(function() {
30           const $input = $(this);
31           const datepickerSettings = {};
32           const dateFormat = $input.data('drupalDateFormat');
33           // The date format is saved in PHP style, we need to convert to jQuery
34           // datepicker.
35           datepickerSettings.dateFormat = dateFormat
36             .replace('Y', 'yy')
37             .replace('m', 'mm')
38             .replace('d', 'dd');
39           // Add min and max date if set on the input.
40           if ($input.attr('min')) {
41             datepickerSettings.minDate = $input.attr('min');
42           }
43           if ($input.attr('max')) {
44             datepickerSettings.maxDate = $input.attr('max');
45           }
46           $input.datepicker(datepickerSettings);
47         });
48     },
49     detach(context, settings, trigger) {
50       if (trigger === 'unload') {
51         $(context)
52           .find('input[data-drupal-date-format]')
53           .findOnce('datePicker')
54           .datepicker('destroy');
55       }
56     },
57   };
58 })(jQuery, Modernizr, Drupal);