responsive-details.es6.js 1.4 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152
  1. /**
  2. * @file
  3. * Provides responsive behaviors to HTML details elements.
  4. */
  5. (($, Drupal) => {
  6. /**
  7. * Initializes the responsive behaviors for details elements.
  8. *
  9. * @type {Drupal~behavior}
  10. *
  11. * @prop {Drupal~behaviorAttach} attach
  12. * Attaches the responsive behavior to status report specific details elements.
  13. */
  14. Drupal.behaviors.responsiveDetails = {
  15. attach(context) {
  16. const $details = $(context)
  17. .find('details')
  18. .once('responsive-details');
  19. if (!$details.length) {
  20. return;
  21. }
  22. const $summaries = $details.find('> summary');
  23. function detailsToggle(matches) {
  24. if (matches) {
  25. $details.attr('open', true);
  26. $summaries.attr('aria-expanded', true);
  27. $summaries.on('click.details-open', false);
  28. } else {
  29. // If user explicitly opened one, leave it alone.
  30. const $notPressed = $details
  31. .find('> summary[aria-pressed!=true]')
  32. .attr('aria-expanded', false);
  33. $notPressed.parent('details').attr('open', false);
  34. // After resize, allow user to close previously opened details.
  35. $summaries.off('.details-open');
  36. }
  37. }
  38. function handleDetailsMQ(event) {
  39. detailsToggle(event.matches);
  40. }
  41. const mql = window.matchMedia('(min-width:48em)');
  42. mql.addListener(handleDetailsMQ);
  43. detailsToggle(mql.matches);
  44. },
  45. };
  46. })(jQuery, Drupal);