"use strict";

var _interopRequireDefault = require("@babel/runtime/helpers/interopRequireDefault");
Object.defineProperty(exports, "__esModule", {
  value: true
});
exports.default = EditSiteEditor;
var _clsx = _interopRequireDefault(require("clsx"));
var _data = require("@wordpress/data");
var _components = require("@wordpress/components");
var _compose = require("@wordpress/compose");
var _editor = require("@wordpress/editor");
var _i18n = require("@wordpress/i18n");
var _coreData = require("@wordpress/core-data");
var _blockLibrary = require("@wordpress/block-library");
var _element = require("@wordpress/element");
var _notices = require("@wordpress/notices");
var _router = require("@wordpress/router");
var _htmlEntities = require("@wordpress/html-entities");
var _icons = require("@wordpress/icons");
var _blockEditor = require("@wordpress/block-editor");
var _welcomeGuide = _interopRequireDefault(require("../welcome-guide"));
var _store = require("../../store");
var _globalStylesRenderer = require("../global-styles-renderer");
var _canvasLoader = _interopRequireDefault(require("../canvas-loader"));
var _lockUnlock = require("../../lock-unlock");
var _useSiteEditorSettings = require("../block-editor/use-site-editor-settings");
var _pluginTemplateSettingPanel = _interopRequireDefault(require("../plugin-template-setting-panel"));
var _globalStylesSidebar = _interopRequireDefault(require("../global-styles-sidebar"));
var _isPreviewingTheme2 = require("../../utils/is-previewing-theme");
var _editorCanvasContainer = require("../editor-canvas-container");
var _saveButton = _interopRequireDefault(require("../save-button"));
var _savePanel = _interopRequireDefault(require("../save-panel"));
var _moreMenu = _interopRequireDefault(require("../more-menu"));
var _siteIcon = _interopRequireDefault(require("../site-icon"));
var _useEditorIframeProps = _interopRequireDefault(require("../block-editor/use-editor-iframe-props"));
var _useEditorTitle = _interopRequireDefault(require("./use-editor-title"));
var _hooks = require("../layout/hooks");
var _useAdaptEditorToCanvas = require("./use-adapt-editor-to-canvas");
var _constants = require("../../utils/constants");
var _useResolveEditedEntity = require("./use-resolve-edited-entity");
var _url = require("@wordpress/url");
var _jsxRuntime = require("react/jsx-runtime");
/**
 * External dependencies
 */

/**
 * WordPress dependencies
 */

/**
 * Internal dependencies
 */

