UNPKG

@mantine/hooks

Version:

A collection of 50+ hooks for state and UI management

1 lines 1.8 kB
{"version":3,"file":"use-in-viewport.cjs","names":[],"sources":["../../src/use-in-viewport/use-in-viewport.ts"],"sourcesContent":["import { useCallback, useRef, useState } from 'react';\n\nexport interface UseInViewportReturnValue<T extends HTMLElement = any> {\n inViewport: boolean;\n ref: React.RefCallback<T | null>;\n}\n\nexport function useInViewport<T extends HTMLElement = any>(): UseInViewportReturnValue<T> {\n const observer = useRef<IntersectionObserver | null>(null);\n const [inViewport, setInViewport] = useState(false);\n\n const ref: React.RefCallback<T | null> = useCallback((node) => {\n if (typeof IntersectionObserver !== 'undefined') {\n if (node && !observer.current) {\n observer.current = new IntersectionObserver((entries) => {\n // Entries might be batched (e.g. when scrolling very fast), so we need to use the last entry to get the most recent state\n const lastEntry = entries[entries.length - 1];\n setInViewport(lastEntry.isIntersecting);\n });\n } else {\n observer.current?.disconnect();\n }\n\n if (node) {\n observer.current?.observe(node);\n } else {\n setInViewport(false);\n }\n }\n }, []);\n\n return { ref, inViewport };\n}\n\nexport namespace useInViewport {\n export type ReturnValue<T extends HTMLElement> = UseInViewportReturnValue<T>;\n}\n"],"mappings":";;;AAOA,SAAgB,gBAA0E;CACxF,MAAM,YAAA,GAAA,MAAA,QAA+C,KAAK;CAC1D,MAAM,CAAC,YAAY,kBAAA,GAAA,MAAA,UAA0B,MAAM;AAsBnD,QAAO;EAAE,MAAA,GAAA,MAAA,cApB6C,SAAS;AAC7D,OAAI,OAAO,yBAAyB,aAAa;AAC/C,QAAI,QAAQ,CAAC,SAAS,QACpB,UAAS,UAAU,IAAI,sBAAsB,YAAY;KAEvD,MAAM,YAAY,QAAQ,QAAQ,SAAS;AAC3C,mBAAc,UAAU,eAAe;MACvC;QAEF,UAAS,SAAS,YAAY;AAGhC,QAAI,KACF,UAAS,SAAS,QAAQ,KAAK;QAE/B,eAAc,MAAM;;KAGvB,EAAE,CAAC;EAEQ;EAAY"}