# All files useResizeObserver.ts

99.23% Statements 261/263
89.28% Branches 25/28
100% Functions 6/6
99.23% Lines 261/263

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
    2641x
    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
    10x
    10x
    10x
    10x
    10x
    10x
    10x
    10x
    10x
    10x
    10x
    10x
    10x
    10x
    10x
    10x
    10x
    10x
    10x
    10x
    66x
    66x
    66x
    66x
    66x
    6x
    58x
    58x
    58x
    48x
    48x
    58x
    66x
    66x
    66x
    66x
    66x
    66x
    66x
    66x
    66x
    66x
    58x
    58x
    66x
    66x
    66x
    66x
    66x
    66x
    66x
    66x
    10x
    10x
    48x
    52x
    52x
    52x

    52x
    52x
    52x
    51x
    51x
    51x
    51x
    51x
    51x
    4x
    51x
    51x
    51x
    13x
    51x
    51x
    51x
    51x
    51x
    51x
    51x
    51x
    47x
    47x
    51x
    52x
    48x
    10x
    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
    339x
    339x
    339x
    339x
    339x
    339x
    339x
    339x
    339x
    339x
    339x
    339x
    339x
    71x
    71x
    5x
    5x
    66x
    66x
    66x
    66x
    66x
    66x
    66x
    66x
    66x
    66x
    66x
    339x
    339x
    339x
    339x
     import type { Ref, RefCallback } from "react";
    import { useEffect } from "react";
    import { useEnsuredRef } from "./useEnsuredRef";

    /**
     * @remarks \@since 6.0.0
     */
    export type ResizeObserverEntryCallback = (entry: ResizeObserverEntry) => void;

    /** @internal */
    type Unsubscribe = () => void;

    /** @internal */
    interface TargetSize {
      height: number;
      width: number;
      scrollHeight: number;
      scrollWidth: number;
    }

    /** @internal */
    interface TargetSubscription {
      readonly onUpdate: ResizeObserverEntryCallback;
      readonly disableHeight: boolean;
      readonly disableWidth: boolean;

      size?: TargetSize;
    }

    /** @internal */
    interface SubscribeOptions {
      element: Element;
      onUpdate: ResizeObserverEntryCallback;
      disableHeight: boolean;
      disableWidth: boolean;
    }

    /** @internal */
    export class ResizeObserverManager {
      frame: number;
      subscriptions: Map<Element, Set<TargetSubscription>>;

      /**
       * Why is there a single shared observer instead of multiple and a
       * "subscription" model?
       *
       * Note: Probably a bit of a premature optimization right now...
       *
       * @see https://github.com/WICG/resize-observer/issues/59
       * @internal
       */
      sharedObserver: ResizeObserver | undefined;

      constructor() {
        this.frame = 0;
        this.subscriptions = new Map();
      }

      subscribe = (options: SubscribeOptions): Unsubscribe => {
        const { element, onUpdate, disableHeight, disableWidth } = options;

        // lazy initialize the observer
        const observer =
          this.sharedObserver ||
          new ResizeObserver((entries, observer) => {
            // this prevents the `ResizeObserver loop limit exceeded`
            window.cancelAnimationFrame(this.frame);
            this.frame = window.requestAnimationFrame(() => {
              this.handleResizeEntries(entries, observer);
            });
          });
        this.sharedObserver = observer;

        const updates = this.subscriptions.get(element) || new Set();
        const subscription: TargetSubscription = {
          onUpdate,
          disableHeight,
          disableWidth,
        };
        updates.add(subscription);
        if (!this.subscriptions.has(element)) {
          this.subscriptions.set(element, updates);
        }

        observer.observe(element);

        return () => {
          observer.unobserve(element);
          updates.delete(subscription);
        };
      };

      handleResizeEntries: ResizeObserverCallback = (entries) => {
        for (const entry of entries) {
          const targetSubscriptions = this.subscriptions.get(entry.target);
          // shouldn't really happen
          if (!targetSubscriptions) {
            continue;
          }

          const entries = targetSubscriptions.values();
          for (const subscription of entries) {
            const { height, width } = entry.contentRect;
            const { scrollHeight, scrollWidth } = entry.target;
            const { onUpdate, size, disableHeight, disableWidth } = subscription;
            const isHeightChange =
              !disableHeight &&
              (!size ||
                size.height !== height ||
                size.scrollHeight !== scrollHeight);
            const isWidthChange =
              !disableWidth &&
              (!size || size.width !== width || size.scrollWidth !== scrollWidth);

            subscription.size = {
              height,
              width,
              scrollHeight,
              scrollWidth,
            };
            if (isHeightChange || isWidthChange) {
              onUpdate(entry);
            }
          }
        }
      };
    }

    /**
     * @internal
     */
    export const resizeObserverManager = new ResizeObserverManager();

    /**
     * @remarks
     * \@since 2.3.0
     * \@since 6.0.0 Renamed from `UseResizeObserverOptions` and added
     * `onUpdate`/`disabled` options.
     */
    export interface ResizeObserverHookOptions<E extends HTMLElement> {
      /**
       * 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
       * ResizeObserver each render.**
       *
       * This function will be called whenever the target element resizes.
       *
       * @see {@link useResizeObserver} for an example.
       */
      onUpdate: ResizeObserverEntryCallback;

      /**
       * Set this to `true` to prevent observing the element's size changes. THis is
       * equivalent to not attaching the returned ref to any element.
       *
       * @defaultValue `false`
       */
      disabled?: boolean;

      /**
       * Set this to `true` if the {@link onUpdate} should not be fired for height
       * changes.
       *
       * @defaultValue `false`
       */
      disableHeight?: boolean;

      /**
       * Set this to `true` if the {@link onUpdate} should not be fired for width
       * changes.
       *
       * @defaultValue `false`
       */
      disableWidth?: boolean;
    }

    /**
     * @example
     * Simple Example
     * ```tsx
     * import { useResizeObserver } from "@react-md/core";
     * import type { ReactElement } from "react";
     * import { useState } from "react";
     *
     * interface Size {
     *   height: number;
     *   width: number;
     * }
     *
     * function Example(): ReactElement {
     *   const [{ height, width }, setSize] = useState<Size>({
     *     height: 0,
     *     width: 0,
     *   });
     *   const targetRef = useResizeObserver({
     *     onResize: useCallback((entry) => {
     *       const { height, width } = entry.borderBox;
     *       setSize({ height, width });
     *     }, []),
     *   });
     *
     *   return (
     *     <div ref={targetRef}>
     *       <table>
     *         <tbody>
     *           <tr>
     *             <th scope="col">Height:</th>
     *             <td>{height}</td>
     *           </tr>
     *           <tr>
     *             <th scope="col">Width:</th>
     *             <td>{width}</td>
     *           </tr>
     *         </tbody>
     *       </table>
     *     </div>
     *   );
     * }
     * ```
     *
     * @remarks
     * \@since 2.3.0
     * \@since 6.0.0 The API was updated to match the `useIntersectionObserver`
     * implementation -- accepts only a single object parameter and returns a
     * {@link RefCallback} instead of `[nodeRef, refCallback]`
     */
    export function useResizeObserver<E extends HTMLElement>(
      options: ResizeObserverHookOptions<E>
    ): RefCallback<E> {
      const {
        ref,
        onUpdate,
        disabled,
        disableHeight = false,
        disableWidth = false,
        manager = resizeObserverManager,
      } = options;

      const [targetNodeRef, refCallback] = useEnsuredRef(ref);
      useEffect(() => {
        const element = targetNodeRef.current;
        if (disabled || (disableHeight && disableWidth) || !element) {
          return;
        }

        const unsubscribe = manager.subscribe({
          element,
          onUpdate,
          disableHeight,
          disableWidth,
        });

        return () => {
          unsubscribe();
        };
      }, [disableHeight, disableWidth, disabled, manager, onUpdate, targetNodeRef]);

      return refCallback;
    }