# All files / src useIntersectionObserver.ts

99.09% Statements 327/330
85.71% Branches 12/14
100% Functions 1/1
99.09% Lines 327/330

Press n or j to go to the next uncovered block, b, p or k for the previous block.

    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    11
    12
    13
    14
    15
    16
    17
    18
    19
    20
    21
    22
    23
    24
    25
    26
    27
    28
    29
    30
    31
    32
    33
    34
    35
    36
    37
    38
    39
    40
    41
    42
    43
    44
    45
    46
    47
    48
    49
    50
    51
    52
    53
    54
    55
    56
    57
    58
    59
    60
    61
    62
    63
    64
    65
    66
    67
    68
    69
    70
    71
    72
    73
    74
    75
    76
    77
    78
    79
    80
    81
    82
    83
    84
    85
    86
    87
    88
    89
    90
    91
    92
    93
    94
    95
    96
    97
    98
    99
    100
    101
    102
    103
    104
    105
    106
    107
    108
    109
    110
    111
    112
    113
    114
    115
    116
    117
    118
    119
    120
    121
    122
    123
    124
    125
    126
    127
    128
    129
    130
    131
    132
    133
    134
    135
    136
    137
    138
    139
    140
    141
    142
    143
    144
    145
    146
    147
    148
    149
    150
    151
    152
    153
    154
    155
    156
    157
    158
    159
    160
    161
    162
    163
    164
    165
    166
    167
    168
    169
    170
    171
    172
    173
    174
    175
    176
    177
    178
    179
    180
    181
    182
    183
    184
    185
    186
    187
    188
    189
    190
    191
    192
    193
    194
    195
    196
    197
    198
    199
    200
    201
    202
    203
    204
    205
    206
    207
    208
    209
    210
    211
    212
    213
    214
    215
    216
    217
    218
    219
    220
    221
    222
    223
    224
    225
    226
    227
    228
    229
    230
    231
    232
    233
    234
    235
    236
    237
    238
    239
    240
    241
    242
    243
    244
    245
    246
    247
    248
    249
    250
    251
    252
    253
    254
    255
    256
    257
    258
    259
    260
    261
    262
    263
    264
    265
    266
    267
    268
    269
    270
    271
    272
    273
    274
    275
    276
    277
    278
    279
    280
    281
    282
    283
    284
    285
    286
    287
    288
    289
    290
    291
    292
    293
    294
    295
    296
    297
    298
    299
    300
    301
    302
    303
    304
    305
    306
    307
    308
    309
    310
    311
    312
    313
    314
    315
    316
    317
    318
    319
    320
    321
    322
    323
    324
    325
    326
    327
    328
    329
    330
    3311x
    1x
    1x
    1x
    1x
    1x
    1x
    1x
    1x
    1x
    1x
    1x
    1x
    1x
    1x
    1x
    1x
    1x
    1x
    1x
    1x
    1x
    1x
    1x
    1x
    1x
    1x
    1x
    1x
    1x
    1x
    1x
    1x
    1x
    1x
    1x
    1x
    1x
    1x
    1x
    1x
    1x
    1x
    1x
    1x
    1x
    1x
    1x
    1x
    1x
    1x
    1x
    1x
    1x
    1x
    1x
    1x
    1x
    1x
    1x
    1x
    1x
    1x
    1x
    1x
    1x
    1x
    1x
    1x
    1x
    1x
    1x
    1x
    1x
    1x
    1x
    1x
    1x
    1x
    1x
    1x
    1x
    1x
    1x
    1x
    1x
    1x
    1x
    1x
    1x
    1x
    1x
    1x
    1x
    1x
    1x
    1x
    1x
    1x
    1x
    1x
    1x
    1x
    1x
    1x
    1x
    1x
    1x
    1x
    1x
    1x
    1x
    1x
    1x
    1x
    1x
    1x
    1x
    1x
    1x
    1x
    1x
    1x
    1x
    1x
    1x
    1x
    1x
    1x
    1x
    1x
    1x
    1x
    1x
    1x
    1x
    1x
    1x
    1x
    1x
    1x
    1x
    1x
    1x
    1x
    1x
    1x
    1x
    1x
    1x
    1x
    1x
    1x
    1x
    1x
    1x
    1x
    1x
    1x
    1x
    1x
    1x
    1x
    1x
    1x
    1x
    1x
    1x
    1x
    1x
    1x
    1x
    1x
    1x
    1x
    1x
    1x
    1x
    1x
    1x
    1x
    1x
    1x
    1x
    1x
    1x
    1x
    1x
    1x
    1x
    1x
    1x
    1x
    1x
    1x
    1x
    1x
    1x
    1x
    1x
    1x
    1x
    1x
    1x
    1x
    1x
    1x
    1x
    1x
    1x
    1x
    1x
    1x
    1x
    1x
    1x
    1x
    1x
    1x
    1x
    1x
    1x
    1x
    1x
    1x
    1x
    1x
    1x
    1x
    1x
    1x
    1x
    1x
    1x
    1x
    1x
    1x
    1x
    1x
    1x
    1x
    1x
    1x
    1x
    1x
    1x
    1x
    1x
    1x
    1x
    1x
    1x
    1x
    1x
    1x
    1x
    1x
    1x
    70x
    70x
    70x
    70x
    70x
    70x
    70x
    70x
    70x
    70x
    70x
    70x
    70x
    70x
    70x
    70x
    70x
    22x
    22x
    22x

    22x
    22x
    22x
    22x
    22x
    2x
    2x
    20x
    20x
    22x
    20x
    22x

    20x
    20x
    20x
    22x
    22x
    22x
    22x
    22x
    22x
    22x
    22x
    22x
    22x
    22x
    22x
    22x
    22x
    20x
    20x
    22x
    22x
    20x
    20x
    70x
    70x
    70x
    70x
    70x
    70x
    70x
    70x
    70x
    70x
    70x
    70x
    70x
    70x
     "use client";
    import type { Ref, RefCallback, RefObject } from "react";
    import { useEffect } from "react";
    import { useEnsuredRef } from "./useEnsuredRef.js";

    /** @remarks \@since 6.0.0 */
    export type IntersectionObserverRoot = IntersectionObserverInit["root"];
    /** @remarks \@since 6.0.0 */
    export type IntersectionObserverThreshold =
      IntersectionObserverInit["threshold"];
    /** @remarks \@since 6.0.0 */
    export type IntersectionObserverRootMargin =
      IntersectionObserverInit["rootMargin"];

    /**
     * @see {@link https://developer.mozilla.org/en-US/docs/Web/API/Intersection_Observer_API#intersection_observer_options}
     * @remarks \@since 6.0.0
     */
    export interface BaseIntersectionObserverHookOptions {
      /**
       * This is the same as the normal `root` for an IntersectionObserverInit, but
       * also supports refs.
       */
      root?: RefObject<IntersectionObserverRoot> | IntersectionObserverRoot;

      /**
       * Set this to `true` if the intersection observer behavior should be
       * disabled.
       *
       * @defaultValue `false`
       */
      disabled?: boolean;

      /**
       * **When using a list of thresholds, they must either be defined outside of
       * the component or wrapped in a `useMemo` to prevent the IntersectionObserver
       * from being re-created each render.**
       *
       * @example
       * Moving Out of Render
       * ```tsx
       * const threshold = [0, 0.25, 0.5, 0.75, 1];
       *
       * function Example() {
       *   const targetRef = useIntersectionObserver({
       *     threshold,
       *     onUpdate: useCallback(([entry]) => {
       *       // do something
       *     }, []),
       *   })
       * }
       * ```
       *
       * @example
       * Wrapping in useMemo
       * ```tsx
       * interface ExampleProps {
       *   min: number;
       *   max: number;
       * }
       *
       * function Example({ min, max }: ExampleProps): ReactElement {
       *   const targetRef = useIntersectionObserver({
       *     threshold: useMemo(() => [min, max], [min, max]),
       *     onUpdate: useCallback(([entry]) => {
       *       // do something
       *     }, []),
       *   });
       * }
       * ```
       *
       * @see {@link getThreshold}
       */
      threshold?: IntersectionObserverThreshold;

      /** @see {@link getRootMargin} */
      rootMargin?: IntersectionObserverRootMargin;

      /**
       * **Must be wrapped in `useCallback` to prevent re-creating the
       * IntersectionObserver each render.**
       *
       * This can be used to dynamically generate the {@link threshold} which is
       * generally useful if you need access to the DOM or do some expensive
       * computation.
       *
       * @example
       * Simple Example
       * ```tsx
       * const targetRef = useIntersectionObserver({
       *   getThreshold: useCallback(() => {
       *     // pretend some expensive computation
       *     return [0, 0.25, 0.5, 0.75, 1];
       *   }, []),
       *   OnUpdate: useCallback(() => {
       *     // do something
       *   }, []),
       * });
       * ```
       *
       * If this option is provided, {@link threshold}'s value will be ignored.
       */
      getThreshold?(): IntersectionObserverThreshold;

      /**
       * **Must be wrapped in `useCallback` to prevent re-creating the
       * IntersectionObserver each render.**
       *
       * This can be used to dynamically generate the {@link rootMargin} which is
       * generally useful if you need access to the DOM.
       *
       * @example
       * Simple Example
       * ```tsx
       * const nodeRef = useRef<HTMLElement>();
       * const targetRef = useIntersectionObserver({
       *   getRootMargin: useCallback(() => {
       *     return `-${nodeRef.current.offsetHeight - 1}px 0px 0px`;
       *   }, []),
       *   onUpdate: useCallback(() => {
       *     // do something
       *   }, []),
       * });
       * ```
       *
       * Note: If this option is provided, {@link rootMargin} will be ignored.
       */
      getRootMargin?(): IntersectionObserverRootMargin;
    }

    /**
     * @see {@link https://developer.mozilla.org/en-US/docs/Web/API/Intersection_Observer_API#intersection_observer_options}
     * @remarks \@since 6.0.0
     */
    export interface IntersectionObserverHookOptions<E extends HTMLElement>
      extends BaseIntersectionObserverHookOptions {
      /**
       * An optional ref to merge with the ref returned by this hook.
       */
      ref?: Ref<E>;

      /**
       * **Must be wrapped in `useCallback` to prevent re-creating the
       * IntersectionObserver each render.**
       *
       * @example
       * Simple Example
       * ```tsx
       * const threshold = [0, 0.25, 0.5, 0.75, 1];
       *
       * function Example(): ReactElement {
       *   const [intersecting, setIntersecting] = useState(false);
       *   const targetRef = useIntersectionObserver({
       *     threshold,
       *     onUpdate: useCallback(([entry]) {
       *       setIntersecting(entry.isIntersecting);
       *     }, []),
       *   });
       *
       *   // implementation
       * }
       * ```
       */
      onUpdate(entries: readonly IntersectionObserverEntry[]): void;

      /**
       * **Must be wrapped in `useCallback` to prevent re-creating the
       * IntersectionObserver each render.**
       *
       * If this is defined, the {@link ref} will be ignored along with the returned
       * ref.
       *
       * @example
       * Watching Queried Elements
       * ```tsx
       * function Example(): ReactElement {
       *   useIntersectionObserver({
       *     onUpdate: useCallback((entries) => {
       *       entries.forEach((entry) => {
       *         // do stuff
       *       });
       *
       *       setIntersectingIds(intersecting);
       *     }, []),
       *     getTargets: useCallback(() => {
       *       return document.querySelectorAll('h1, h2, h3, h4, h5, h6');
       *     }, []),
       *   }),
       *
       *   return <div {...props} />;
       * }
       * ```
       */
      getTargets?(): readonly Element[];
    }

    /**
     * @example
     * Simple Example
     * ```tsx
     * // https://developer.mozilla.org/en-US/docs/Web/API/Intersection_Observer_API#a_simple_example
     *
     * import { useIntersectionObserver } from "@react-md/core";
     * import type { ReactElement } from "react";
     * import { useState } from "react";
     *
     * import styles from "./Example.module.scss";
     *
     * const numSteps = 20;
     * const thresholds = Array.from({ length: numSteps }, (_, i) => i / numSteps);
     * thresholds.push(0);
     *
     * const INCREASING = "rgba(40, 40, 190, ratio)";
     * const DECREASING = "rgba(190, 40, 40, ratio)";
     *
     * export default function Example(): ReactElement {
     *   const [{ ratio, increasing }, setState] = useState({
     *     ratio: 0.0,
     *     increasing: true,
     *   });
     *
     *   const targetRef = useIntersectionObserver({
     *     threshold: thresholds,
     *     rootMargin: "0px",
     *     onUpdate: useCallback(([entry]) => {
     *       const { intersectionRatio } = entry;
     *       setState((prevState) => {
     *         return {
     *           ratio: intersectionRatio,
     *           increasing: intersectionRatio > prevState.ratio,
     *         };
     *       });
     *     }, []),
     *   });
     *
     *   return (
     *     <div
     *       ref={targetRef}
     *       className={styles.box}
     *       style={{
     *         backgroundColor: (increasing ? INCREASING : DECREASING).replace(
     *           "ratio",
     *           `${ratio}`
     *         ),
     *       }}
     *     >
     *       <div className={styles.vertical}>
     *         Welcome to <strong>The Box!</strong>
     *       </div>
     *     </div>
     *   );
     * }
     * ```
     *
     * @remarks \@since 6.0.0
     * @see https://developer.mozilla.org/en-US/docs/Web/API/Intersection_Observer_API
     */
    export function useIntersectionObserver<E extends HTMLElement>(
      options: IntersectionObserverHookOptions<E>
    ): RefCallback<E> {
      const {
        ref,
        root,
        disabled = false,
        onUpdate,
        threshold,
        rootMargin,
        getTargets,
        getThreshold,
        getRootMargin,
      } = options;

      const [targetNodeRef, targetRef] = useEnsuredRef(ref);

      useEffect(() => {
        const element = targetNodeRef.current;
        let targets: readonly Element[] = [];
        if (getTargets) {
          targets = getTargets();
        } else if (element) {
          targets = [element];
        }

        if (disabled || !targets.length) {
          return;
        }

        let resolvedRoot: IntersectionObserverRoot;
        if (root && "current" in root) {
          resolvedRoot = root.current;
        } else {
          resolvedRoot = root;
        }

        const options: IntersectionObserverInit = {
          root: resolvedRoot,
          threshold: (getThreshold || (() => threshold))(),
          rootMargin: (getRootMargin || (() => rootMargin))(),
        };

        // Just like the ResizeObserver, you can see performance improvements by
        // sharing a single intersection observer but I don't think it's worth the
        // effort to implement here since I'd need to:
        // - check if there is an observer with the same options
        //   - if there is, add the callback to that existing observer
        //   - if there isn't, create a new observer
        // - when cleaning up, check if there are any other existing callbacks
        //   - disconnect and remove the observer if there are none left
        const observer = new IntersectionObserver(onUpdate, options);
        targets.forEach((target) => {
          observer.observe(target);
        });

        return () => {
          observer.disconnect();
        };
      }, [
        disabled,
        getRootMargin,
        getTargets,
        getThreshold,
        onUpdate,
        root,
        rootMargin,
        targetNodeRef,
        threshold,
      ]);

      return targetRef;
    }