// packages/block-editor/src/components/link-control/use-create-page.js
import { __ } from "@wordpress/i18n";
import { useEffect, useState, useRef } from "@wordpress/element";
function useCreatePage(handleCreatePage) {
  const cancelableCreateSuggestion = useRef();
  const [isCreatingPage, setIsCreatingPage] = useState(false);
  const [errorMessage, setErrorMessage] = useState(null);
  const createPage = async function(suggestionTitle) {
    setIsCreatingPage(true);
    setErrorMessage(null);
    try {
      cancelableCreateSuggestion.current = makeCancelable(
        // Using Promise.resolve to allow createSuggestion to return a
        // non-Promise based value.
        Promise.resolve(handleCreatePage(suggestionTitle))
      );
      return await cancelableCreateSuggestion.current.promise;
    } catch (error) {
      if (error && error.isCanceled) {
        return;
      }
      setErrorMessage(
        error.message || __(
          "An unknown error occurred during creation. Please try again."
        )
      );
      throw error;
    } finally {
      setIsCreatingPage(false);
    }
  };
  useEffect(() => {
    return () => {
      if (cancelableCreateSuggestion.current) {
        cancelableCreateSuggestion.current.cancel();
      }
    };
  }, []);
  return {
    createPage,
    isCreatingPage,
    errorMessage
  };
}
var makeCancelable = (promise) => {
  let hasCanceled_ = false;
  const wrappedPromise = new Promise((resolve, reject) => {
    promise.then(
      (val) => hasCanceled_ ? reject({ isCanceled: true }) : resolve(val),
      (error) => hasCanceled_ ? reject({ isCanceled: true }) : reject(error)
    );
  });
  return {
    promise: wrappedPromise,
    cancel() {
      hasCanceled_ = true;
    }
  };
};
export {
  useCreatePage as default
};
//# sourceMappingURL=use-create-page.js.map
