date.es6.js 1.8 KB

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