import { addResizeObserver, FiltersMap } from '@wix/bex-core'; import { action, makeObservable } from 'mobx'; import { ToolbarCollectionState } from '../../state'; import { ToolbarResponsiveState } from '../../state/Toolbar/ToolbarResponsiveState'; export class ToolbarState { readonly toolbar; readonly responsive; constructor(toolbar: ToolbarCollectionState) { this.toolbar = toolbar; this.responsive = new ToolbarResponsiveState({ toolbar: this, }); makeObservable(this, { init: action, }); } _subscribeResizeOrMoved({ scrollElement, }: { readonly scrollElement?: HTMLElement | null; }) { 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 }: { scrollElement?: HTMLElement | null }) { const { toolbar, responsive } = this; const disposers = [ toolbar.toolbarRect.init({ scrollElement }), this._subscribeResizeOrMoved({ scrollElement }), responsive.init(), ]; return () => { disposers.forEach((d) => d?.()); }; } }