debian-mirror-gitlab/app/assets/javascripts/lib/utils/sticky.js

61 lines
2 KiB
JavaScript
Raw Normal View History

2018-11-08 19:23:39 +05:30
import StickyFill from 'stickyfilljs';
2018-03-17 18:26:18 +05:30
export const createPlaceholder = () => {
const placeholder = document.createElement('div');
placeholder.classList.add('sticky-placeholder');
return placeholder;
};
export const isSticky = (el, scrollY, stickyTop, insertPlaceholder) => {
2017-09-10 17:25:29 +05:30
const top = Math.floor(el.offsetTop - scrollY);
2018-03-17 18:26:18 +05:30
if (top <= stickyTop && !el.classList.contains('is-stuck')) {
const placeholder = insertPlaceholder ? createPlaceholder() : null;
const heightBefore = el.offsetHeight;
2017-09-10 17:25:29 +05:30
el.classList.add('is-stuck');
2018-03-17 18:26:18 +05:30
if (insertPlaceholder) {
el.parentNode.insertBefore(placeholder, el.nextElementSibling);
placeholder.style.height = `${heightBefore - el.offsetHeight}px`;
}
} else if (top > stickyTop && el.classList.contains('is-stuck')) {
2017-09-10 17:25:29 +05:30
el.classList.remove('is-stuck');
2018-03-17 18:26:18 +05:30
if (insertPlaceholder && el.nextElementSibling && el.nextElementSibling.classList.contains('sticky-placeholder')) {
el.nextElementSibling.remove();
}
2017-09-10 17:25:29 +05:30
}
};
2018-11-08 19:23:39 +05:30
/**
* Create a listener that will toggle a 'is-stuck' class, based on the current scroll position.
*
* - If the current environment does not support `position: sticky`, do nothing.
*
* @param {HTMLElement} el The `position: sticky` element.
* @param {Number} stickyTop Used to determine when an element is stuck.
* @param {Boolean} insertPlaceholder Should a placeholder element be created when element is stuck?
*/
export const stickyMonitor = (el, stickyTop, insertPlaceholder = true) => {
2017-09-10 17:25:29 +05:30
if (!el) return;
2018-03-17 18:26:18 +05:30
if (typeof CSS === 'undefined' || !(CSS.supports('(position: -webkit-sticky) or (position: sticky)'))) return;
2017-09-10 17:25:29 +05:30
2018-03-17 18:26:18 +05:30
document.addEventListener('scroll', () => isSticky(el, window.scrollY, stickyTop, insertPlaceholder), {
2017-09-10 17:25:29 +05:30
passive: true,
});
};
2018-11-08 19:23:39 +05:30
/**
* Polyfill the `position: sticky` behavior.
*
* - If the current environment supports `position: sticky`, do nothing.
* - Can receive an iterable element list (NodeList, jQuery collection, etc.) or single HTMLElement.
*/
export const polyfillSticky = (el) => {
StickyFill.add(el);
};