"use strict";

var _interopRequireDefault = require("@babel/runtime/helpers/interopRequireDefault");
Object.defineProperty(exports, "__esModule", {
  value: true
});
exports.__experimentalTearDownEditor = __experimentalTearDownEditor;
exports.clearSelectedBlock = exports.autosave = exports.__unstableSaveForPreview = void 0;
exports.closePublishSidebar = closePublishSidebar;
exports.createUndoLevel = createUndoLevel;
exports.insertDefaultBlock = exports.insertBlocks = exports.insertBlock = exports.hideInsertionPoint = exports.exitFormattedText = exports.enterFormattedText = exports.enablePublishSidebar = exports.editPost = exports.disablePublishSidebar = void 0;
exports.lockPostAutosaving = lockPostAutosaving;
exports.lockPostSaving = lockPostSaving;
exports.multiSelect = exports.moveBlocksUp = exports.moveBlocksDown = exports.moveBlockToPosition = exports.mergeBlocks = void 0;
exports.openPublishSidebar = openPublishSidebar;
exports.redo = exports.receiveBlocks = void 0;
exports.refreshPost = refreshPost;
exports.removeBlocks = exports.removeBlock = void 0;
exports.removeEditorPanel = removeEditorPanel;
exports.resetEditorBlocks = exports.resetBlocks = exports.replaceBlocks = exports.replaceBlock = void 0;
exports.resetPost = resetPost;
exports.selectBlock = exports.savePost = void 0;
exports.setDeviceType = setDeviceType;
exports.setEditedPost = setEditedPost;
exports.setIsInserterOpened = void 0;
exports.setIsListViewOpened = setIsListViewOpened;
exports.setupEditor = exports.setTemplateValidity = exports.setRenderingMode = void 0;
exports.setupEditorState = setupEditorState;
exports.toggleEditorPanelOpened = exports.toggleEditorPanelEnabled = exports.toggleDistractionFree = exports.toggleBlockMode = exports.synchronizeTemplate = exports.switchEditorMode = exports.stopTyping = exports.stopMultiSelect = exports.startTyping = exports.startMultiSelect = exports.showInsertionPoint = void 0;
exports.togglePublishSidebar = togglePublishSidebar;
exports.undo = exports.trashPost = exports.toggleTopToolbar = exports.toggleSpotlightMode = exports.toggleSelection = void 0;
exports.unlockPostAutosaving = unlockPostAutosaving;
exports.unlockPostSaving = unlockPostSaving;
exports.updateBlockListSettings = exports.updateBlockAttributes = exports.updateBlock = void 0;
exports.updateEditorSettings = updateEditorSettings;
exports.updatePost = updatePost;
exports.updatePostLock = updatePostLock;
var _a11y = require("@wordpress/a11y");
var _apiFetch = _interopRequireDefault(require("@wordpress/api-fetch"));
var _deprecated = _interopRequireDefault(require("@wordpress/deprecated"));
var _blocks = require("@wordpress/blocks");
var _notices = require("@wordpress/notices");
var _coreData = require("@wordpress/core-data");
var _blockEditor = require("@wordpress/block-editor");
var _hooks = require("@wordpress/hooks");
var _preferences = require("@wordpress/preferences");
var _i18n = require("@wordpress/i18n");
var _localAutosave = require("./local-autosave");
var _noticeBuilder = require("./utils/notice-builder");
var _lockUnlock = require("../lock-unlock");
/**
 * WordPress dependencies
 */

/**
 * Internal dependencies
 */

/**
 * Returns an action generator used in signalling that editor has initialized with
 * the specified post object and editor settings.
 *
 * @param {Object} post       Post object.
 * @param {Object} edits      Initial edited attributes object.
 * @param {Array}  [template] Block Template.
 */
const setupEditor = (post, edits, template) => ({
  dispatch
}) => {
  dispatch.setEditedPost(post.type, post.id);
  // Apply a template for new posts only, if exists.
  const isNewPost = post.status === 'auto-draft';
  if (isNewPost && template) {
    // In order to ensure maximum of a single parse during setup, edits are
    // included as part of editor setup action. Assume edited content as
    // canonical if provided, falling back to post.
    let content;
    if ('content' in edits) {
      content = edits.content;
    } else {
      content = post.content.raw;
    }
    let blocks = (0, _blocks.parse)(content);
    blocks = (0, _blocks.synchronizeBlocksWithTemplate)(blocks, template);
    dispatch.resetEditorBlocks(blocks, {
      __unstableShouldCreateUndoLevel: false
    });
  }
  if (edits && Object.values(edits).some(([key, edit]) => {
    var _post$key$raw;
    return edit !== ((_post$key$raw = post[key]?.raw) !== null && _post$key$raw !== void 0 ? _post$key$raw : post[key]);
  })) {
    dispatch.editPost(edits);
  }
};

