# All files / src useResizeObserver.ts

100% Statements 235/235
100% Branches 29/29
100% Functions 6/6
100% Lines 235/235

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
    2361x
    1x
    1x
    1x
    1x
    1x
    1x
    1x
    1x
    1x
    1x
    1x
    1x
    1x
    1x
    1x
    1x
    1x
    1x
    1x
    1x
    1x
    1x
    1x
    1x
    1x
    1x
    1x
    1x
    1x
    1x
    1x
    1x
    1x
    1x
    1x
    1x
    1x
    1x
    1x
    1x
    1x
    1x
    1x
    1x
    1x
    1x
    1x
    173x
    173x
    173x
    173x
    173x
    173x
    173x
    173x
    173x
    173x
    173x
    173x
    173x
    173x
    173x
    173x
    173x
    173x
    173x
    173x
    90x
    90x
    90x
    90x
    90x
    14x
    72x
    72x
    72x
    47x
    47x
    72x
    90x
    90x
    90x
    90x
    90x
    90x
    90x
    90x
    90x
    90x
    82x
    82x
    90x
    90x
    90x
    90x
    84x
    84x
    84x
    90x
    173x
    173x
    76x
    93x
    93x
    1x
    1x
    1x
    1x
    1x
    1x
    1x
    1x
    1x
    1x
    1x
    1x
    1x
    1x
    1x
    1x
    1x
    1x
    1x
    1x
    1x
    1x
    1x
    1x
    1x
    1x
    1x
    1x
    1x
    1x
    1x
    1x
    1x
    1x
    1x
    1x
    1x
    1x
    1x
    1x
    1x
    1x
    1x
    1x
    1x
    1x
    1x
    1x
    1x
    1x
    1x
    1x
    1x
    1x
    1x
    1x
    1x
    1x
    1x
    1x
    1x
    1x
    1x
    1x
    1x
    1x
    1x
    1x
    1x
    1x
    1x
    1x
    1x
    1x
    1x
    1x
    1x
    1x
    1x
    1x
    1x
    1x
    1x
    1x
    1x
    1x
    1x
    1x
    1x
    1x
    1x
    1x
    1x
    1x
    1x
    1x
    1x
    1x
    1x
    1x
    1x
    1x
    1x
    1x
    1x
    1x
    1x
    1x
    1x
    1x
    1x
    1x
    1x
    1x
    1x
    1x
    1x
    1x
    1x
    1x
    1x
    1x
    1x
    1x
    1x
    1x
    1x
    1x
    1x
    1x
     "use client";
    import { useEffect, type Ref, type RefCallback } from "react";
    import { useEnsuredRef } from "./useEnsuredRef.js";

    // eslint-disable-next-line @typescript-eslint/no-unused-vars
    import { type useElementSize } from "./useElementSize.js";

    /**
     * @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
     * @remarks \@since 6.0.0 This was added to help with testing. The
     * `subscriptions` and `sharedObserver` used to be module-level variables but
     * moving to a class makes it easier to mock. Checkout the
     * `src/tests-utils/ResizeObserver.ts`
     */
    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) => {
            // this prevents the `ResizeObserver loop limit exceeded`
            window.cancelAnimationFrame(this.frame);
            this.frame = window.requestAnimationFrame(() => {
              this.handleResizeEntries(entries);
            });
          });
        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 = (entries: ResizeObserverEntry[]): void => {
        for (const entry of entries) {
          const targetSubscriptions = this.subscriptions.get(entry.target);
          // shouldn't really happen
          /* c8 ignore start */
          if (!targetSubscriptions) {
            continue;
          }
          /* c8 ignore end */

          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
     * @remarks \@since 6.0.0
     */
    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;
    }

    /**
     * The resize observer is used to track the size changes of a specific element.
     * For most cases you can use the {@link useElementSize} instead, but this hook
     * can be used for more complex behavior with the {@link ResizeObserverEntry}.
     *
     * @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,
      } = options;

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

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

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

      return refCallback;
    }