import { action, makeObservable, observable } from 'mobx';

export class ResizeObserverState {
  contentRect: {
    height: number;
  } | null = null;

  constructor() {
    makeObservable(this, {
      contentRect: observable.ref,
    });
  }

  init({ target }: { target?: Element | null }) {
    if (target == null || typeof ResizeObserver === 'undefined') {
      return;
    }

    const resizeObserver = new ResizeObserver(
      action(([{ contentRect }]) => {
        this.contentRect = {
          height: contentRect.height,
        };
      }),
    );

    resizeObserver.observe(target);

    return () => {
      resizeObserver.disconnect();
    };
  }
}
