@tanstack/solid-router
Version:
Modern and scalable routing for Solid applications
1 lines • 2.81 kB
Source Map (JSON)
{"version":3,"file":"utils.cjs","names":[],"sources":["../../src/utils.ts"],"sourcesContent":["import * as Solid from 'solid-js'\n\nexport const usePrevious = (fn: () => boolean) => {\n return Solid.createMemo(\n (\n prev: { current: boolean | null; previous: boolean | null } = {\n current: null,\n previous: null,\n },\n ) => {\n const current = fn()\n\n if (prev.current !== current) {\n prev.previous = prev.current\n prev.current = current\n }\n\n return prev\n },\n )\n}\n\n/**\n * React hook to wrap `IntersectionObserver`.\n *\n * This hook will create an `IntersectionObserver` and observe the ref passed to it.\n *\n * When the intersection changes, the callback will be called with the `IntersectionObserverEntry`.\n *\n * @param ref - The ref to observe\n * @param intersectionObserverOptions - The options to pass to the IntersectionObserver\n * @param options - The options to pass to the hook\n * @param callback - The callback to call when the intersection changes\n * @returns The IntersectionObserver instance\n * @example\n * ```tsx\n * const MyComponent = () => {\n * const ref = React.useRef<HTMLDivElement>(null)\n * useIntersectionObserver(\n * ref,\n * (entry) => { doSomething(entry) },\n * { rootMargin: '10px' },\n * { disabled: false }\n * )\n * return <div ref={ref} />\n * ```\n */\nexport function useIntersectionObserver<T extends Element>(\n ref: Solid.Accessor<T | null>,\n callback: (entry: IntersectionObserverEntry | undefined) => void,\n intersectionObserverOptions: IntersectionObserverInit = {},\n options: { disabled?: boolean } = {},\n): Solid.Accessor<IntersectionObserver | null> {\n const isIntersectionObserverAvailable =\n typeof IntersectionObserver === 'function'\n let observerRef: IntersectionObserver | null = null\n\n Solid.createEffect(() => {\n const r = ref()\n if (!r || !isIntersectionObserverAvailable || options.disabled) {\n return\n }\n\n observerRef = new IntersectionObserver(([entry]) => {\n callback(entry)\n }, intersectionObserverOptions)\n\n observerRef.observe(r)\n\n Solid.onCleanup(() => {\n observerRef?.disconnect()\n })\n })\n\n return () => observerRef\n}\n"],"mappings":";;;;AAEA,IAAa,eAAe,OAAsB;AAChD,QAAO,SAAM,YAET,OAA8D;EAC5D,SAAS;EACT,UAAU;EACX,KACE;EACH,MAAM,UAAU,IAAI;AAEpB,MAAI,KAAK,YAAY,SAAS;AAC5B,QAAK,WAAW,KAAK;AACrB,QAAK,UAAU;;AAGjB,SAAO;GAEV;;;;;;;;;;;;;;;;;;;;;;;;;;;AA4BH,SAAgB,wBACd,KACA,UACA,8BAAwD,EAAE,EAC1D,UAAkC,EAAE,EACS;CAC7C,MAAM,kCACJ,OAAO,yBAAyB;CAClC,IAAI,cAA2C;AAE/C,UAAM,mBAAmB;EACvB,MAAM,IAAI,KAAK;AACf,MAAI,CAAC,KAAK,CAAC,mCAAmC,QAAQ,SACpD;AAGF,gBAAc,IAAI,sBAAsB,CAAC,WAAW;AAClD,YAAS,MAAM;KACd,4BAA4B;AAE/B,cAAY,QAAQ,EAAE;AAEtB,WAAM,gBAAgB;AACpB,gBAAa,YAAY;IACzB;GACF;AAEF,cAAa"}