diff --git a/packages/core/src/CommandManager.ts b/packages/core/src/CommandManager.ts index 7d5fb89f..f77879b1 100644 --- a/packages/core/src/CommandManager.ts +++ b/packages/core/src/CommandManager.ts @@ -1,5 +1,7 @@ import { EditorState, Transaction } from 'prosemirror-state' -import { ChainedCommands, Editor, CommandSpec } from './Editor' +import { + SingleCommands, ChainedCommands, Editor, CommandSpec, +} from './Editor' import getAllMethodNames from './utils/getAllMethodNames' export default class CommandManager { @@ -95,6 +97,30 @@ export default class CommandManager { }) as ChainedCommands } + public createCan(startTr?: Transaction) { + const { commands, editor } = this + const { state } = editor + const dispatch = false + const hasStartTransaction = !!startTr + const tr = hasStartTransaction ? startTr : state.tr + + if (!tr) { + return + } + + const props = this.buildProps(tr, dispatch) + const formattedCommands = Object.fromEntries(Object + .entries(commands) + .map(([name, command]) => { + return [name, (...args: any[]) => command(...args)({ ...props, dispatch })] + })) + + return { + ...formattedCommands, + chain: () => this.createChain(tr, dispatch), + } as SingleCommands & { chain: () => ChainedCommands } + } + public buildProps(tr: Transaction, shouldDispatch = true) { const { editor, commands } = this const { state, view } = editor @@ -108,19 +134,7 @@ export default class CommandManager { ? () => true : undefined, chain: () => this.createChain(tr), - can: () => { - const dispatch = false - const formattedCommands = Object.fromEntries(Object - .entries(commands) - .map(([name, command]) => { - return [name, (...args: any[]) => command(...args)({ ...props, dispatch })] - })) - - return { - ...formattedCommands, - chain: () => this.createChain(tr, dispatch), - } - }, + can: () => this.createCan(tr), get commands() { return Object.fromEntries(Object .entries(commands) diff --git a/packages/core/src/Editor.ts b/packages/core/src/Editor.ts index 0c8355e4..6d8805be 100644 --- a/packages/core/src/Editor.ts +++ b/packages/core/src/Editor.ts @@ -115,7 +115,6 @@ export class Editor extends EventEmitter { this.createExtensionManager() this.createSchema() this.createView() - // this.registerCommands(coreCommands) this.injectCSS() window.setTimeout(() => this.proxy.focus(this.options.autoFocus), 0) @@ -138,6 +137,13 @@ export class Editor extends EventEmitter { return this.commandManager.createChain() } + /** + * Check if a command or a command chain can be executed. Without executing it. + */ + public can() { + return this.commandManager.createCan() + } + /** * Inject CSS styles. */