/**
 * Returns an action object signalling that the editor is being destroyed and
 * that any necessary state or side-effect cleanup should occur.
 *
 * @deprecated
 *
 * @return {Object} Action object.
 */
exports.setupEditor = setupEditor;
function __experimentalTearDownEditor() {
  (0, _deprecated.default)("wp.data.dispatch( 'core/editor' ).__experimentalTearDownEditor", {
    since: '6.5'
  });
  return {
    type: 'DO_NOTHING'
  };
}

/**
 * Returns an action object used in signalling that the latest version of the
 * post has been received, either by initialization or save.
 *
 * @deprecated Since WordPress 6.0.
 */
function resetPost() {
  (0, _deprecated.default)("wp.data.dispatch( 'core/editor' ).resetPost", {
    since: '6.0',
    version: '6.3',
    alternative: 'Initialize the editor with the setupEditorState action'
  });
  return {
    type: 'DO_NOTHING'
  };
}

/**
 * Returns an action object used in signalling that a patch of updates for the
 * latest version of the post have been received.
 *
 * @return {Object} Action object.
 * @deprecated since Gutenberg 9.7.0.
 */
function updatePost() {
  (0, _deprecated.default)("wp.data.dispatch( 'core/editor' ).updatePost", {
    since: '5.7',
    alternative: 'Use the core entities store instead'
  });
  return {
    type: 'DO_NOTHING'
  };
}

/**
 * Setup the editor state.
 *
 * @deprecated
 *
 * @param {Object} post Post object.
 */
function setupEditorState(post) {
  (0, _deprecated.default)("wp.data.dispatch( 'core/editor' ).setupEditorState", {
    since: '6.5',
    alternative: "wp.data.dispatch( 'core/editor' ).setEditedPost"
  });
  return setEditedPost(post.type, post.id);
}

/**
 * Returns an action that sets the current post Type and post ID.
 *
 * @param {string} postType Post Type.
 * @param {string} postId   Post ID.
 *
 * @return {Object} Action object.
 */
function setEditedPost(postType, postId) {
  return {
    type: 'SET_EDITED_POST',
    postType,
    postId
  };
}

/**
 * Returns an action object used in signalling that attributes of the post have
 * been edited.
 *
 * @param {Object} edits     Post attributes to edit.
 * @param {Object} [options] Options for the edit.
 *
 * @example
 * ```js
 * // Update the post title
 * wp.data.dispatch( 'core/editor' ).editPost( { title: `${ newTitle }` } );
 * ```
 *
 * @return {Object} Action object
 */
const editPost = (edits, options) => ({
  select,
  registry
}) => {
  const {
    id,
    type
  } = select.getCurrentPost();
  registry.dispatch(_coreData.store).editEntityRecord('postType', type, id, edits, options);
};

/**
 * Action for saving the current post in the editor.
 *
 * @param {Object} [options]
 */