const {
  Editor,
  BackButton
} = (0, _lockUnlock.unlock)(_editor.privateApis);
const {
  useHistory,
  useLocation
} = (0, _lockUnlock.unlock)(_router.privateApis);
const {
  BlockKeyboardShortcuts
} = (0, _lockUnlock.unlock)(_blockLibrary.privateApis);
const toggleHomeIconVariants = {
  edit: {
    opacity: 0,
    scale: 0.2
  },
  hover: {
    opacity: 1,
    scale: 1,
    clipPath: 'inset( 22% round 2px )'
  }
};
const siteIconVariants = {
  edit: {
    clipPath: 'inset(0% round 0px)'
  },
  hover: {
    clipPath: 'inset( 22% round 2px )'
  },
  tap: {
    clipPath: 'inset(0% round 0px)'
  }
};
function getListPathForPostType(postType) {
  switch (postType) {
    case 'navigation':
      return '/navigation';
    case 'wp_block':
      return '/pattern?postType=wp_block';
    case 'wp_template_part':
      return '/pattern?postType=wp_template_part';
    case 'wp_template':
      return '/template';
    case 'page':
      return '/page';
    case 'post':
      return '/';
  }
  throw 'Unknown post type';
}
function getNavigationPath(location, postType) {
  const {
    path,
    name
  } = location;
  if (['pattern-item', 'template-part-item', 'page-item', 'template-item', 'post-item'].includes(name)) {
    return getListPathForPostType(postType);
  }
  return (0, _url.addQueryArgs)(path, {
    canvas: undefined
  });
}
function EditSiteEditor({
  isPostsList = false
}) {
  const disableMotion = (0, _compose.useReducedMotion)();
  const location = useLocation();
  const {
    canvas = 'view'
  } = location.query;
  const isLoading = (0, _hooks.useIsSiteEditorLoading)();
  (0, _useAdaptEditorToCanvas.useAdaptEditorToCanvas)(canvas);
  const entity = (0, _useResolveEditedEntity.useResolveEditedEntity)();
  // deprecated sync state with url
  (0, _useResolveEditedEntity.useSyncDeprecatedEntityIntoState)(entity);
  const {
    postType,
    postId,
    context
  } = entity;
  const {
    supportsGlobalStyles,
    editorCanvasView,
    currentPostIsTrashed,
    hasSiteIcon
  } = (0, _data.useSelect)(select => {
    const {
      getEditorCanvasContainerView
    } = (0, _lockUnlock.unlock)(select(_store.store));
    const {
      getCurrentTheme,
      getEntityRecord
    } = select(_coreData.store);
    const siteData = getEntityRecord('root', '__unstableBase', undefined);
    return {
      supportsGlobalStyles: getCurrentTheme()?.is_block_theme,
      editorCanvasView: getEditorCanvasContainerView(),
      currentPostIsTrashed: select(_editor.store).getCurrentPostAttribute('status') === 'trash',
      hasSiteIcon: !!siteData?.site_icon_url
    };
  }, []);
  const postWithTemplate = !!context?.postId;
  (0, _useEditorTitle.default)(postWithTemplate ? context.postType : postType, postWithTemplate ? context.postId : postId);
  const _isPreviewingTheme = (0, _isPreviewingTheme2.isPreviewingTheme)();
  const hasDefaultEditorCanvasView = !(0, _editorCanvasContainer.useHasEditorCanvasContainer)();
  const iframeProps = (0, _useEditorIframeProps.default)();
  const isEditMode = canvas === 'edit';
  const loadingProgressId = (0, _compose.useInstanceId)(_canvasLoader.default, 'edit-site-editor__loading-progress');
  const settings = (0, _useSiteEditorSettings.useSpecificEditorSettings)();
  const styles = (0, _element.useMemo)(() => [...settings.styles, {
    // Forming a "block formatting context" to prevent margin collapsing.
    // @see https://developer.mozilla.org/en-US/docs/Web/Guide/CSS/Block_formatting_context
    css: canvas === 'view' ? `body{min-height: 100vh; ${currentPostIsTrashed ? '' : 'cursor: pointer;'}}` : undefined
  }], [settings.styles, canvas, currentPostIsTrashed]);
  const {
    resetZoomLevel
  } = (0, _lockUnlock.unlock)((0, _data.useDispatch)(_blockEditor.store));
  const {
    createSuccessNotice
  } = (0, _data.useDispatch)(_notices.store);
  const history = useHistory();
  const onActionPerformed = (0, _element.useCallback)((actionId, items) => {
    switch (actionId) {
      case 'move-to-trash':
      case 'delete-post':
        {
          history.navigate(getListPathForPostType(postWithTemplate ? context.postType : postType));
        }
        break;
      case 'duplicate-post':
        {
          const newItem = items[0];
          const _title = typeof newItem.title === 'string' ? newItem.title : newItem.title?.rendered;
          createSuccessNotice((0, _i18n.sprintf)(
          // translators: %s: Title of the created post or template, e.g: "Hello world".
          (0, _i18n.__)('"%s" successfully created.'), (0, _htmlEntities.decodeEntities)(_title)), {
            type: 'snackbar',
            id: 'duplicate-post-action',
            actions: [{
              label: (0, _i18n.__)('Edit'),
              onClick: () => {
                history.navigate(`/${newItem.type}/${newItem.id}?canvas=edit`);
              }
            }]
          });
        }
        break;
    }
  }, [postType, context?.postType, postWithTemplate, history, createSuccessNotice]);

  // Replace the title and icon displayed in the DocumentBar when there's an overlay visible.
  const title = (0, _editorCanvasContainer.getEditorCanvasContainerTitle)(editorCanvasView);
  const isReady = !isLoading;
  const transition = {
    duration: disableMotion ? 0 : 0.2
  };
  return /*#__PURE__*/(0, _jsxRuntime.jsxs)(_jsxRuntime.Fragment, {
    children: [/*#__PURE__*/(0, _jsxRuntime.jsx)(_globalStylesRenderer.GlobalStylesRenderer, {
      disableRootPadding: postType !== _constants.TEMPLATE_POST_TYPE
    }), /*#__PURE__*/(0, _jsxRuntime.jsx)(_editor.EditorKeyboardShortcutsRegister, {}), isEditMode && /*#__PURE__*/(0, _jsxRuntime.jsx)(BlockKeyboardShortcuts, {}), !isReady ? /*#__PURE__*/(0, _jsxRuntime.jsx)(_canvasLoader.default, {
      id: loadingProgressId
    }) : null, isEditMode && /*#__PURE__*/(0, _jsxRuntime.jsx)(_welcomeGuide.default, {
      postType: postWithTemplate ? context.postType : postType
    }), isReady && /*#__PURE__*/(0, _jsxRuntime.jsxs)(Editor, {
      postType: postWithTemplate ? context.postType : postType,
      postId: postWithTemplate ? context.postId : postId,
      templateId: postWithTemplate ? postId : undefined,
      settings: settings,
      className: "edit-site-editor__editor-interface",
      styles: styles,
      customSaveButton: _isPreviewingTheme && /*#__PURE__*/(0, _jsxRuntime.jsx)(_saveButton.default, {
        size: "compact"
      }),
      customSavePanel: _isPreviewingTheme && /*#__PURE__*/(0, _jsxRuntime.jsx)(_savePanel.default, {}),
      forceDisableBlockTools: !hasDefaultEditorCanvasView,
      title: title,
      iframeProps: iframeProps,
      onActionPerformed: onActionPerformed,
      extraSidebarPanels: !postWithTemplate && /*#__PURE__*/(0, _jsxRuntime.jsx)(_pluginTemplateSettingPanel.default.Slot, {}),
      children: [isEditMode && /*#__PURE__*/(0, _jsxRuntime.jsx)(BackButton, {
        children: ({
          length
        }) => length <= 1 && /*#__PURE__*/(0, _jsxRuntime.jsxs)(_components.__unstableMotion.div, {
          className: "edit-site-editor__view-mode-toggle",
          transition: transition,
          animate: "edit",
          initial: "edit",
          whileHover: "hover",
          whileTap: "tap",
          children: [/*#__PURE__*/(0, _jsxRuntime.jsx)(_components.Button, {
            __next40pxDefaultSize: true,
            label: (0, _i18n.__)('Open Navigation'),
            showTooltip: true,
            tooltipPosition: "middle right",
            onClick: () => {
              resetZoomLevel();

              // TODO: this is a temporary solution to navigate to the posts list if we are
              // come here through `posts list` and are in focus mode editing a template, template part etc..
              if (isPostsList && location.query?.focusMode) {
                history.navigate('/', {
                  transition: 'canvas-mode-view-transition'
                });
              } else {
                history.navigate(getNavigationPath(location, postWithTemplate ? context.postType : postType), {
                  transition: 'canvas-mode-view-transition'
                });
              }
            },
            children: /*#__PURE__*/(0, _jsxRuntime.jsx)(_components.__unstableMotion.div, {
              variants: siteIconVariants,
              children: /*#__PURE__*/(0, _jsxRuntime.jsx)(_siteIcon.default, {
                className: "edit-site-editor__view-mode-toggle-icon"
              })
            })
          }), /*#__PURE__*/(0, _jsxRuntime.jsx)(_components.__unstableMotion.div, {
            className: (0, _clsx.default)('edit-site-editor__back-icon', {
              'has-site-icon': hasSiteIcon
            }),
            variants: toggleHomeIconVariants,
            children: /*#__PURE__*/(0, _jsxRuntime.jsx)(_icons.Icon, {
              icon: _icons.arrowUpLeft
            })
          })]
        })
      }), /*#__PURE__*/(0, _jsxRuntime.jsx)(_moreMenu.default, {}), supportsGlobalStyles && /*#__PURE__*/(0, _jsxRuntime.jsx)(_globalStylesSidebar.default, {})]
    })]
  });
}
//# sourceMappingURL=index.js.map