All files / resize-observer resize-observer.service.ts

95.77% Statements 68/71
86.36% Branches 19/22
100% Functions 21/21
95.45% Lines 63/66

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                                                                                    1x 352x   352x 352x     352x 352x     352x 348x                                 705x 705x 644x 644x     705x 686x             686x 686x                 686x 686x 528x     686x 680x         447x 447x 447x   447x   289x 289x   447x   447x       552x 552x       584x       584x 2x   582x 501x   582x       1694x 1694x           830x   864x 864x                   1763x 582x     1763x 1763x 438x 438x 438x 438x 438x       1763x       447x 447x 155x 69x 69x           438x 438x 1694x 572x   1694x                   204x      
/**
 * Copyright (c) Siemens 2016 - 2025
 * SPDX-License-Identifier: MIT
 */
import { isPlatformBrowser } from '@angular/common';
import { inject, Injectable, NgZone, PLATFORM_ID } from '@angular/core';
import { Observable, Subscriber } from 'rxjs';
 
export interface ElementDimensions {
  width: number;
  height: number;
}
 
interface ResizeSubscriber {
  sub: Subscriber<ElementDimensions>;
  dim?: ElementDimensions;
  throttle: number;
  blocked: boolean;
  emitImmediate?: boolean;
}
 
interface Listener {
  element: Element;
  subscribers: ResizeSubscriber[];
}
 
interface QueueEntry {
  element: Element;
  subscriber: ResizeSubscriber;
  unblock: boolean;
  force: boolean;
}
 
/**
 * A service wrapping `ResizeObserver`. This is a service for those reasons:
 * - only one `ResizeObserver` should be used for performance reason.
 * - For Angular change detection to work, explicit `ngZone` calls are necessary
 * - Observable stream
 */
@Injectable({
  providedIn: 'root'
})
export class ResizeObserverService {
  private listeners = new Map<Element, Listener>();
  private resizeObserver?: ResizeObserver;
  private timerQueue = new Map<number, QueueEntry[]>();
  private zone = inject(NgZone);
 
  constructor() {
    const isBrowser = isPlatformBrowser(inject(PLATFORM_ID));
    Iif (!isBrowser || !ResizeObserver) {
      return;
    }
    this.resizeObserver = new ResizeObserver((entries: ResizeObserverEntry[]) =>
      entries.forEach(entry => this.handleElement(entry.target))
    );
  }
 
  /**
   * Observe the size of an element. Returns an observable with the changes.
   * @param element - The element to observe
   * @param throttle - Throttle time in ms. Will emit this time after the resize
   * @param emitInitial - Emit the initial size after subscribe?
   * @param emitImmediate - Emit an event immediately after the size changes. Useful e.g. for visibility checks.
   */
  observe(
    element: Element,
    throttle: number,
    emitInitial?: boolean,
    emitImmediate?: boolean
  ): Observable<ElementDimensions> {
    let entry = this.listeners.get(element);
    if (!entry) {
      entry = { element, subscribers: [] };
      this.listeners.set(element, entry);
    }
 
    return new Observable<ElementDimensions>(subscriber => {
      const sub: ResizeSubscriber = {
        sub: subscriber,
        dim: undefined,
        throttle,
        blocked: false,
        emitImmediate
      };
      this.subscriberAdded(entry!, sub, emitInitial);
      return () => this.subscriberRemoved(entry!, sub);
    });
  }
 
  private subscriberAdded(
    entry: Listener,
    subscriber: ResizeSubscriber,
    emitInitial?: boolean
  ): void {
    entry.subscribers.push(subscriber);
    if (entry.subscribers.length === 1) {
      this.resizeObserver?.observe(entry.element);
    }
 
    if (emitInitial) {
      this.schedule(0, entry.element, subscriber, false, true);
    }
  }
 
  private subscriberRemoved(entry: Listener, subscriber: ResizeSubscriber): void {
    const index = entry.subscribers.indexOf(subscriber);
    if (index >= 0) {
      entry.subscribers.splice(index, 1);
    }
    if (entry.subscribers.length === 0) {
      // no more subscribers, tear down everything
      this.resizeObserver?.unobserve(entry.element);
      this.listeners.delete(entry.element);
    }
    this.unschedule(subscriber);
    // close down, no re-subscription possible
    subscriber.sub.complete();
  }
 
  private handleElement(element: Element): void {
    const entry = this.listeners.get(element);
    Iif (!entry) {
      this.resizeObserver?.unobserve(element);
      return;
    }
    entry.subscribers.forEach(sub => this.handleResizeSubscriber(element, sub));
  }
 
  private handleResizeSubscriber(element: Element, entry: ResizeSubscriber): void {
    if (entry.blocked) {
      return;
    }
    if (entry.emitImmediate) {
      this.schedule(0, element, entry, false);
    }
    this.schedule(entry.throttle, element, entry, true);
  }
 
  private emitSize(element: Element, entry: ResizeSubscriber, force = false): void {
    const dimensions = { width: element.clientWidth, height: element.clientHeight };
    if (
      !force &&
      entry.dim?.width === dimensions.width &&
      entry.dim?.height === dimensions.height
    ) {
      // Prevent spurious emissions. Subpixels and all..
      return;
    }
    entry.dim = dimensions;
    entry.sub.next(dimensions);
  }
 
  private schedule(
    timeout: number,
    element: Element,
    subscriber: ResizeSubscriber,
    unblock: boolean,
    force = false
  ): void {
    if (unblock) {
      subscriber.blocked = true;
    }
 
    let queue = this.timerQueue.get(timeout);
    if (!queue) {
      queue = [];
      this.timerQueue.set(timeout, queue);
      setTimeout(() => {
        this.timerQueue.delete(timeout);
        this.processQueue(queue!);
      }, timeout);
    }
 
    queue.push({ element, subscriber, unblock, force });
  }
 
  private unschedule(entry: ResizeSubscriber): void {
    const queued = this.timerQueue.get(entry.throttle);
    if (queued) {
      const index = queued.findIndex(q => q.subscriber === entry);
      if (index > -1) {
        queued.splice(index, 1);
      }
    }
  }
 
  private processQueue(queue: QueueEntry[]): void {
    this.zone.run(() => {
      queue?.forEach(q => {
        if (q.unblock) {
          q.subscriber.blocked = false;
        }
        this.emitSize(q.element, q.subscriber, q.force);
      });
    });
  }
 
  /**
   * check size on all observed elements. Only use in testing!
   */
  // eslint-disable-next-line @typescript-eslint/naming-convention
  _checkAll(): void {
    this.listeners.forEach(entry => this.handleElement(entry.element));
  }
}