system.date.es6.js 1.6 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162
  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(
  38. /\\?(.?)/gi,
  39. (key, value) => (dateFormats[key] ? dateFormats[key] : value),
  40. );
  41. $preview.html(dateString);
  42. $target.toggleClass('js-hide', !dateString.length);
  43. }
  44. /**
  45. * On given event triggers the date character replacement.
  46. */
  47. $source
  48. .on(
  49. 'keyup.dateFormat change.dateFormat input.dateFormat',
  50. dateFormatHandler,
  51. )
  52. // Initialize preview.
  53. .trigger('keyup');
  54. },
  55. };
  56. })(jQuery, Drupal, drupalSettings);