import { addResizeObserver } from '@wix/bex-core';
import { action, makeObservable } from 'mobx';
import { ToolbarResponsiveState } from '../../state/Toolbar/ToolbarResponsiveState';
export class ToolbarState {
    constructor(toolbar) {
        this.toolbar = toolbar;
        this.responsive = new ToolbarResponsiveState({
            toolbar: this,
        });
        makeObservable(this, {
            init: action,
        });
    }
    _subscribeResizeOrMoved({ scrollElement, }) {
        const { toolbar: table } = this;
        if (scrollElement == null) {
            return;
        }
        const onResizedOrMoved = action(function onResizedOrMoved() {
            const scrollElementRect = scrollElement.getBoundingClientRect();
            table.scrollElementRect.height = scrollElementRect.height;
            table.scrollElementRect.top = scrollElementRect.top;
        });
        const onResizedOrMovedThrottled = table.container.lodash.throttle(() => window.requestAnimationFrame(onResizedOrMoved), 300);
        const onScroll = () => {
            onResizedOrMovedThrottled();
        };
        scrollElement.addEventListener('scroll', onScroll);
        const dispose = addResizeObserver(scrollElement, onResizedOrMovedThrottled);
        const onResizedOrMovedAnimationFrame = window.requestAnimationFrame(() => {
            window.requestAnimationFrame(onResizedOrMoved);
        });
        return () => {
            dispose?.();
            window.cancelAnimationFrame(onResizedOrMovedAnimationFrame);
            scrollElement.removeEventListener('scroll', onScroll);
        };
    }
    init({ scrollElement }) {
        const { toolbar, responsive } = this;
        const disposers = [
            toolbar.toolbarRect.init({ scrollElement }),
            this._subscribeResizeOrMoved({ scrollElement }),
            responsive.init(),
        ];
        return () => {
            disposers.forEach((d) => d?.());
        };
    }
}
//# sourceMappingURL=ToolbarState.js.map