exports.editPost = editPost;
const savePost = (options = {}) => async ({
  select,
  dispatch,
  registry
}) => {
  if (!select.isEditedPostSaveable()) {
    return;
  }
  const content = select.getEditedPostContent();
  if (!options.isAutosave) {
    dispatch.editPost({
      content
    }, {
      undoIgnore: true
    });
  }
  const previousRecord = select.getCurrentPost();
  let edits = {
    id: previousRecord.id,
    ...registry.select(_coreData.store).getEntityRecordNonTransientEdits('postType', previousRecord.type, previousRecord.id),
    content
  };
  dispatch({
    type: 'REQUEST_POST_UPDATE_START',
    options
  });
  let error = false;
  try {
    edits = await (0, _hooks.applyFiltersAsync)('editor.preSavePost', edits, options);
  } catch (err) {
    error = err;
  }
  if (!error) {
    try {
      await registry.dispatch(_coreData.store).saveEntityRecord('postType', previousRecord.type, edits, options);
    } catch (err) {
      error = err.message && err.code !== 'unknown_error' ? err.message : (0, _i18n.__)('An error occurred while updating.');
    }
  }
  if (!error) {
    error = registry.select(_coreData.store).getLastEntitySaveError('postType', previousRecord.type, previousRecord.id);
  }

  // Run the hook with legacy unstable name for backward compatibility
  if (!error) {
    try {
      await (0, _hooks.applyFilters)('editor.__unstableSavePost', Promise.resolve(), options);
    } catch (err) {
      error = err;
    }
  }
  if (!error) {
    try {
      await (0, _hooks.doActionAsync)('editor.savePost', {
        id: previousRecord.id
      }, options);
    } catch (err) {
      error = err;
    }
  }
  dispatch({
    type: 'REQUEST_POST_UPDATE_FINISH',
    options
  });
  if (error) {
    const args = (0, _noticeBuilder.getNotificationArgumentsForSaveFail)({
      post: previousRecord,
      edits,
      error
    });
    if (args.length) {
      registry.dispatch(_notices.store).createErrorNotice(...args);
    }
  } else {
    const updatedRecord = select.getCurrentPost();
    const args = (0, _noticeBuilder.getNotificationArgumentsForSaveSuccess)({
      previousPost: previousRecord,
      post: updatedRecord,
      postType: await registry.resolveSelect(_coreData.store).getPostType(updatedRecord.type),
      options
    });
    if (args.length) {
      registry.dispatch(_notices.store).createSuccessNotice(...args);
    }
    // Make sure that any edits after saving create an undo level and are
    // considered for change detection.
    if (!options.isAutosave) {
      registry.dispatch(_blockEditor.store).__unstableMarkLastChangeAsPersistent();
    }
  }
};

/**
 * Action for refreshing the current post.
 *
 * @deprecated Since WordPress 6.0.
 */
exports.savePost = savePost;
function refreshPost() {
  (0, _deprecated.default)("wp.data.dispatch( 'core/editor' ).refreshPost", {
    since: '6.0',
    version: '6.3',
    alternative: 'Use the core entities store instead'
  });
  return {
    type: 'DO_NOTHING'
  };
}

/**
 * Action for trashing the current post in the editor.
 */
const trashPost = () => async ({
  select,
  dispatch,
  registry
}) => {
  const postTypeSlug = select.getCurrentPostType();
  const postType = await registry.resolveSelect(_coreData.store).getPostType(postTypeSlug);
  const {
    rest_base: restBase,
    rest_namespace: restNamespace = 'wp/v2'
  } = postType;
  dispatch({
    type: 'REQUEST_POST_DELETE_START'
  });
  try {
    const post = select.getCurrentPost();
    await (0, _apiFetch.default)({
      path: `/${restNamespace}/${restBase}/${post.id}`,
      method: 'DELETE'
    });
    await dispatch.savePost();
  } catch (error) {
    registry.dispatch(_notices.store).createErrorNotice(...(0, _noticeBuilder.getNotificationArgumentsForTrashFail)({
      error
    }));
  }
  dispatch({
    type: 'REQUEST_POST_DELETE_FINISH'
  });
};

/**
 * Action that autosaves the current post.  This
 * includes server-side autosaving (default) and client-side (a.k.a. local)
 * autosaving (e.g. on the Web, the post might be committed to Session
 * Storage).
 *
 * @param {Object}  [options]       Extra flags to identify the autosave.
 * @param {boolean} [options.local] Whether to perform a local autosave.
 */
exports.trashPost = trashPost;
const autosave = ({
  local = false,
  ...options
} = {}) => async ({
  select,
  dispatch
}) => {
  const post = select.getCurrentPost();

  // Currently template autosaving is not supported.
  if (post.type === 'wp_template') {
    return;
  }
  if (local) {
    const isPostNew = select.isEditedPostNew();
    const title = select.getEditedPostAttribute('title');
    const content = select.getEditedPostAttribute('content');
    const excerpt = select.getEditedPostAttribute('excerpt');
    (0, _localAutosave.localAutosaveSet)(post.id, isPostNew, title, content, excerpt);
  } else {
    await dispatch.savePost({
      isAutosave: true,
      ...options
    });
  }
};
exports.autosave = autosave;
const __unstableSaveForPreview = ({
  forceIsAutosaveable
} = {}) => async ({
  select,
  dispatch
}) => {
  if ((forceIsAutosaveable || select.isEditedPostAutosaveable()) && !select.isPostLocked()) {
    const isDraft = ['draft', 'auto-draft'].includes(select.getEditedPostAttribute('status'));
    if (isDraft) {
      await dispatch.savePost({
        isPreview: true
      });
    } else {
      await dispatch.autosave({
        isPreview: true
      });
    }
  }
  return select.getEditedPostPreviewLink();
};

