UNPKG

@vue-widget/hooks

Version:

hooks from react to vue

39 lines (38 loc) 1.7 kB
import { __assign, __rest } from "tslib"; import "intersection-observer"; import { getTargetElement } from "../utils/domTarget"; import { useState } from "../useState"; import { toRef, unref } from "vue"; import useEffectWithTarget from "../utils/useEffectWithTarget"; import { getArray } from "../utils/getArray"; export function useInViewport(target, options) { var _target = toRef(target); var _options = toRef(options || {}); var _a = useState(), state = _a[0], setState = _a[1]; var _b = useState(), ratio = _b[0], setRatio = _b[1]; useEffectWithTarget(function () { var targets = getArray(unref(target)); var els = targets .map(function (element) { return getTargetElement(element); }) .filter(Boolean); if (!els.length) { setState(false); setRatio(0); return; } var _a = _options.value, callback = _a.callback, option = __rest(_a, ["callback"]); var observer = new IntersectionObserver(function (entries) { for (var _i = 0, entries_1 = entries; _i < entries_1.length; _i++) { var entry = entries_1[_i]; setRatio(entry.intersectionRatio); setState(entry.isIntersecting); callback === null || callback === void 0 ? void 0 : callback(entry); } }, __assign(__assign({}, option), { root: getTargetElement(option === null || option === void 0 ? void 0 : option.root) })); els.forEach(function (el) { return observer.observe(el); }); return function () { observer.disconnect(); }; }, [_options], _target); return [state, ratio]; }