all files / ui/ InsertNodeCommand.js

20% Statements 5/25
42.86% Branches 6/14
25% Functions 1/4
21.74% Lines 5/23
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55            1522× 1522×       1522× 1038×   1522×                                                                                
import { forEach } from '../util'
import Command from './Command'
 
class InsertNodeCommand extends Command {
 
  getCommandState(params) {
    let sel = params.selection
    let newState = {
      disabled: true,
      active: false
    }
    if (sel && !sel.isNull() && !sel.isCustomSelection() && sel.containerId) {
      newState.disabled = false
    }
    return newState
  }
 
  execute(params, context) {
    var state = params.commandState
    if (state.disabled) return
    let editorSession = this._getEditorSession(params, context)
    editorSession.transaction((tx) => {
      let nodeData = this.createNodeData(tx, params, context)
      let node = tx.insertBlockNode(nodeData)
      this.setSelection(tx, node)
    })
  }
 
  createNodeData(tx, params, context) {
    const type = params.type
    if (!type) throw new Error("'type' is mandatory")
    const doc = context.editorSession.getDocument()
    const nodeSchema = doc.getSchema().getNodeSchema(type)
    let nodeData = {type}
    forEach(nodeSchema, (key) => {
      if (params.hasOwnProperty(key)) {
        nodeData[key] = params[key]
      }
    })
    return nodeData
  }
 
  setSelection(tx, node) {
    if (node.isText()) {
      tx.selection = {
        type: 'property',
        path: node.getPath(),
        startOffset: 0
      }
    }
  }
}
 
export default InsertNodeCommand