/**
 * Action that restores last popped state in undo history.
 */
exports.__unstableSaveForPreview = __unstableSaveForPreview;
const redo = () => ({
  registry
}) => {
  registry.dispatch(_coreData.store).redo();
};

/**
 * Action that pops a record from undo history and undoes the edit.
 */
exports.redo = redo;
const undo = () => ({
  registry
}) => {
  registry.dispatch(_coreData.store).undo();
};

/**
 * Action that creates an undo history record.
 *
 * @deprecated Since WordPress 6.0
 */
exports.undo = undo;
function createUndoLevel() {
  (0, _deprecated.default)("wp.data.dispatch( 'core/editor' ).createUndoLevel", {
    since: '6.0',
    version: '6.3',
    alternative: 'Use the core entities store instead'
  });
  return {
    type: 'DO_NOTHING'
  };
}

/**
 * Action that locks the editor.
 *
 * @param {Object} lock Details about the post lock status, user, and nonce.
 * @return {Object} Action object.
 */
function updatePostLock(lock) {
  return {
    type: 'UPDATE_POST_LOCK',
    lock
  };
}

/**
 * Enable the publish sidebar.
 */
const enablePublishSidebar = () => ({
  registry
}) => {
  registry.dispatch(_preferences.store).set('core', 'isPublishSidebarEnabled', true);
};

/**
 * Disables the publish sidebar.
 */
exports.enablePublishSidebar = enablePublishSidebar;
const disablePublishSidebar = () => ({
  registry
}) => {
  registry.dispatch(_preferences.store).set('core', 'isPublishSidebarEnabled', false);
};

/**
 * Action that locks post saving.
 *
 * @param {string} lockName The lock name.
 *
 * @example
 * ```
 * const { subscribe } = wp.data;
 *
 * const initialPostStatus = wp.data.select( 'core/editor' ).getEditedPostAttribute( 'status' );
 *
 * // Only allow publishing posts that are set to a future date.
 * if ( 'publish' !== initialPostStatus ) {
 *
 * 	// Track locking.
 * 	let locked = false;
 *
 * 	// Watch for the publish event.
 * 	let unssubscribe = subscribe( () => {
 * 		const currentPostStatus = wp.data.select( 'core/editor' ).getEditedPostAttribute( 'status' );
 * 		if ( 'publish' !== currentPostStatus ) {
 *
 * 			// Compare the post date to the current date, lock the post if the date isn't in the future.
 * 			const postDate = new Date( wp.data.select( 'core/editor' ).getEditedPostAttribute( 'date' ) );
 * 			const currentDate = new Date();
 * 			if ( postDate.getTime() <= currentDate.getTime() ) {
 * 				if ( ! locked ) {
 * 					locked = true;
 * 					wp.data.dispatch( 'core/editor' ).lockPostSaving( 'futurelock' );
 * 				}
 * 			} else {
 * 				if ( locked ) {
 * 					locked = false;
 * 					wp.data.dispatch( 'core/editor' ).unlockPostSaving( 'futurelock' );
 * 				}
 * 			}
 * 		}
 * 	} );
 * }
 * ```
 *
 * @return {Object} Action object
 */
exports.disablePublishSidebar = disablePublishSidebar;
function lockPostSaving(lockName) {
  return {
    type: 'LOCK_POST_SAVING',
    lockName
  };
}

/**
 * Action that unlocks post saving.
 *
 * @param {string} lockName The lock name.
 *
 * @example
 * ```
 * // Unlock post saving with the lock key `mylock`:
 * wp.data.dispatch( 'core/editor' ).unlockPostSaving( 'mylock' );
 * ```
 *
 * @return {Object} Action object
 */
function unlockPostSaving(lockName) {
  return {
    type: 'UNLOCK_POST_SAVING',
    lockName
  };
}

/**
 * Action that locks post autosaving.
 *
 * @param {string} lockName The lock name.
 *
 * @example
 * ```
 * // Lock post autosaving with the lock key `mylock`:
 * wp.data.dispatch( 'core/editor' ).lockPostAutosaving( 'mylock' );
 * ```
 *
 * @return {Object} Action object
 */
function lockPostAutosaving(lockName) {
  return {
    type: 'LOCK_POST_AUTOSAVING',
    lockName
  };
}

/**
 * Action that unlocks post autosaving.
 *
 * @param {string} lockName The lock name.
 *
 * @example
 * ```
 * // Unlock post saving with the lock key `mylock`:
 * wp.data.dispatch( 'core/editor' ).unlockPostAutosaving( 'mylock' );
 * ```
 *
 * @return {Object} Action object
 */
