import { editorCommandToPMCommand } from '../editor-commands';
import { scheduleDocumentRequest } from './requestDocument';
/**
 * Core plugin that is always included in the preset.
 * Allows for executing `EditorCommand` and other core functionality.
 */
export const corePlugin = ({
  config
}) => {
  return {
    name: 'core',
    actions: {
      execute: command => {
        const editorView = config === null || config === void 0 ? void 0 : config.getEditorView();
        if (!editorView || !command) {
          return false;
        }
        const {
          state,
          dispatch
        } = editorView;
        return editorCommandToPMCommand(command)(state, dispatch);
      },
      // Code copied from `EditorActions.focus()`
      focus: () => {
        const editorView = config === null || config === void 0 ? void 0 : config.getEditorView();
        if (!editorView || editorView.hasFocus()) {
          return false;
        }
        editorView.focus();
        editorView.dispatch(editorView.state.tr.scrollIntoView());
        return true;
      },
      // Code copied from `EditorActions.blur()`
      blur: () => {
        const editorView = config === null || config === void 0 ? void 0 : config.getEditorView();
        if (!editorView || !editorView.hasFocus()) {
          return false;
        }
        editorView.dom.blur();
        return true;
      },
      requestDocument(onReceive, options) {
        var _config$getEditorView;
        const view = (_config$getEditorView = config === null || config === void 0 ? void 0 : config.getEditorView()) !== null && _config$getEditorView !== void 0 ? _config$getEditorView : null;
        scheduleDocumentRequest(view, onReceive, options === null || options === void 0 ? void 0 : options.transformer);
      },
      createTransformer(cb) {
        var _config$getEditorView2;
        const view = (_config$getEditorView2 = config === null || config === void 0 ? void 0 : config.getEditorView()) !== null && _config$getEditorView2 !== void 0 ? _config$getEditorView2 : null;
        if (!(view !== null && view !== void 0 && view.state.schema)) {
          return undefined;
        }
        return cb(view === null || view === void 0 ? void 0 : view.state.schema);
      }
    }
  };
};