Spaces:
Runtime error
Runtime error
File size: 1,068 Bytes
b37570d |
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 |
/**
* @param node element to snap scroll to bottom
* @param dependency pass in a dependency to update scroll on changes.
*/
export const snapScrollToBottom = (node: HTMLElement, dependency: any) => {
let prevScrollValue = node.scrollTop;
let isDetached = false;
const handleScroll = () => {
// if user scrolled up, we detach
if (node.scrollTop < prevScrollValue) {
isDetached = true;
}
// if user scrolled back to bottom, we reattach
if (node.scrollTop === node.scrollHeight - node.clientHeight) {
isDetached = false;
}
prevScrollValue = node.scrollTop;
};
const updateScroll = (_options: { force?: boolean } = {}) => {
const defaultOptions = { force: false };
const options = { ...defaultOptions, ..._options };
const { force } = options;
if (!force && isDetached) return;
node.scroll({
top: node.scrollHeight
});
};
node.addEventListener('scroll', handleScroll);
updateScroll({ force: true });
return {
update: updateScroll,
destroy: () => {
node.removeEventListener('scroll', handleScroll);
}
};
};
|