function unlockPostAutosaving(lockName) {
  return {
    type: 'UNLOCK_POST_AUTOSAVING',
    lockName
  };
}

/**
 * Returns an action object used to signal that the blocks have been updated.
 *
 * @param {Array}  blocks    Block Array.
 * @param {Object} [options] Optional options.
 */
const resetEditorBlocks = (blocks, options = {}) => ({
  select,
  dispatch,
  registry
}) => {
  const {
    __unstableShouldCreateUndoLevel,
    selection
  } = options;
  const edits = {
    blocks,
    selection
  };
  if (__unstableShouldCreateUndoLevel !== false) {
    const {
      id,
      type
    } = select.getCurrentPost();
    const noChange = registry.select(_coreData.store).getEditedEntityRecord('postType', type, id).blocks === edits.blocks;
    if (noChange) {
      registry.dispatch(_coreData.store).__unstableCreateUndoLevel('postType', type, id);
      return;
    }

    // We create a new function here on every persistent edit
    // to make sure the edit makes the post dirty and creates
    // a new undo level.
    edits.content = ({
      blocks: blocksForSerialization = []
    }) => (0, _blocks.__unstableSerializeAndClean)(blocksForSerialization);
  }
  dispatch.editPost(edits);
};

/*
 * Returns an action object used in signalling that the post editor settings have been updated.
 *
 * @param {Object} settings Updated settings
 *
 * @return {Object} Action object
 */
exports.resetEditorBlocks = resetEditorBlocks;
function updateEditorSettings(settings) {
  return {
    type: 'UPDATE_EDITOR_SETTINGS',
    settings
  };
}

/**
 * Returns an action used to set the rendering mode of the post editor. We support multiple rendering modes:
 *
 * -   `post-only`: This mode extracts the post blocks from the template and renders only those. The idea is to allow the user to edit the post/page in isolation without the wrapping template.
 * -   `template-locked`: This mode renders both the template and the post blocks but the template blocks are locked and can't be edited. The post blocks are editable.
 *
 * @param {string} mode Mode (one of 'post-only' or 'template-locked').
 */
const setRenderingMode = mode => ({
  dispatch,
  registry,
  select
}) => {
  if (select.__unstableIsEditorReady()) {
    // We clear the block selection but we also need to clear the selection from the core store.
    registry.dispatch(_blockEditor.store).clearSelectedBlock();
    dispatch.editPost({
      selection: undefined
    }, {
      undoIgnore: true
    });
  }
  dispatch({
    type: 'SET_RENDERING_MODE',
    mode
  });
};

/**
 * Action that changes the width of the editing canvas.
 *
 * @param {string} deviceType
 *
 * @return {Object} Action object.
 */
exports.setRenderingMode = setRenderingMode;
function setDeviceType(deviceType) {
  return {
    type: 'SET_DEVICE_TYPE',
    deviceType
  };
}

/**
 * Returns an action object used to enable or disable a panel in the editor.
 *
 * @param {string} panelName A string that identifies the panel to enable or disable.
 *
 * @return {Object} Action object.
 */
const toggleEditorPanelEnabled = panelName => ({
  registry
}) => {
  var _registry$select$get;
  const inactivePanels = (_registry$select$get = registry.select(_preferences.store).get('core', 'inactivePanels')) !== null && _registry$select$get !== void 0 ? _registry$select$get : [];
  const isPanelInactive = !!inactivePanels?.includes(panelName);

  // If the panel is inactive, remove it to enable it, else add it to
  // make it inactive.
  let updatedInactivePanels;
  if (isPanelInactive) {
    updatedInactivePanels = inactivePanels.filter(invactivePanelName => invactivePanelName !== panelName);
  } else {
    updatedInactivePanels = [...inactivePanels, panelName];
  }
  registry.dispatch(_preferences.store).set('core', 'inactivePanels', updatedInactivePanels);
};

/**
 * Opens a closed panel and closes an open panel.
 *
 * @param {string} panelName A string that identifies the panel to open or close.
 */
