"use strict";

var _interopRequireDefault = require("@babel/runtime/helpers/interopRequireDefault");
Object.defineProperty(exports, "__esModule", {
  value: true
});
exports.default = useCommands;
var _data = require("@wordpress/data");
var _i18n = require("@wordpress/i18n");
var _icons = require("@wordpress/icons");
var _commands = require("@wordpress/commands");
var _preferences = require("@wordpress/preferences");
var _notices = require("@wordpress/notices");
var _blockEditor = require("@wordpress/block-editor");
var _coreData = require("@wordpress/core-data");
var _interface = require("@wordpress/interface");
var _url = require("@wordpress/url");
var _htmlEntities = require("@wordpress/html-entities");
var _lockUnlock = require("../../lock-unlock");
var _store = require("../../store");
var _constants = require("../../store/constants");
var _patternRenameModal = require("../pattern-rename-modal");
var _patternDuplicateModal = require("../pattern-duplicate-modal");
var _isTemplateRevertable = _interopRequireDefault(require("../../store/utils/is-template-revertable"));
/**
 * WordPress dependencies
 */

/**
 * Internal dependencies
 */

const getEditorCommandLoader = () => function useEditorCommandLoader() {
  const {
    editorMode,
    isListViewOpen,
    showBlockBreadcrumbs,
    isDistractionFree,
    isFocusMode,
    isPreviewMode,
    isViewable,
    isCodeEditingEnabled,
    isRichEditingEnabled,
    isPublishSidebarEnabled
  } = (0, _data.useSelect)(select => {
    var _get, _getPostType$viewable;
    const {
      get
    } = select(_preferences.store);
    const {
      isListViewOpened,
      getCurrentPostType,
      getEditorSettings
    } = select(_store.store);
    const {
      getSettings
    } = select(_blockEditor.store);
    const {
      getPostType
    } = select(_coreData.store);
    return {
      editorMode: (_get = get('core', 'editorMode')) !== null && _get !== void 0 ? _get : 'visual',
      isListViewOpen: isListViewOpened(),
      showBlockBreadcrumbs: get('core', 'showBlockBreadcrumbs'),
      isDistractionFree: get('core', 'distractionFree'),
      isFocusMode: get('core', 'focusMode'),
      isPreviewMode: getSettings().isPreviewMode,
      isViewable: (_getPostType$viewable = getPostType(getCurrentPostType())?.viewable) !== null && _getPostType$viewable !== void 0 ? _getPostType$viewable : false,
      isCodeEditingEnabled: getEditorSettings().codeEditingEnabled,
      isRichEditingEnabled: getEditorSettings().richEditingEnabled,
      isPublishSidebarEnabled: select(_store.store).isPublishSidebarEnabled()
    };
  }, []);
  const {
    getActiveComplementaryArea
  } = (0, _data.useSelect)(_interface.store);
  const {
    toggle
  } = (0, _data.useDispatch)(_preferences.store);
  const {
    createInfoNotice
  } = (0, _data.useDispatch)(_notices.store);
  const {
    __unstableSaveForPreview,
    setIsListViewOpened,
    switchEditorMode,
    toggleDistractionFree,
    toggleSpotlightMode,
    toggleTopToolbar
  } = (0, _data.useDispatch)(_store.store);
  const {
    openModal,
    enableComplementaryArea,
    disableComplementaryArea
  } = (0, _data.useDispatch)(_interface.store);
  const {
    getCurrentPostId
  } = (0, _data.useSelect)(_store.store);
  const {
    isBlockBasedTheme,
    canCreateTemplate
  } = (0, _data.useSelect)(select => {
    return {
      isBlockBasedTheme: select(_coreData.store).getCurrentTheme()?.is_block_theme,
      canCreateTemplate: select(_coreData.store).canUser('create', {
        kind: 'postType',
        name: 'wp_template'
      })
    };
  }, []);
  const allowSwitchEditorMode = isCodeEditingEnabled && isRichEditingEnabled;
  if (isPreviewMode) {
    return {
      commands: [],
      isLoading: false
    };
  }
  const commands = [];
  commands.push({
    name: 'core/open-shortcut-help',
    label: (0, _i18n.__)('Keyboard shortcuts'),
    icon: _icons.keyboard,
    callback: ({
      close
    }) => {
      close();
      openModal('editor/keyboard-shortcut-help');
    }
  });
  commands.push({
    name: 'core/toggle-distraction-free',
    label: isDistractionFree ? (0, _i18n.__)('Exit Distraction free') : (0, _i18n.__)('Enter Distraction free'),
    callback: ({
      close
    }) => {
      toggleDistractionFree();
      close();
    }
  });
  commands.push({
    name: 'core/open-preferences',
    label: (0, _i18n.__)('Editor preferences'),
    callback: ({
      close
    }) => {
      close();
      openModal('editor/preferences');
    }
  });
  commands.push({
    name: 'core/toggle-spotlight-mode',
    label: isFocusMode ? (0, _i18n.__)('Exit Spotlight mode') : (0, _i18n.__)('Enter Spotlight mode'),
    callback: ({
      close
    }) => {
      toggleSpotlightMode();
      close();
    }
  });
  commands.push({
    name: 'core/toggle-list-view',
    label: isListViewOpen ? (0, _i18n.__)('Close List View') : (0, _i18n.__)('Open List View'),
    icon: _icons.listView,
    callback: ({
      close
    }) => {
      setIsListViewOpened(!isListViewOpen);
      close();
      createInfoNotice(isListViewOpen ? (0, _i18n.__)('List View off.') : (0, _i18n.__)('List View on.'), {
        id: 'core/editor/toggle-list-view/notice',
        type: 'snackbar'
      });
    }
  });
  commands.push({
    name: 'core/toggle-top-toolbar',
    label: (0, _i18n.__)('Top toolbar'),
    callback: ({
      close
    }) => {
      toggleTopToolbar();
      close();
    }
  });
  if (allowSwitchEditorMode) {
    commands.push({
      name: 'core/toggle-code-editor',
      label: editorMode === 'visual' ? (0, _i18n.__)('Open code editor') : (0, _i18n.__)('Exit code editor'),
      icon: _icons.code,
      callback: ({
        close
      }) => {
        switchEditorMode(editorMode === 'visual' ? 'text' : 'visual');
        close();
      }
    });
  }
  commands.push({
    name: 'core/toggle-breadcrumbs',
    label: showBlockBreadcrumbs ? (0, _i18n.__)('Hide block breadcrumbs') : (0, _i18n.__)('Show block breadcrumbs'),
    callback: ({
      close
    }) => {
      toggle('core', 'showBlockBreadcrumbs');
      close();
      createInfoNotice(showBlockBreadcrumbs ? (0, _i18n.__)('Breadcrumbs hidden.') : (0, _i18n.__)('Breadcrumbs visible.'), {
        id: 'core/editor/toggle-breadcrumbs/notice',
        type: 'snackbar'
      });
    }
  });
  commands.push({
    name: 'core/open-settings-sidebar',
    label: (0, _i18n.__)('Show or hide the Settings panel.'),
    icon: (0, _i18n.isRTL)() ? _icons.drawerLeft : _icons.drawerRight,
    callback: ({
      close
    }) => {
      const activeSidebar = getActiveComplementaryArea('core');
      close();
      if (activeSidebar === 'edit-post/document') {
        disableComplementaryArea('core');
      } else {
        enableComplementaryArea('core', 'edit-post/document');
      }
    }
  });
  commands.push({
    name: 'core/open-block-inspector',
    label: (0, _i18n.__)('Show or hide the Block settings panel'),
    icon: _icons.blockDefault,
    callback: ({
      close
    }) => {
      const activeSidebar = getActiveComplementaryArea('core');
      close();
      if (activeSidebar === 'edit-post/block') {
        disableComplementaryArea('core');
      } else {
        enableComplementaryArea('core', 'edit-post/block');
      }
    }
  });
  commands.push({
    name: 'core/toggle-publish-sidebar',
    label: isPublishSidebarEnabled ? (0, _i18n.__)('Disable pre-publish checks') : (0, _i18n.__)('Enable pre-publish checks'),
    icon: _icons.formatListBullets,
    callback: ({
      close
    }) => {
      close();
      toggle('core', 'isPublishSidebarEnabled');
      createInfoNotice(isPublishSidebarEnabled ? (0, _i18n.__)('Pre-publish checks disabled.') : (0, _i18n.__)('Pre-publish checks enabled.'), {
        id: 'core/editor/publish-sidebar/notice',
        type: 'snackbar'
      });
    }
  });
  if (isViewable) {
    commands.push({
      name: 'core/preview-link',
      label: (0, _i18n.__)('Preview in a new tab'),
      icon: _icons.external,
      callback: async ({
        close
      }) => {
        close();
        const postId = getCurrentPostId();
        const link = await __unstableSaveForPreview();
        window.open(link, `wp-preview-${postId}`);
      }
    });
  }
  if (canCreateTemplate && isBlockBasedTheme) {
    const isSiteEditor = (0, _url.getPath)(window.location.href)?.includes('site-editor.php');
    if (!isSiteEditor) {
      commands.push({
        name: 'core/go-to-site-editor',
        label: (0, _i18n.__)('Open Site Editor'),
        callback: ({
          close
        }) => {
          close();
          document.location = 'site-editor.php';
        }
      });
    }
  }
  return {
    commands,
    isLoading: false
  };
};
const getEditedEntityContextualCommands = () => function useEditedEntityContextualCommands() {
  const {
    postType
  } = (0, _data.useSelect)(select => {
    const {
      getCurrentPostType
    } = select(_store.store);
    return {
      postType: getCurrentPostType()
    };
  }, []);
  const {
    openModal
  } = (0, _data.useDispatch)(_interface.store);
  const commands = [];
  if (postType === _constants.PATTERN_POST_TYPE) {
    commands.push({
      name: 'core/rename-pattern',
      label: (0, _i18n.__)('Rename pattern'),
      icon: _icons.edit,
      callback: ({
        close
      }) => {
        openModal(_patternRenameModal.modalName);
        close();
      }
    });
    commands.push({
      name: 'core/duplicate-pattern',
      label: (0, _i18n.__)('Duplicate pattern'),
      icon: _icons.symbol,
      callback: ({
        close
      }) => {
        openModal(_patternDuplicateModal.modalName);
        close();
      }
    });
  }
  return {
    isLoading: false,
    commands
  };
};
const getPageContentFocusCommands = () => function usePageContentFocusCommands() {
  const {
    onNavigateToEntityRecord,
    goBack,
    templateId,
    isPreviewMode
  } = (0, _data.useSelect)(select => {
    const {
      getRenderingMode,
      getEditorSettings: _getEditorSettings,
      getCurrentTemplateId
    } = (0, _lockUnlock.unlock)(select(_store.store));
    const editorSettings = _getEditorSettings();
    return {
      isTemplateHidden: getRenderingMode() === 'post-only',
      onNavigateToEntityRecord: editorSettings.onNavigateToEntityRecord,
      getEditorSettings: _getEditorSettings,
      goBack: editorSettings.onNavigateToPreviousEntityRecord,
      templateId: getCurrentTemplateId(),
      isPreviewMode: editorSettings.isPreviewMode
    };
  }, []);
  const {
    editedRecord: template,
    hasResolved
  } = (0, _coreData.useEntityRecord)('postType', 'wp_template', templateId);
  if (isPreviewMode) {
    return {
      isLoading: false,
      commands: []
    };
  }
  const commands = [];
  if (templateId && hasResolved) {
    commands.push({
      name: 'core/switch-to-template-focus',
      label: (0, _i18n.sprintf)(/* translators: %s: template title */
      (0, _i18n.__)('Edit template: %s'), (0, _htmlEntities.decodeEntities)(template.title)),
      icon: _icons.layout,
      callback: ({
        close
      }) => {
        onNavigateToEntityRecord({
          postId: templateId,
          postType: 'wp_template'
        });
        close();
      }
    });
  }
  if (!!goBack) {
    commands.push({
      name: 'core/switch-to-previous-entity',
      label: (0, _i18n.__)('Go back'),
      icon: _icons.page,
      callback: ({
        close
      }) => {
        goBack();
        close();
      }
    });
  }
  return {
    isLoading: false,
    commands
  };
};
const getManipulateDocumentCommands = () => function useManipulateDocumentCommands() {
  const {
    postType,
    postId
  } = (0, _data.useSelect)(select => {
    const {
      getCurrentPostId,
      getCurrentPostType
    } = select(_store.store);
    return {
      postType: getCurrentPostType(),
      postId: getCurrentPostId()
    };
  }, []);
  const {
    editedRecord: template,
    hasResolved
  } = (0, _coreData.useEntityRecord)('postType', postType, postId);
  // eslint-disable-next-line @wordpress/no-unused-vars-before-return
  const {
    revertTemplate
  } = (0, _lockUnlock.unlock)((0, _data.useDispatch)(_store.store));
  if (!hasResolved || ![_constants.TEMPLATE_PART_POST_TYPE, _constants.TEMPLATE_POST_TYPE].includes(postType)) {
    return {
      isLoading: true,
      commands: []
    };
  }
  const commands = [];
  if ((0, _isTemplateRevertable.default)(template)) {
    const label = template.type === _constants.TEMPLATE_POST_TYPE ? (0, _i18n.sprintf)(/* translators: %s: template title */
    (0, _i18n.__)('Reset template: %s'), (0, _htmlEntities.decodeEntities)(template.title)) : (0, _i18n.sprintf)(/* translators: %s: template part title */
    (0, _i18n.__)('Reset template part: %s'), (0, _htmlEntities.decodeEntities)(template.title));
    commands.push({
      name: 'core/reset-template',
      label,
      icon: (0, _i18n.isRTL)() ? _icons.rotateRight : _icons.rotateLeft,
      callback: ({
        close
      }) => {
        revertTemplate(template);
        close();
      }
    });
  }
  return {
    isLoading: !hasResolved,
    commands
  };
};
function useCommands() {
  (0, _commands.useCommandLoader)({
    name: 'core/editor/edit-ui',
    hook: getEditorCommandLoader()
  });
  (0, _commands.useCommandLoader)({
    name: 'core/editor/contextual-commands',
    hook: getEditedEntityContextualCommands(),
    context: 'entity-edit'
  });
  (0, _commands.useCommandLoader)({
    name: 'core/editor/page-content-focus',
    hook: getPageContentFocusCommands(),
    context: 'entity-edit'
  });
  (0, _commands.useCommandLoader)({
    name: 'core/edit-site/manipulate-document',
    hook: getManipulateDocumentCommands()
  });
}
//# sourceMappingURL=index.js.map