import { debounce } from './utils';
const transitionKeys = ['top', 'right', 'bottom', 'left', 'width', 'height'];
export class ResizeController {
    constructor(element, cb, wait) {
        this.element = element;
        this.cb = cb;
        this.supported = typeof ResizeObserver !== 'undefined';
        this.onTransitionEnd = this.onTransitionEnd.bind(this);
        if (debounce) {
            this.cb = debounce(this.cb, wait);
        }
    }
    connect() {
        if (this.supported) {
            this.resizeObserver = new ResizeObserver(() => {
                this.cb();
            });
            this.resizeObserver.observe(this.element);
        }
        else {
            window.addEventListener('resize', this.cb);
            document.addEventListener('transitionend', this.onTransitionEnd);
        }
    }
    disconnect() {
        if (!this.supported) {
            window.removeEventListener('resize', this.cb);
            document.removeEventListener('transitionend', this.onTransitionEnd);
        }
        if (this.resizeObserver) {
            this.resizeObserver.disconnect();
            this.resizeObserver = undefined;
        }
    }
    onDidRender() {
        if (!this.supported) {
            this.cb();
        }
    }
    onTransitionEnd({ propertyName }) {
        if (transitionKeys.includes(propertyName)) {
            this.cb();
        }
    }
}
