Open History to see the last commit
1import * as Solid from 'solid-js'
2β
3export const useLayoutEffect =
4 typeof window !== 'undefined' ? Solid.createRenderEffect : Solid.createEffect
5β
6export const usePrevious = (fn: () => boolean) => {
7 return Solid.createMemo(
8 (
9 prev: { current: boolean | null; previous: boolean | null } = {
10 current: null,
11 previous: null,
12 },
13 ) => {
14 const current = fn()
15β
16 if (prev.current !== current) {
17 prev.previous = prev.current
18 prev.current = current
19 }
20β
21 return prev
22 },
23 )
24}
25β
26/**
27 * React hook to wrap `IntersectionObserver`.
28 *
29 * This hook will create an `IntersectionObserver` and observe the ref passed to it.
30 *
31 * When the intersection changes, the callback will be called with the `IntersectionObserverEntry`.
32 *
33 * @param ref - The ref to observe
34 * @param intersectionObserverOptions - The options to pass to the IntersectionObserver
35 * @param options - The options to pass to the hook
36 * @param callback - The callback to call when the intersection changes
37 * @returns The IntersectionObserver instance
38 * @example
39 * ```tsx
40 * const MyComponent = () => {
41 * const ref = React.useRef<HTMLDivElement>(null)
42 * useIntersectionObserver(
43 * ref,
44 * (entry) => { doSomething(entry) },
45 * { rootMargin: '10px' },
46 * { disabled: false }
47 * )
48 * return <div ref={ref} />
49 * ```
50 */
51export function useIntersectionObserver<T extends Element>(
52 ref: Solid.Accessor<T | null>,
53 callback: (entry: IntersectionObserverEntry | undefined) => void,
54 intersectionObserverOptions: IntersectionObserverInit = {},
55 options: { disabled?: boolean } = {},
56): Solid.Accessor<IntersectionObserver | null> {
57 const isIntersectionObserverAvailable =
58 typeof IntersectionObserver === 'function'
59 let observerRef: IntersectionObserver | null = null
60β
61 Solid.createEffect(() => {
62 const r = ref()
63 if (!r || !isIntersectionObserverAvailable || options.disabled) {
64 return
65 }
66β
67 observerRef = new IntersectionObserver(([entry]) => {
68 callback(entry)
69 }, intersectionObserverOptions)
70β
71 observerRef.observe(r)
72β
73 Solid.onCleanup(() => {
74 observerRef?.disconnect()
75 })
76 })
77β
78 return () => observerRef
79}