UNPKG

@dfsj/ec-hooks

Version:

贵州东方世纪常用 hook。

115 lines (114 loc) 3.27 kB
import { defaults as O, debounce as w } from "lodash-es"; import { ref as h, shallowRef as g, onMounted as k, readonly as A } from "vue"; import { clamp as D } from "../utils/math/index.js"; import { useHover as P } from "./useHover.js"; const v = []; for (let o = 0; o <= 1; o += 0.01) v.push(o); const V = "0px", _ = 1, B = 1e-3, L = { thresholds: v, visibleThreshold: _, rootMargin: V }; function U(o, a = L) { const i = h(), r = g(), e = g([]), d = g([]), f = h(), s = h(), n = h(null), p = [], b = O(a, L), y = D( +(b.visibleThreshold ?? 1), B, _ ); let m = !0; const E = w(S, 100), { setHoverEle: H } = P({ in: R, out: T }); return k(() => { o.forEach((t) => { typeof t == "string" ? (p.push(document.getElementById(t)), m = !0) : z(t) ? (p.push(t), m = !1) : console.log("targets 必须是 dom 的 id 属性的数组或者 dom 数组"); }), S(); }), { //firstVisible: readonly(firstVisible), //visible: readonly(visible), //hidden: readonly(hidden), //isScrollEnd: readonly(isScrollEnd), //isScrollTop: readonly(isScrollEnd), firstVisible: r, visible: e, hidden: d, isScrollEnd: s, isScrollTop: f, setScrollContainer: M, enableScrollLocation: A(i), stopScrollLocation: T, startScrollLocation: R }; function M(t) { n.value = t, H(t); } function S() { j(p, n.value, b.thresholds, b.rootMargin).then( ({ visible: t, hidden: x }) => { let l = t.find((c) => c.intersectionRatio >= y); l || (l = t.sort((u, I) => I.intersectionRatio - u.intersectionRatio)[0]), m ? r.value = l == null ? void 0 : l.target.id : r.value = l == null ? void 0 : l.target, e.value = t.map((c) => { var u; return { // ...item, //@ts-ignore id: (u = c.target) == null ? void 0 : u.id, //@ts-ignore visibleRatio: c.intersectionRatio }; }), d.value = x.map((c) => { var u; return { // ...item, //@ts-ignore id: (u = c.target) == null ? void 0 : u.id, //@ts-ignore visibleRatio: c.intersectionRatio }; }); } ), f.value = F(n.value), s.value = G(n.value); } function T() { i.value = !1, n.value && n.value.removeEventListener("scroll", E); } function R() { i.value = !0, n.value && n.value.addEventListener("scroll", E); } } function j(o, a, i = v, r = V) { return Promise.all( Array.from(o).map((e) => q(e, a, i, r)) ).then((e) => { const d = e.filter((s) => s.intersectionRatio > 0), f = e.filter((s) => s.intersectionRatio === 0); return { visible: d, hidden: f }; }); } function q(o, a = document.body, i = v, r = "0px") { const e = { root: a, rootMargin: r, threshold: i }; return new Promise((d) => { new IntersectionObserver((s) => { s.forEach((n) => { d(n); }); }, e).observe(o); }); } function z(o) { return o instanceof Element || o instanceof HTMLDocument; } function F(o) { return o.scrollTop === 0; } function G(o) { const { clientHeight: a, scrollTop: i, scrollHeight: r } = o; return r <= a + i; } export { U as useIntersection };