import { resolver } from "@rocicorp/resolver";
function getDocumentVisibilityWatcher(doc, hiddenIntervalMS, signal) {
  return doc ? new DocumentVisibilityWatcherImpl(doc, hiddenIntervalMS, signal) : new DocumentVisibilityWatcherNoDoc();
}
class DocumentVisibilityWatcherImpl {
  #doc;
  #hiddenIntervalMS;
  #timeoutID = 0;
  // This trails doc.visibilityState by hiddenIntervalMS when being hidden. This
  // is because we want to wait for the tab to be hidden for a while before
  // considering as hidden.
  visibilityState;
  #promises = /* @__PURE__ */ new Set();
  constructor(doc, hiddenIntervalMS, signal) {
    this.#doc = doc;
    this.#hiddenIntervalMS = hiddenIntervalMS;
    this.visibilityState = doc.visibilityState;
    this.#doc.addEventListener("visibilitychange", this.#onVisibilityChange, {
      signal
    });
  }
  #onVisibilityChange = () => {
    if (this.#doc.visibilityState === "visible") {
      clearTimeout(this.#timeoutID);
      this.#setVisibilityState("visible");
    } else {
      this.#timeoutID = setTimeout(() => {
        this.#setVisibilityState("hidden");
      }, this.#hiddenIntervalMS);
    }
  };
  #setVisibilityState(visibilityState) {
    if (visibilityState === this.visibilityState) {
      return;
    }
    this.visibilityState = visibilityState;
    for (const entry of this.#promises) {
      const { resolve, state } = entry;
      if (state === visibilityState) {
        resolve();
        this.#promises.delete(entry);
      }
    }
  }
  waitForVisible() {
    return this.#waitFor("visible");
  }
  waitForHidden() {
    return this.#waitFor("hidden");
  }
  #waitFor(state) {
    if (this.visibilityState === state) {
      return Promise.resolve();
    }
    const { promise, resolve } = resolver();
    this.#promises.add({ resolve, state });
    return promise;
  }
}
const resolvedPromise = Promise.resolve();
const promiseThatNeverResolves = new Promise(() => void 0);
class DocumentVisibilityWatcherNoDoc {
  visibilityState = "visible";
  waitForVisible() {
    return resolvedPromise;
  }
  waitForHidden() {
    return promiseThatNeverResolves;
  }
}
export {
  getDocumentVisibilityWatcher
};
//# sourceMappingURL=document-visible.js.map
