import {Directive, ElementRef, EventEmitter, Output} from '@angular/core';
import {ResizeSensor} from 'css-element-queries';
import {Subject} from 'rxjs';
import {debounceTime} from 'rxjs/operators';

@Directive({
  selector: '[appResize]'
})
export class ResizeDirective {
  @Output()
  resize = new EventEmitter();
  debounce = new Subject();

  constructor(private el: ElementRef) {
    this.debounce
      .pipe(debounceTime(100))
      .subscribe(rect => {
        this.resize.emit(rect);
      });

    const sensor = new ResizeSensor(this.el.nativeElement, (event) => {
      const {clientWidth, clientHeight} = this.el.nativeElement;
      this.debounce.next({clientWidth, clientHeight});
    });
  }

}