exports.toggleEditorPanelEnabled = toggleEditorPanelEnabled;
const toggleEditorPanelOpened = panelName => ({
  registry
}) => {
  var _registry$select$get2;
  const openPanels = (_registry$select$get2 = registry.select(_preferences.store).get('core', 'openPanels')) !== null && _registry$select$get2 !== void 0 ? _registry$select$get2 : [];
  const isPanelOpen = !!openPanels?.includes(panelName);

  // If the panel is open, remove it to close it, else add it to
  // make it open.
  let updatedOpenPanels;
  if (isPanelOpen) {
    updatedOpenPanels = openPanels.filter(openPanelName => openPanelName !== panelName);
  } else {
    updatedOpenPanels = [...openPanels, panelName];
  }
  registry.dispatch(_preferences.store).set('core', 'openPanels', updatedOpenPanels);
};

/**
 * Returns an action object used to remove a panel from the editor.
 *
 * @param {string} panelName A string that identifies the panel to remove.
 *
 * @return {Object} Action object.
 */
exports.toggleEditorPanelOpened = toggleEditorPanelOpened;
function removeEditorPanel(panelName) {
  return {
    type: 'REMOVE_PANEL',
    panelName
  };
}

/**
 * Returns an action object used to open/close the inserter.
 *
 * @param {boolean|Object} value                Whether the inserter should be
 *                                              opened (true) or closed (false).
 *                                              To specify an insertion point,
 *                                              use an object.
 * @param {string}         value.rootClientId   The root client ID to insert at.
 * @param {number}         value.insertionIndex The index to insert at.
 * @param {string}         value.filterValue    A query to filter the inserter results.
 * @param {Function}       value.onSelect       A callback when an item is selected.
 * @param {string}         value.tab            The tab to open in the inserter.
 * @param {string}         value.category       The category to initialize in the inserter.
 *
 * @return {Object} Action object.
 */
const setIsInserterOpened = value => ({
  dispatch,
  registry
}) => {
  if (typeof value === 'object' && value.hasOwnProperty('rootClientId') && value.hasOwnProperty('insertionIndex')) {
    (0, _lockUnlock.unlock)(registry.dispatch(_blockEditor.store)).setInsertionPoint({
      rootClientId: value.rootClientId,
      index: value.insertionIndex
    });
  }
  dispatch({
    type: 'SET_IS_INSERTER_OPENED',
    value
  });
};

/**
 * Returns an action object used to open/close the list view.
 *
 * @param {boolean} isOpen A boolean representing whether the list view should be opened or closed.
 * @return {Object} Action object.
 */
exports.setIsInserterOpened = setIsInserterOpened;
function setIsListViewOpened(isOpen) {
  return {
    type: 'SET_IS_LIST_VIEW_OPENED',
    isOpen
  };
}

/**
 * Action that toggles Distraction free mode.
 * Distraction free mode expects there are no sidebars, as due to the
 * z-index values set, you can't close sidebars.
 *
 * @param {Object}  [options={}]                Optional configuration object
 * @param {boolean} [options.createNotice=true] Whether to create a notice
 */
const toggleDistractionFree = ({
  createNotice = true
} = {}) => ({
  dispatch,
  registry
}) => {
  const isDistractionFree = registry.select(_preferences.store).get('core', 'distractionFree');
  if (isDistractionFree) {
    registry.dispatch(_preferences.store).set('core', 'fixedToolbar', false);
  }
  if (!isDistractionFree) {
    registry.batch(() => {
      registry.dispatch(_preferences.store).set('core', 'fixedToolbar', true);
      dispatch.setIsInserterOpened(false);
      dispatch.setIsListViewOpened(false);
      (0, _lockUnlock.unlock)(registry.dispatch(_blockEditor.store)).resetZoomLevel();
    });
  }
  registry.batch(() => {
    registry.dispatch(_preferences.store).set('core', 'distractionFree', !isDistractionFree);
    if (createNotice) {
      registry.dispatch(_notices.store).createInfoNotice(isDistractionFree ? (0, _i18n.__)('Distraction free mode deactivated.') : (0, _i18n.__)('Distraction free mode activated.'), {
        id: 'core/editor/distraction-free-mode/notice',
        type: 'snackbar',
        actions: [{
          label: (0, _i18n.__)('Undo'),
          onClick: () => {
            registry.batch(() => {
              registry.dispatch(_preferences.store).set('core', 'fixedToolbar', isDistractionFree);
              registry.dispatch(_preferences.store).toggle('core', 'distractionFree');
            });
          }
        }]
      });
    }
  });
};

/**
 * Action that toggles the Spotlight Mode view option.
 */
