date.es6.js 1.9 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758
  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
  26. .find('input[data-drupal-date-format]')
  27. .once('datePicker')
  28. .each(function() {
  29. const $input = $(this);
  30. const datepickerSettings = {};
  31. const dateFormat = $input.data('drupalDateFormat');
  32. // The date format is saved in PHP style, we need to convert to jQuery
  33. // datepicker.
  34. datepickerSettings.dateFormat = dateFormat
  35. .replace('Y', 'yy')
  36. .replace('m', 'mm')
  37. .replace('d', 'dd');
  38. // Add min and max date if set on the input.
  39. if ($input.attr('min')) {
  40. datepickerSettings.minDate = $input.attr('min');
  41. }
  42. if ($input.attr('max')) {
  43. datepickerSettings.maxDate = $input.attr('max');
  44. }
  45. $input.datepicker(datepickerSettings);
  46. });
  47. },
  48. detach(context, settings, trigger) {
  49. if (trigger === 'unload') {
  50. $(context)
  51. .find('input[data-drupal-date-format]')
  52. .findOnce('datePicker')
  53. .datepicker('destroy');
  54. }
  55. },
  56. };
  57. })(jQuery, Modernizr, Drupal);