sector_long_form-1.0.x-dev/components/pager/pager.js
components/pager/pager.js
/**
* Enable full page view or in-page pagination of sections.
*/
(function () {
'use strict';
/**
* A pager for the long form document.
*/
Drupal.behaviors.long_form_pager = {
attach: (context, settings) => {
const { sector_long_form: config } = settings;
const prose = document.querySelector('.prose');
const pager = document.querySelector(`.${config.pager_class}`);
const first_chunk = prose.querySelector(`.${config.chunker_class}:first-of-type`);
const navigate = {
previous: (current) => {
const next = current.previousElementSibling;
if (next && next.classList.contains(config.chunker_class)) {
return next
}
return current.parentElement.querySelector(`.${config.chunker_class}:last-of-type`)
},
next: (current) => {
const next = current.nextElementSibling;
if (next && next.classList.contains(config.chunker_class)) {
return next
}
return first_chunk
}
}
const marker = document.createElement('span')
marker.classList.add('long-form__toc-marker')
first_chunk.previousElementSibling.after(marker)
pager.querySelectorAll('.long-form__pager-btn[data-direction]').forEach(pagerButton => {
pagerButton.addEventListener('click', async ({ target }) => {
const { direction } = target.dataset;
const current = document.querySelector(`.${config.chunker_class}:is([aria-hidden="false"])`);
const newItem = navigate[direction](current);
const id = newItem.querySelector('h2[id]:first-of-type');
if (id) {
window.location.hash = id.getAttribute('id')
marker.scrollIntoView({
behavior: 'smooth',
block: "start", inline: "nearest"
})
}
})
})
}
};
})(drupalSettings);
