@sorens/artist-svelte
Version:
an opinionated and clean UI framework for SvelteKit with theme support built-in
39 lines (38 loc) • 1.44 kB
JavaScript
import { browser } from '$app/env';
import { readable } from 'svelte/store';
export const currentBodyPosition = () => browser && { scrollY: window.scrollY, scrollX: window.scrollX };
let scrollThreshold = 50;
export const store = readable(currentBodyPosition(), (set) => {
let position = currentBodyPosition().scrollY;
/* istanbul ignore next */
const setScrollHeight = () => {
const currentScrollPosition = currentBodyPosition();
const direction = position > currentScrollPosition.scrollY ? 'up' : 'down';
if (Math.abs(position - currentScrollPosition.scrollY) > scrollThreshold)
position = currentScrollPosition.scrollY;
set({ ...currentScrollPosition, direction });
};
browser && window.addEventListener('scroll', setScrollHeight);
return () => {
if (browser)
window.removeEventListener('scroll', setScrollHeight);
};
});
export default (threshold = 50) => {
scrollThreshold = threshold;
const setScroll = (ScrollToOptions) => {
if (!browser) /* istanbul ignore next */
return;
window.scrollTo({ behavior: 'smooth', ...ScrollToOptions });
};
const scrollToTop = () => {
if (!browser) /* istanbul ignore next */
return;
window.scrollTo({ behavior: 'smooth', top: 0 });
};
return {
scrollPosition: store,
scrollToTop,
setScroll
};
};