"use strict";

Object.defineProperty(exports, "__esModule", {
  value: true
});
exports.default = useSyncCanvasModeWithURL;
var _element = require("@wordpress/element");
var _data = require("@wordpress/data");
var _router = require("@wordpress/router");
var _store = require("../../store");
var _lockUnlock = require("../../lock-unlock");
/**
 * WordPress dependencies
 */

/**
 * Internal dependencies
 */

const {
  useLocation,
  useHistory
} = (0, _lockUnlock.unlock)(_router.privateApis);
function useSyncCanvasModeWithURL() {
  const history = useHistory();
  const {
    params
  } = useLocation();
  const canvasMode = (0, _data.useSelect)(select => (0, _lockUnlock.unlock)(select(_store.store)).getCanvasMode(), []);
  const {
    setCanvasMode
  } = (0, _lockUnlock.unlock)((0, _data.useDispatch)(_store.store));
  const currentCanvasModeRef = (0, _element.useRef)(canvasMode);
  const {
    canvas: canvasInUrl
  } = params;
  const currentCanvasInUrlRef = (0, _element.useRef)(canvasInUrl);
  const currentUrlParamsRef = (0, _element.useRef)(params);
  (0, _element.useEffect)(() => {
    currentUrlParamsRef.current = params;
  }, [params]);
  (0, _element.useEffect)(() => {
    currentCanvasModeRef.current = canvasMode;
    if (canvasMode === 'init') {
      return;
    }
    if (canvasMode === 'edit' && currentCanvasInUrlRef.current !== canvasMode) {
      history.push({
        ...currentUrlParamsRef.current,
        canvas: 'edit'
      });
    }
    if (canvasMode === 'view' && currentCanvasInUrlRef.current !== undefined) {
      history.push({
        ...currentUrlParamsRef.current,
        canvas: undefined
      });
    }
  }, [canvasMode, history]);
  (0, _element.useEffect)(() => {
    currentCanvasInUrlRef.current = canvasInUrl;
    if (canvasInUrl !== 'edit' && currentCanvasModeRef.current !== 'view') {
      setCanvasMode('view');
    } else if (canvasInUrl === 'edit' && currentCanvasModeRef.current !== 'edit') {
      setCanvasMode('edit');
    }
  }, [canvasInUrl, setCanvasMode]);
}
//# sourceMappingURL=use-sync-canvas-mode-with-url.js.map