import _defineProperty from "@babel/runtime/helpers/defineProperty";
export let ShadowKeys = /*#__PURE__*/function (ShadowKeys) {
  ShadowKeys["SHOW_LEFT_SHADOW"] = "showLeftShadow";
  ShadowKeys["SHOW_RIGHT_SHADOW"] = "showRightShadow";
  return ShadowKeys;
}({});
export const shadowObserverClassNames = {
  SENTINEL_LEFT: 'sentinel-left',
  SENTINEL_RIGHT: 'sentinel-right',
  SHADOW_CONTAINER: 'with-shadow-observer'
};
const requestIdleCallback = fn => {
  return window.requestIdleCallback ? window.requestIdleCallback(fn) : window.requestAnimationFrame(fn);
};
const cancelIdleCallback = id => {
  return window.cancelIdleCallback ? window.cancelIdleCallback(id) : window.cancelAnimationFrame(id);
};
export class ShadowObserver {
  constructor({
    scrollContainer,
    onUpdateShadows
  }) {
    _defineProperty(this, "sentinels", {});
    _defineProperty(this, "shadowStates", {
      [ShadowKeys.SHOW_LEFT_SHADOW]: false,
      [ShadowKeys.SHOW_RIGHT_SHADOW]: false
    });
    _defineProperty(this, "init", () => {
      if (!this.scrollContainer || this.intersectionObserver) {
        return;
      }
      this.sentinels.right = document.createElement('div');
      this.sentinels.right.classList.add(shadowObserverClassNames.SENTINEL_RIGHT);
      this.scrollContainer.appendChild(this.sentinels.right);
      this.sentinels.left = document.createElement('div');
      this.sentinels.left.classList.add(shadowObserverClassNames.SENTINEL_LEFT);
      this.scrollContainer.prepend(this.sentinels.left);
      this.intersectionObserver = new IntersectionObserver((entries, _) => {
        entries.forEach(this.onIntersect);
      }, {
        root: this.scrollContainer,
        rootMargin: '1px'
      });
      this.intersectionObserver.observe(this.sentinels.left);
      this.intersectionObserver.observe(this.sentinels.right);
    });
    _defineProperty(this, "onIntersect", entry => {
      this.requestCallbackId = requestIdleCallback(() => {
        if (entry.target.classList.contains(shadowObserverClassNames.SENTINEL_LEFT)) {
          this.shadowStates[ShadowKeys.SHOW_LEFT_SHADOW] = !entry.isIntersecting;
        }
        if (entry.target.classList.contains(shadowObserverClassNames.SENTINEL_RIGHT)) {
          this.shadowStates[ShadowKeys.SHOW_RIGHT_SHADOW] = !entry.isIntersecting;
        }
        this.onUpdateShadows(this.shadowStates);
      });
    });
    this.scrollContainer = scrollContainer;
    this.onUpdateShadows = onUpdateShadows;
    this.init();
  }
  dispose() {
    if (this.intersectionObserver) {
      this.intersectionObserver.disconnect();
      this.intersectionObserver = undefined;
      this.requestCallbackId && cancelIdleCallback(this.requestCallbackId);
    }
  }
}