system.date.es6.js 1.6 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061
  1. /**
  2. * @file
  3. * Provides date format preview feature.
  4. */
  5. (function($, Drupal, drupalSettings) {
  6. const dateFormats = drupalSettings.dateFormats;
  7. /**
  8. * Display the preview for date format entered.
  9. *
  10. * @type {Drupal~behavior}
  11. *
  12. * @prop {Drupal~behaviorAttach} attach
  13. * Attach behavior for previewing date formats on input elements.
  14. */
  15. Drupal.behaviors.dateFormat = {
  16. attach(context) {
  17. const $context = $(context);
  18. const $source = $context
  19. .find('[data-drupal-date-formatter="source"]')
  20. .once('dateFormat');
  21. const $target = $context
  22. .find('[data-drupal-date-formatter="preview"]')
  23. .once('dateFormat');
  24. const $preview = $target.find('em');
  25. // All elements have to exist.
  26. if (!$source.length || !$target.length) {
  27. return;
  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) =>
  38. dateFormats[key] ? dateFormats[key] : value,
  39. );
  40. $preview.text(dateString);
  41. $target.toggleClass('js-hide', !dateString.length);
  42. }
  43. /**
  44. * On given event triggers the date character replacement.
  45. */
  46. $source
  47. .on(
  48. 'keyup.dateFormat change.dateFormat input.dateFormat',
  49. dateFormatHandler,
  50. )
  51. // Initialize preview.
  52. .trigger('keyup');
  53. },
  54. };
  55. })(jQuery, Drupal, drupalSettings);