system.date.es6.js 1.5 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051
  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.find('[data-drupal-date-formatter="source"]').once('dateFormat');
  19. const $target = $context.find('[data-drupal-date-formatter="preview"]').once('dateFormat');
  20. const $preview = $target.find('em');
  21. // All elements have to exist.
  22. if (!$source.length || !$target.length) {
  23. return;
  24. }
  25. /**
  26. * Event handler that replaces date characters with value.
  27. *
  28. * @param {jQuery.Event} e
  29. * The jQuery event triggered.
  30. */
  31. function dateFormatHandler(e) {
  32. const baseValue = $(e.target).val() || '';
  33. const dateString = baseValue.replace(/\\?(.?)/gi, (key, value) => (dateFormats[key] ? dateFormats[key] : value));
  34. $preview.html(dateString);
  35. $target.toggleClass('js-hide', !dateString.length);
  36. }
  37. /**
  38. * On given event triggers the date character replacement.
  39. */
  40. $source.on('keyup.dateFormat change.dateFormat input.dateFormat', dateFormatHandler)
  41. // Initialize preview.
  42. .trigger('keyup');
  43. },
  44. };
  45. }(jQuery, Drupal, drupalSettings));