// packages/block-editor/src/components/link-control/use-rich-url-data.js
import { store as blockEditorStore } from "../../store";
import { useSelect } from "@wordpress/data";
import { useEffect, useReducer } from "@wordpress/element";
function reducer(state, action) {
  switch (action.type) {
    case "RESOLVED":
      return {
        ...state,
        isFetching: false,
        richData: action.richData
      };
    case "ERROR":
      return {
        ...state,
        isFetching: false,
        richData: null
      };
    case "LOADING":
      return {
        ...state,
        isFetching: true
      };
    default:
      throw new Error(`Unexpected action type ${action.type}`);
  }
}
function useRemoteUrlData(url) {
  const [state, dispatch] = useReducer(reducer, {
    richData: null,
    isFetching: false
  });
  const { fetchRichUrlData } = useSelect((select) => {
    const { getSettings } = select(blockEditorStore);
    return {
      fetchRichUrlData: getSettings().__experimentalFetchRichUrlData
    };
  }, []);
  useEffect(() => {
    if (url?.length && fetchRichUrlData && typeof AbortController !== "undefined") {
      dispatch({
        type: "LOADING"
      });
      const controller = new window.AbortController();
      const signal = controller.signal;
      fetchRichUrlData(url, {
        signal
      }).then((urlData) => {
        dispatch({
          type: "RESOLVED",
          richData: urlData
        });
      }).catch(() => {
        if (!signal.aborted) {
          dispatch({
            type: "ERROR"
          });
        }
      });
      return () => {
        controller.abort();
      };
    }
  }, [url]);
  return state;
}
var use_rich_url_data_default = useRemoteUrlData;
export {
  use_rich_url_data_default as default
};
//# sourceMappingURL=use-rich-url-data.js.map
