drupal/core/misc/collapse.js

74 lines
2.2 KiB
JavaScript

/**
* DO NOT EDIT THIS FILE.
* See the following change record for more information,
* https://www.drupal.org/node/2815083
* @preserve
**/
(function ($, Modernizr, Drupal) {
function CollapsibleDetails(node) {
this.$node = $(node);
this.$node.data('details', this);
const anchor = window.location.hash && window.location.hash !== '#' ? `, ${window.location.hash}` : '';
if (this.$node.find(`.error${anchor}`).length) {
this.$node.attr('open', true);
}
this.setupSummaryPolyfill();
}
$.extend(CollapsibleDetails, {
instances: []
});
$.extend(CollapsibleDetails.prototype, {
setupSummaryPolyfill() {
const $summary = this.$node.find('> summary');
$summary.attr('tabindex', '-1');
$('<span class="details-summary-prefix visually-hidden"></span>').append(this.$node.attr('open') ? Drupal.t('Hide') : Drupal.t('Show')).prependTo($summary).after(document.createTextNode(' '));
$('<a class="details-title"></a>').attr('href', `#${this.$node.attr('id')}`).prepend($summary.contents()).appendTo($summary);
$summary.append(this.$summary).on('click', $.proxy(this.onSummaryClick, this));
},
onSummaryClick(e) {
this.toggle();
e.preventDefault();
},
toggle() {
const isOpen = !!this.$node.attr('open');
const $summaryPrefix = this.$node.find('> summary span.details-summary-prefix');
if (isOpen) {
$summaryPrefix.html(Drupal.t('Show'));
} else {
$summaryPrefix.html(Drupal.t('Hide'));
}
setTimeout(() => {
this.$node.attr('open', !isOpen);
}, 0);
}
});
Drupal.behaviors.collapse = {
attach(context) {
if (Modernizr.details) {
return;
}
once('collapse', 'details', context).forEach(detail => {
detail.classList.add('collapse-processed');
CollapsibleDetails.instances.push(new CollapsibleDetails(detail));
});
}
};
const handleFragmentLinkClickOrHashChange = (e, $target) => {
$target.parents('details').not('[open]').find('> summary').trigger('click');
};
$('body').on('formFragmentLinkClickOrHashChange.details', handleFragmentLinkClickOrHashChange);
Drupal.CollapsibleDetails = CollapsibleDetails;
})(jQuery, Modernizr, Drupal);