exports.toggleDistractionFree = toggleDistractionFree;
const toggleSpotlightMode = () => ({
  registry
}) => {
  registry.dispatch(_preferences.store).toggle('core', 'focusMode');
  const isFocusMode = registry.select(_preferences.store).get('core', 'focusMode');
  registry.dispatch(_notices.store).createInfoNotice(isFocusMode ? (0, _i18n.__)('Spotlight mode activated.') : (0, _i18n.__)('Spotlight mode deactivated.'), {
    id: 'core/editor/toggle-spotlight-mode/notice',
    type: 'snackbar',
    actions: [{
      label: (0, _i18n.__)('Undo'),
      onClick: () => {
        registry.dispatch(_preferences.store).toggle('core', 'focusMode');
      }
    }]
  });
};

/**
 * Action that toggles the Top Toolbar view option.
 */
exports.toggleSpotlightMode = toggleSpotlightMode;
const toggleTopToolbar = () => ({
  registry
}) => {
  registry.dispatch(_preferences.store).toggle('core', 'fixedToolbar');
  const isTopToolbar = registry.select(_preferences.store).get('core', 'fixedToolbar');
  registry.dispatch(_notices.store).createInfoNotice(isTopToolbar ? (0, _i18n.__)('Top toolbar activated.') : (0, _i18n.__)('Top toolbar deactivated.'), {
    id: 'core/editor/toggle-top-toolbar/notice',
    type: 'snackbar',
    actions: [{
      label: (0, _i18n.__)('Undo'),
      onClick: () => {
        registry.dispatch(_preferences.store).toggle('core', 'fixedToolbar');
      }
    }]
  });
};

/**
 * Triggers an action used to switch editor mode.
 *
 * @param {string} mode The editor mode.
 */
exports.toggleTopToolbar = toggleTopToolbar;
const switchEditorMode = mode => ({
  dispatch,
  registry
}) => {
  registry.dispatch(_preferences.store).set('core', 'editorMode', mode);
  if (mode !== 'visual') {
    // Unselect blocks when we switch to a non visual mode.
    registry.dispatch(_blockEditor.store).clearSelectedBlock();
    // Exit zoom out state when switching to a non visual mode.
    (0, _lockUnlock.unlock)(registry.dispatch(_blockEditor.store)).resetZoomLevel();
  }
  if (mode === 'visual') {
    (0, _a11y.speak)((0, _i18n.__)('Visual editor selected'), 'assertive');
  } else if (mode === 'text') {
    const isDistractionFree = registry.select(_preferences.store).get('core', 'distractionFree');
    if (isDistractionFree) {
      dispatch.toggleDistractionFree();
    }
    (0, _a11y.speak)((0, _i18n.__)('Code editor selected'), 'assertive');
  }
};

/**
 * Returns an action object used in signalling that the user opened the publish
 * sidebar.
 *
 * @return {Object} Action object
 */
exports.switchEditorMode = switchEditorMode;
function openPublishSidebar() {
  return {
    type: 'OPEN_PUBLISH_SIDEBAR'
  };
}

/**
 * Returns an action object used in signalling that the user closed the
 * publish sidebar.
 *
 * @return {Object} Action object.
 */
function closePublishSidebar() {
  return {
    type: 'CLOSE_PUBLISH_SIDEBAR'
  };
}

/**
 * Returns an action object used in signalling that the user toggles the publish sidebar.
 *
 * @return {Object} Action object
 */
function togglePublishSidebar() {
  return {
    type: 'TOGGLE_PUBLISH_SIDEBAR'
  };
}

/**
 * Backward compatibility
 */

const getBlockEditorAction = name => (...args) => ({
  registry
}) => {
  (0, _deprecated.default)("`wp.data.dispatch( 'core/editor' )." + name + '`', {
    since: '5.3',
    alternative: "`wp.data.dispatch( 'core/block-editor' )." + name + '`',
    version: '6.2'
  });
  registry.dispatch(_blockEditor.store)[name](...args);
};

/**
 * @see resetBlocks in core/block-editor store.
 */
const resetBlocks = exports.resetBlocks = getBlockEditorAction('resetBlocks');

/**
 * @see receiveBlocks in core/block-editor store.
 */
const receiveBlocks = exports.receiveBlocks = getBlockEditorAction('receiveBlocks');

/**
 * @see updateBlock in core/block-editor store.
 */
const updateBlock = exports.updateBlock = getBlockEditorAction('updateBlock');

/**
 * @see updateBlockAttributes in core/block-editor store.
 */
const updateBlockAttributes = exports.updateBlockAttributes = getBlockEditorAction('updateBlockAttributes');

/**
 * @see selectBlock in core/block-editor store.
 */
