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

Ignoring revisions in .git-blame-ignore-revs. Click here to bypass and see the normal blame view.

61 lines
1.8 KiB
JavaScript
Raw Normal View History

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
2018-12-13 13:39:08 +05:30
if (
insertPlaceholder &&
el.nextElementSibling &&
el.nextElementSibling.classList.contains('sticky-placeholder')
) {
2018-03-17 18:26:18 +05:30
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-12-13 13:39:08 +05:30
if (
typeof CSS === 'undefined' ||
!CSS.supports('(position: -webkit-sticky) or (position: sticky)')
)
return;
2017-09-10 17:25:29 +05:30
2018-12-13 13:39:08 +05:30
document.addEventListener(
'scroll',
() => isSticky(el, window.scrollY, stickyTop, insertPlaceholder),
{
passive: true,
},
);
2017-09-10 17:25:29 +05:30
};