Skip to content

Commit

Permalink
add can method to editor class
Browse files Browse the repository at this point in the history
  • Loading branch information
philippkuehn committed Nov 2, 2020
1 parent c73b03c commit 7bfab46
Show file tree
Hide file tree
Showing 2 changed files with 35 additions and 15 deletions.
42 changes: 28 additions & 14 deletions packages/core/src/CommandManager.ts
Original file line number Diff line number Diff line change
@@ -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 {
Expand Down Expand Up @@ -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
Expand All @@ -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)
Expand Down
8 changes: 7 additions & 1 deletion packages/core/src/Editor.ts
Original file line number Diff line number Diff line change
Expand Up @@ -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)
Expand All @@ -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.
*/
Expand Down

0 comments on commit 7bfab46

Please sign in to comment.