const selectBlock = exports.selectBlock = getBlockEditorAction('selectBlock');

/**
 * @see startMultiSelect in core/block-editor store.
 */
const startMultiSelect = exports.startMultiSelect = getBlockEditorAction('startMultiSelect');

/**
 * @see stopMultiSelect in core/block-editor store.
 */
const stopMultiSelect = exports.stopMultiSelect = getBlockEditorAction('stopMultiSelect');

/**
 * @see multiSelect in core/block-editor store.
 */
const multiSelect = exports.multiSelect = getBlockEditorAction('multiSelect');

/**
 * @see clearSelectedBlock in core/block-editor store.
 */
const clearSelectedBlock = exports.clearSelectedBlock = getBlockEditorAction('clearSelectedBlock');

/**
 * @see toggleSelection in core/block-editor store.
 */
const toggleSelection = exports.toggleSelection = getBlockEditorAction('toggleSelection');

/**
 * @see replaceBlocks in core/block-editor store.
 */
const replaceBlocks = exports.replaceBlocks = getBlockEditorAction('replaceBlocks');

/**
 * @see replaceBlock in core/block-editor store.
 */
const replaceBlock = exports.replaceBlock = getBlockEditorAction('replaceBlock');

/**
 * @see moveBlocksDown in core/block-editor store.
 */
const moveBlocksDown = exports.moveBlocksDown = getBlockEditorAction('moveBlocksDown');

/**
 * @see moveBlocksUp in core/block-editor store.
 */
const moveBlocksUp = exports.moveBlocksUp = getBlockEditorAction('moveBlocksUp');

/**
 * @see moveBlockToPosition in core/block-editor store.
 */
const moveBlockToPosition = exports.moveBlockToPosition = getBlockEditorAction('moveBlockToPosition');

/**
 * @see insertBlock in core/block-editor store.
 */
const insertBlock = exports.insertBlock = getBlockEditorAction('insertBlock');

/**
 * @see insertBlocks in core/block-editor store.
 */
const insertBlocks = exports.insertBlocks = getBlockEditorAction('insertBlocks');

/**
 * @see showInsertionPoint in core/block-editor store.
 */
const showInsertionPoint = exports.showInsertionPoint = getBlockEditorAction('showInsertionPoint');

/**
 * @see hideInsertionPoint in core/block-editor store.
 */
const hideInsertionPoint = exports.hideInsertionPoint = getBlockEditorAction('hideInsertionPoint');

/**
 * @see setTemplateValidity in core/block-editor store.
 */
const setTemplateValidity = exports.setTemplateValidity = getBlockEditorAction('setTemplateValidity');

/**
 * @see synchronizeTemplate in core/block-editor store.
 */
const synchronizeTemplate = exports.synchronizeTemplate = getBlockEditorAction('synchronizeTemplate');

/**
 * @see mergeBlocks in core/block-editor store.
 */
const mergeBlocks = exports.mergeBlocks = getBlockEditorAction('mergeBlocks');

/**
 * @see removeBlocks in core/block-editor store.
 */
const removeBlocks = exports.removeBlocks = getBlockEditorAction('removeBlocks');

/**
 * @see removeBlock in core/block-editor store.
 */
const removeBlock = exports.removeBlock = getBlockEditorAction('removeBlock');

/**
 * @see toggleBlockMode in core/block-editor store.
 */
const toggleBlockMode = exports.toggleBlockMode = getBlockEditorAction('toggleBlockMode');

/**
 * @see startTyping in core/block-editor store.
 */
const startTyping = exports.startTyping = getBlockEditorAction('startTyping');

/**
 * @see stopTyping in core/block-editor store.
 */
const stopTyping = exports.stopTyping = getBlockEditorAction('stopTyping');

/**
 * @see enterFormattedText in core/block-editor store.
 */
const enterFormattedText = exports.enterFormattedText = getBlockEditorAction('enterFormattedText');

/**
 * @see exitFormattedText in core/block-editor store.
 */
const exitFormattedText = exports.exitFormattedText = getBlockEditorAction('exitFormattedText');

/**
 * @see insertDefaultBlock in core/block-editor store.
 */
const insertDefaultBlock = exports.insertDefaultBlock = getBlockEditorAction('insertDefaultBlock');

/**
 * @see updateBlockListSettings in core/block-editor store.
 */
const updateBlockListSettings = exports.updateBlockListSettings = getBlockEditorAction('updateBlockListSettings');
//# sourceMappingURL=actions.js.map