"use client";
import * as ReactDOM from "react-dom";
import { useAnimationFrame } from "../../../utils/esm/useAnimationFrame.js";
import { useStableCallback } from "../../../utils/esm/useStableCallback.js";
import { resolveRef } from "./resolveRef.js";
function useAnimationsFinished(elementOrRef, waitForNextTick = false, treatAbortedAsFinished = true) {
  const frame = useAnimationFrame();
  return useStableCallback((fnToExecute, signal = null) => {
    frame.cancel();
    const element = resolveRef(elementOrRef);
    if (element == null) {
      return;
    }
    if (typeof element.getAnimations !== "function" || globalThis.BASE_UI_ANIMATIONS_DISABLED) {
      fnToExecute();
    } else {
      frame.request(() => {
        function exec() {
          if (!element) {
            return;
          }
          Promise.all(element.getAnimations().map((anim) => anim.finished)).then(() => {
            if (signal != null && signal.aborted) {
              return;
            }
            ReactDOM.flushSync(fnToExecute);
          }).catch(() => {
            if (treatAbortedAsFinished) {
              if (signal != null && signal.aborted) {
                return;
              }
              ReactDOM.flushSync(fnToExecute);
            } else if (element.getAnimations().length > 0 && element.getAnimations().some((anim) => anim.pending || anim.playState !== "finished")) {
              exec();
            }
          });
        }
        if (waitForNextTick) {
          frame.request(exec);
        } else {
          exec();
        }
      });
    }
  });
}
export {
  useAnimationsFinished
};
//# sourceMappingURL=useAnimationsFinished.js.map
