export default function inView(node: Element, params = { threshold: 0 }) {
    let observer: IntersectionObserver

    const handleIntersect = (e: any) => {
        const v = e[0].isIntersecting ? "enter" : "exit"
        node.dispatchEvent(new CustomEvent(v))
    }

    const setObserver = ({ threshold }) => {
        const options = { threshold }
        if (observer) observer.disconnect()
        observer = new IntersectionObserver(handleIntersect, options)
        observer.observe(node)
    }

    setObserver(params)

    return {
        update(params: any) {
            setObserver(params)
        },

        destroy() {
            if (observer) observer.disconnect()
        },
    }
}
