@yrobot/auto-scroll
Version:
This is a tool which makes scroll-container auto scroll to the bottom easy.
69 lines (68 loc) • 2.05 kB
JavaScript
const h = (l, a) => {
let n = -1 / 0, o, t = !1;
return [
(...f) => {
if (t) return null;
let r = n + a - Date.now();
return clearTimeout(o), o = window.setTimeout(() => {
n = Date.now(), l(...f);
}, Math.max(0, r)), null;
},
() => {
t = !0, clearTimeout(o);
}
];
}, u = ({ threshold: l = 24, throttleTime: a = 100 } = {}) => {
const n = {};
let o = !1, t = -1 / 0;
const [f] = h((r) => {
const c = r.target;
!o && c.scrollTop < t && (o = !0), o && c.scrollHeight - c.scrollTop - c.clientHeight <= l && (o = !1), t = c.scrollTop;
}, a);
return n.onMount = (r) => {
t = r.scrollTop, r.addEventListener("scroll", f);
}, n.onUnmount = (r) => {
r.removeEventListener("scroll", f);
}, n.escapeHook = () => o, n;
};
function v({
throttleTime: l = 100,
plugins: a = [],
offset: n = 0,
...o
}) {
const t = "container" in o ? o.container : document.querySelector(o.selector);
if (t === null) throw new Error("Container element not found");
const f = a.map((e) => {
var s;
return (s = e == null ? void 0 : e.onMount) == null ? void 0 : s.call(e, t);
}).filter((e) => typeof e == "function"), r = () => a.find((e) => {
var s;
return ((s = e == null ? void 0 : e.escapeHook) == null ? void 0 : s.call(e, t)) === !0;
}) ? !1 : (requestAnimationFrame(() => {
t.scrollTo({
top: t.scrollHeight - n
// behavior: "smooth", // will effect escapeWhenUpPlugin user scroll up detection
});
}), !0), [c] = l > 0 ? h(r, l) : [r], i = new ResizeObserver(() => {
c();
}), d = new MutationObserver(() => {
m(), c();
}), m = () => {
i.disconnect();
for (const e of t.children)
i.observe(e);
};
return m(), d.observe(t, {
childList: !0
}), () => {
i.disconnect(), d.disconnect(), f.forEach((e) => e(t)), a.forEach((e) => {
var s;
return (s = e == null ? void 0 : e.onUnmount) == null ? void 0 : s.call(e, t);
});
};
}
export {
v as default,
u as escapeWhenUpPlugin
};