1
0
mirror of https://github.com/misskey-dev/misskey synced 2024-12-12 21:59:02 +09:00
misskey/src/client/scripts/scroll.ts
syuilo 1eda7c8565
Chat UI (#7197)
* wip

* wip

* wip

* wip

* refactor

* Update note.vue

* wip
2021-02-14 22:26:07 +09:00

75 lines
2.2 KiB
TypeScript

export function getScrollContainer(el: Element | null): Element | null {
if (el == null || el.tagName === 'BODY') return null;
const overflow = window.getComputedStyle(el).getPropertyValue('overflow');
if (overflow.endsWith('auto')) { // xとyを個別に指定している場合、hidden auto みたいな値になる
return el;
} else {
return getScrollContainer(el.parentElement);
}
}
export function getScrollPosition(el: Element | null): number {
const container = getScrollContainer(el);
return container == null ? window.scrollY : container.scrollTop;
}
export function isTopVisible(el: Element | null): boolean {
const scrollTop = getScrollPosition(el);
const topPosition = el.offsetTop; // TODO: container内でのelの相対位置を取得できればより正確になる
return scrollTop <= topPosition;
}
export function onScrollTop(el: Element, cb) {
const container = getScrollContainer(el) || window;
const onScroll = ev => {
if (!document.body.contains(el)) return;
if (isTopVisible(el)) {
cb();
container.removeEventListener('scroll', onScroll);
}
};
container.addEventListener('scroll', onScroll, { passive: true });
}
export function onScrollBottom(el: Element, cb) {
const container = getScrollContainer(el) || window;
const onScroll = ev => {
if (!document.body.contains(el)) return;
const pos = getScrollPosition(el);
if (pos + el.clientHeight > el.scrollHeight - 1) {
cb();
container.removeEventListener('scroll', onScroll);
}
};
container.addEventListener('scroll', onScroll, { passive: true });
}
export function scroll(el: Element, top: number) {
const container = getScrollContainer(el);
if (container == null) {
window.scroll({ top: top, behavior: 'instant' });
} else {
container.scrollTop = top;
}
}
export function scrollToTop(el: Element) {
scroll(el, 0);
}
export function scrollToBottom(el: Element) {
scroll(el, 99999); // TODO: ちゃんと計算する
}
export function isBottom(el: Element, asobi = 0) {
const container = getScrollContainer(el);
const current = container
? el.scrollTop + el.offsetHeight
: window.scrollY + window.innerHeight;
const max = container
? el.scrollHeight
: document.body.offsetHeight;
return current >= (max - asobi);
}