jsPlumbHandle.js 22.0 KB
Newer Older
L
ligang 已提交
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16
/*
 * Licensed to the Apache Software Foundation (ASF) under one or more
 * contributor license agreements.  See the NOTICE file distributed with
 * this work for additional information regarding copyright ownership.
 * The ASF licenses this file to You under the Apache License, Version 2.0
 * (the "License"); you may not use this file except in compliance with
 * the License.  You may obtain a copy of the License at
 *
 *    http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */
17 18 19
import 'jquery-ui/ui/widgets/draggable'
import 'jquery-ui/ui/widgets/droppable'
import 'jquery-ui/ui/widgets/resizable'
L
ligang 已提交
20 21 22 23 24 25 26 27
import Vue from 'vue'
import _ from 'lodash'
import i18n from '@/module/i18n'
import { jsPlumb } from 'jsplumb'
import DragZoom from './dragZoom'
import store from '@/conf/home/store'
import router from '@/conf/home/router'
import { uuid, findComponentDownward } from '@/module/util/'
28

L
ligang 已提交
29 30 31 32 33
import {
  tasksAll,
  rtTasksTpl,
  setSvgColor,
  saveTargetarr,
S
satcblue 已提交
34 35
  rtTargetarrArr,
  computeScale
36
} from './util'
L
ligang 已提交
37
import mStart from '@/conf/home/pages/projects/pages/definition/pages/list/_source/start'
S
satcblue 已提交
38
import multiDrag from './multiDrag'
L
ligang 已提交
39

40
const JSP = function () {
L
ligang 已提交
41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61
  this.dag = {}
  this.selectedElement = {}

  this.config = {
    // Whether to drag
    isDrag: true,
    // Whether to allow connection
    isAttachment: false,
    // Whether to drag a new node
    isNewNodes: true,
    // Whether to support double-click node events
    isDblclick: true,
    // Whether to support right-click menu events
    isContextmenu: true,
    // Whether to allow click events
    isClick: false
  }
}
/**
 * dag init
 */
Z
zhukai 已提交
62
JSP.prototype.init = function ({ dag, instance, options }) {
L
ligang 已提交
63 64 65 66
  // Get the dag component instance
  this.dag = dag
  // Get jsplumb instance
  this.JspInstance = instance
Z
zhukai 已提交
67 68
  // Get JSP options
  this.options = options || {}
L
ligang 已提交
69 70 71
  // Register jsplumb connection type and configuration
  this.JspInstance.registerConnectionType('basic', {
    anchor: 'Continuous',
B
break60 已提交
72
    connector: 'Bezier' // Line type
L
ligang 已提交
73 74 75 76 77 78
  })

  // Initial configuration
  this.setConfig({
    isDrag: !store.state.dag.isDetails,
    isAttachment: false,
79
    isNewNodes: !store.state.dag.isDetails, // Permissions.getAuth() === false ? false : !store.state.dag.isDetails,
L
ligang 已提交
80 81 82 83 84 85 86
    isDblclick: true,
    isContextmenu: true,
    isClick: false
  })

  // Monitor line click
  this.JspInstance.bind('click', e => {
87 88 89 90
    // Untie event
  if (this.config.isDblclick) {
    findComponentDownward(this.dag.$root, 'dag-chart')._createLineLabel({id: e._jsPlumb.overlays.label.canvas.id, sourceId: e.sourceId, targetId: e.targetId})
    }
L
ligang 已提交
91 92 93 94 95 96 97 98 99
    if (this.config.isClick) {
      this.connectClick(e)
    }
  })

  // Drag and drop
  if (this.config.isNewNodes) {
    DragZoom.init()
  }
S
satcblue 已提交
100 101 102

  // support multi drag
  multiDrag()
L
ligang 已提交
103 104 105 106 107 108 109 110 111 112 113 114 115
}

/**
 * set config attribute
 */
JSP.prototype.setConfig = function (o) {
  this.config = Object.assign(this.config, {}, o)
}

/**
 * Node binding event
 */
JSP.prototype.tasksEvent = function (selfId) {
116
  const tasks = $(`#${selfId}`)
L
ligang 已提交
117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139
  // Bind right event
  tasks.on('contextmenu', e => {
    this.tasksContextmenu(e)
    return false
  })

  // Binding double click event
  tasks.find('.icos').bind('dblclick', e => {
    this.tasksDblclick(e)
  })

  // Binding click event
  tasks.on('click', e => {
    this.tasksClick(e)
  })
}

/**
 * Dag node drag and drop processing
 */
JSP.prototype.draggable = function () {
  if (this.config.isNewNodes) {
    let selfId
140
    const self = this
L
ligang 已提交
141 142 143 144 145 146 147 148 149 150 151 152 153 154 155
    $('.toolbar-btn .roundedRect').draggable({
      scope: 'plant',
      helper: 'clone',
      containment: $('.dag-model'),
      stop: function (e, ui) {
      },
      drag: function () {
        $('body').find('.tooltip.fade.top.in').remove()
      }
    })

    $('#canvas').droppable({
      scope: 'plant',
      drop: function (ev, ui) {
        let id = 'tasks-' + Math.ceil(Math.random() * 100000) // eslint-disable-line
S
satcblue 已提交
156 157 158 159 160 161 162

        let scale = computeScale($(this))
        scale = scale || 1

        // Get mouse coordinates and after scale coordinate
        const left = parseInt(ui.offset.left - $(this).offset().left) / scale
        const top = parseInt(ui.offset.top - $(this).offset().top) / scale
L
ligang 已提交
163 164 165 166 167 168 169 170 171 172 173
        // Generate template node
        $('#canvas').append(rtTasksTpl({
          id: id,
          name: id,
          x: left,
          y: top,
          isAttachment: self.config.isAttachment,
          taskType: findComponentDownward(self.dag.$root, 'dag-chart').dagBarId
        }))

        // Get the generated node
174
        const thisDom = jsPlumb.getSelector('.statemachine-demo .w')
L
ligang 已提交
175 176 177 178 179 180

        // Generating a connection node
        self.JspInstance.batch(() => {
          self.initNode(thisDom[thisDom.length - 1])
        })
        selfId = id
Z
zhukai 已提交
181 182 183 184 185 186 187 188 189 190

        self.tasksEvent(selfId)

        // Dom structure is not generated without pop-up form form
        if ($(`#${selfId}`).html()) {
          // dag event
          findComponentDownward(self.dag.$root, 'dag-chart')._createNodes({
            id: selfId
          })
        }
L
ligang 已提交
191 192 193 194 195 196 197 198 199 200 201 202 203 204
      }
    })
  }
}

/**
 * Echo json processing and old data structure processing
 */
JSP.prototype.jsonHandle = function ({ largeJson, locations }) {
  _.map(largeJson, v => {
    // Generate template
    $('#canvas').append(rtTasksTpl({
      id: v.id,
      name: v.name,
205 206 207
      x: locations[v.id].x,
      y: locations[v.id].y,
      targetarr: locations[v.id].targetarr,
L
ligang 已提交
208
      isAttachment: this.config.isAttachment,
G
gongzijian 已提交
209
      taskType: v.type,
210
      runFlag: v.runFlag,
211
      nodenumber: locations[v.id].nodenumber,
B
fix  
break60 已提交
212 213
      successNode: v.conditionResult === undefined? '' : v.conditionResult.successNode[0],
      failedNode: v.conditionResult === undefined? '' : v.conditionResult.failedNode[0]
L
ligang 已提交
214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249
    }))

    // contextmenu event
    $(`#${v.id}`).on('contextmenu', e => {
      this.tasksContextmenu(e)
      return false
    })

    // dblclick event
    $(`#${v.id}`).find('.icos').bind('dblclick', e => {
      this.tasksDblclick(e)
    })

    // click event
    $(`#${v.id}`).bind('click', e => {
      this.tasksClick(e)
    })
  })
}

/**
 * Initialize a single node
 */
JSP.prototype.initNode = function (el) {
  // Whether to drag
  if (this.config.isDrag) {
    this.JspInstance.draggable(el, {
      containment: 'dag-container'
    })
  }

  // Node attribute configuration
  this.JspInstance.makeSource(el, {
    filter: '.ep',
    anchor: 'Continuous',
    connectorStyle: {
B
break60 已提交
250
      stroke: '#2d8cf0',
L
ligang 已提交
251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276
      strokeWidth: 2,
      outlineStroke: 'transparent',
      outlineWidth: 4
    },
    // This place is leaking
    // connectionType: "basic",
    extract: {
      action: 'the-action'
    },
    maxConnections: -1
  })

  // Node connection property configuration
  this.JspInstance.makeTarget(el, {
    dropOptions: { hoverClass: 'dragHover' },
    anchor: 'Continuous',
    allowLoopback: false // Forbid yourself to connect yourself
  })
  this.JspInstance.fire('jsPlumbDemoNodeAdded', el)
}

/**
 * Node right click menu
 */
JSP.prototype.tasksContextmenu = function (event) {
  if (this.config.isContextmenu) {
277
    const routerName = router.history.current.name
L
ligang 已提交
278
    // state
279
    const isOne = routerName === 'projects-definition-details' && this.dag.releaseState !== 'NOT_RELEASE'
L
ligang 已提交
280
    // hide
281
    const isTwo = store.state.dag.isDetails
L
ligang 已提交
282

283
    const html = [
284 285 286 287
      `<a href="javascript:" id="startRunning" class="${isOne ? '' : 'disbled'}"><em class="ans-icon-play"></em><span>${i18n.$t('Start')}</span></a>`,
      `<a href="javascript:" id="editNodes" class="${isTwo ? 'disbled' : ''}"><em class="ans-icon-edit"></em><span>${i18n.$t('Edit')}</span></a>`,
      `<a href="javascript:" id="copyNodes" class="${isTwo ? 'disbled' : ''}"><em class="ans-icon-copy"></em><span>${i18n.$t('Copy')}</span></a>`,
      `<a href="javascript:" id="removeNodes" class="${isTwo ? 'disbled' : ''}"><em class="ans-icon-trash"></em><span>${i18n.$t('Delete')}</span></a>`
L
ligang 已提交
288 289
    ]

290
    const operationHtml = () => {
L
ligang 已提交
291 292 293
      return html.splice(',')
    }

294 295 296 297 298 299
    const e = event
    const $id = e.currentTarget.id
    const $contextmenu = $('#contextmenu')
    const $name = $(`#${$id}`).find('.name-p').text()
    const $left = e.pageX + document.body.scrollLeft - 5
    const $top = e.pageY + document.body.scrollTop - 5
L
ligang 已提交
300 301 302 303 304 305 306 307 308 309 310
    $contextmenu.css({
      left: $left,
      top: $top,
      visibility: 'visible'
    })
    // Action bar
    $contextmenu.html('').append(operationHtml)

    if (isOne) {
      // start run
      $('#startRunning').on('click', () => {
311 312
        const name = store.state.dag.name
        const id = router.history.current.params.id
L
ligang 已提交
313
        store.dispatch('dag/getStartCheck', { processDefinitionId: id }).then(res => {
314
          const modal = Vue.$modal.dialog({
L
ligang 已提交
315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331
            closable: false,
            showMask: true,
            escClose: true,
            className: 'v-modal-custom',
            transitionName: 'opacityp',
            render (h) {
              return h(mStart, {
                on: {
                  onUpdate () {
                    modal.remove()
                  },
                  close () {
                    modal.remove()
                  }
                },
                props: {
                  item: {
B
break60 已提交
332 333
                    id: id,
                    name: name
L
ligang 已提交
334 335 336 337 338 339 340 341 342 343 344 345
                  },
                  startNodeList: $name,
                  sourceType: 'contextmenu'
                }
              })
            }
          })
        }).catch(e => {
          Vue.$message.error(e.msg || '')
        })
      })
    }
346
    if (!isTwo) {
L
ligang 已提交
347
      // edit node
348
      $('#editNodes').click(ev => {
L
ligang 已提交
349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372
        findComponentDownward(this.dag.$root, 'dag-chart')._createNodes({
          id: $id,
          type: $(`#${$id}`).attr('data-tasks-type')
        })
      })
      // delete node
      $('#removeNodes').click(ev => {
        this.removeNodes($id)
      })

      // copy node
      $('#copyNodes').click(res => {
        this.copyNodes($id)
      })
    }
  }
}

/**
 * Node double click event
 */
JSP.prototype.tasksDblclick = function (e) {
  // Untie event
  if (this.config.isDblclick) {
373
    const id = $(e.currentTarget.offsetParent).attr('id')
L
ligang 已提交
374 375 376 377 378 379 380 381 382 383 384 385 386

    findComponentDownward(this.dag.$root, 'dag-chart')._createNodes({
      id: id,
      type: $(`#${id}`).attr('data-tasks-type')
    })
  }
}

/**
 * Node click event
 */
JSP.prototype.tasksClick = function (e) {
  let $id
387 388
  const self = this
  const $body = $('body')
L
ligang 已提交
389
  if (this.config.isClick) {
390
    const $connect = this.selectedElement.connect
L
ligang 已提交
391 392 393
    $('.w').removeClass('jtk-tasks-active')
    $(e.currentTarget).addClass('jtk-tasks-active')
    if ($connect) {
B
break60 已提交
394
      setSvgColor($connect, '#2d8cf0')
L
ligang 已提交
395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419
      this.selectedElement.connect = null
    }
    this.selectedElement.id = $(e.currentTarget).attr('id')

    // Unbind copy and paste events
    $body.unbind('copy').unbind('paste')
    // Copy binding id
    $id = self.selectedElement.id

    $body.bind({
      copy: function () {
        $id = self.selectedElement.id
      },
      paste: function () {
        $id && self.copyNodes($id)
      }
    })
  }
}

/**
 * Remove binding events
 * paste
 */
JSP.prototype.removePaste = function () {
420
  const $body = $('body')
L
ligang 已提交
421 422 423 424 425 426 427 428 429 430 431 432 433 434
  // Unbind copy and paste events
  $body.unbind('copy').unbind('paste')
  // Remove selected node parameters
  this.selectedElement.id = null
  // Remove node selection effect
  $('.w').removeClass('jtk-tasks-active')
}

/**
 * Line click event
 */
JSP.prototype.connectClick = function (e) {
  // Set svg color
  setSvgColor(e, '#0097e0')
435
  const $id = this.selectedElement.id
L
ligang 已提交
436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458
  if ($id) {
    $(`#${$id}`).removeClass('jtk-tasks-active')
    this.selectedElement.id = null
  }
  this.selectedElement.connect = e
}

/**
 * toolbarEvent
 * @param {Pointer}
 */
JSP.prototype.handleEventPointer = function (is) {
  this.setConfig({
    isClick: is,
    isAttachment: false
  })
}

/**
 * toolbarEvent
 * @param {Line}
 */
JSP.prototype.handleEventLine = function (is) {
459
  const wDom = $('.w')
L
ligang 已提交
460 461 462 463 464 465 466 467 468 469 470
  this.setConfig({
    isAttachment: is
  })
  is ? wDom.addClass('jtk-ep') : wDom.removeClass('jtk-ep')
}

/**
 * toolbarEvent
 * @param {Remove}
 */
JSP.prototype.handleEventRemove = function () {
471 472
  const $id = this.selectedElement.id || null
  const $connect = this.selectedElement.connect || null
L
ligang 已提交
473 474 475 476 477 478 479 480 481 482 483 484 485 486 487 488
  if ($id) {
    this.removeNodes(this.selectedElement.id)
  } else {
    this.removeConnect($connect)
  }

  // Monitor whether to edit DAG
  store.commit('dag/setIsEditDag', true)
}

/**
 * Delete node
 */
JSP.prototype.removeNodes = function ($id) {
  // Delete node processing(data-targetarr)
  _.map(tasksAll(), v => {
489
    const targetarr = v.targetarr.split(',')
L
ligang 已提交
490
    if (targetarr.length) {
491
      const newArr = _.filter(targetarr, v1 => v1 !== $id)
L
ligang 已提交
492 493 494 495 496
      $(`#${v.id}`).attr('data-targetarr', newArr.toString())
    }
  })
  // delete node
  this.JspInstance.remove($id)
497 498 499

  // delete dom
  $(`#${$id}`).remove()
Z
zhukai 已提交
500 501

  // callback onRemoveNodes event
502
  this.options && this.options.onRemoveNodes && this.options.onRemoveNodes($id)
L
ligang 已提交
503 504 505 506 507 508 509 510 511 512
}

/**
 * Delete connection
 */
JSP.prototype.removeConnect = function ($connect) {
  if (!$connect) {
    return
  }
  // Remove connections and remove node and node dependencies
513 514
  const targetId = $connect.targetId
  const sourceId = $connect.sourceId
L
ligang 已提交
515 516 517 518 519
  let targetarr = rtTargetarrArr(targetId)
  if (targetarr.length) {
    targetarr = _.filter(targetarr, v => v !== sourceId)
    $(`#${targetId}`).attr('data-targetarr', targetarr.toString())
  }
520 521
  if ($(`#${sourceId}`).attr('data-tasks-type') === 'CONDITIONS') {
    $(`#${sourceId}`).attr('data-nodenumber', Number($(`#${sourceId}`).attr('data-nodenumber')) - 1)
522
  }
L
ligang 已提交
523 524 525 526 527 528 529 530 531 532
  this.JspInstance.deleteConnection($connect)

  this.selectedElement = {}
}

/**
 * Copy node
 */
JSP.prototype.copyNodes = function ($id) {
  let newNodeInfo = _.cloneDeep(_.find(store.state.dag.tasks, v => v.id === $id))
533
  const newNodePors = store.state.dag.locations[$id]
L
ligang 已提交
534 535 536 537 538
  // Unstored nodes do not allow replication
  if (!newNodePors) {
    return
  }
  // Generate random id
539 540 541
  const newUuId = `${uuid() + uuid()}`
  const id = newNodeInfo.id.length > 8 ? newNodeInfo.id.substr(0, 7) : newNodeInfo.id
  const name = newNodeInfo.name.length > 8 ? newNodeInfo.name.substr(0, 7) : newNodeInfo.name
L
ligang 已提交
542 543

  // new id
544
  const newId = `${id || ''}-${newUuId}`
L
ligang 已提交
545
  // new name
546
  const newName = `${name || ''}-${newUuId}`
L
ligang 已提交
547
  // coordinate x
548
  const newX = newNodePors.x + 100
L
ligang 已提交
549
  // coordinate y
550
  const newY = newNodePors.y + 40
L
ligang 已提交
551 552 553 554 555 556 557 558 559 560 561 562

  // Generate template node
  $('#canvas').append(rtTasksTpl({
    id: newId,
    name: newName,
    x: newX,
    y: newY,
    isAttachment: this.config.isAttachment,
    taskType: newNodeInfo.type
  }))

  // Get the generated node
563
  const thisDom = jsPlumb.getSelector('.statemachine-demo .w')
L
ligang 已提交
564 565 566 567 568 569 570 571 572 573

  // Copy node information
  newNodeInfo = Object.assign(newNodeInfo, {
    id: newId,
    name: newName
  })

  // Add new node
  store.commit('dag/addTasks', newNodeInfo)
  // Add node location information
574
  store.commit('dag/addLocations', {
L
ligang 已提交
575 576 577
    [newId]: {
      name: newName,
      targetarr: '',
578
      nodenumber: 0,
L
ligang 已提交
579 580 581 582 583 584 585 586 587 588 589 590 591 592 593 594 595 596 597
      x: newX,
      y: newY
    }
  })

  // Generating a connection node
  this.JspInstance.batch(() => {
    this.initNode(thisDom[thisDom.length - 1])
    // Add events to nodes
    this.tasksEvent(newId)
  })
}
/**
 * toolbarEvent
 * @param {Screen}
 */
JSP.prototype.handleEventScreen = function ({ item, is }) {
  let screenOpen = true
  if (is) {
598
    item.icon = 'ans-icon-min'
L
ligang 已提交
599 600
    screenOpen = true
  } else {
601
    item.icon = 'ans-icon-max'
L
ligang 已提交
602 603
    screenOpen = false
  }
604
  const $mainLayoutModel = $('.main-layout-model')
L
ligang 已提交
605 606 607 608 609 610 611 612 613 614 615 616 617 618
  if (screenOpen) {
    $mainLayoutModel.addClass('dag-screen')
  } else {
    $mainLayoutModel.removeClass('dag-screen')
  }
}
/**
 * save task
 * @param tasks
 * @param locations
 * @param connects
 */
JSP.prototype.saveStore = function () {
  return new Promise((resolve, reject) => {
619 620 621
    const connects = []
    const locations = {}
    const tasks = []
L
ligang 已提交
622

623
    const is = (id) => {
L
ligang 已提交
624 625 626 627 628 629
      return !!_.filter(tasksAll(), v => v.id === id).length
    }

    // task
    _.map(_.cloneDeep(store.state.dag.tasks), v => {
      if (is(v.id)) {
630 631 632 633
        const preTasks = []
        const id = $(`#${v.id}`)
        const tar = id.attr('data-targetarr')
        const idDep = tar ? id.attr('data-targetarr').split(',') : []
L
ligang 已提交
634 635 636 637 638 639 640 641 642 643 644 645 646 647 648 649 650 651
        if (idDep.length) {
          _.map(idDep, v1 => {
            preTasks.push($(`#${v1}`).find('.name-p').text())
          })
        }

        let tasksParam = _.assign(v, {
          preTasks: preTasks
        })

        // Sub-workflow has no retries and interval
        if (v.type === 'SUB_PROCESS') {
          tasksParam = _.omit(tasksParam, ['maxRetryTimes', 'retryInterval'])
        }

        tasks.push(tasksParam)
      }
    })
652 653 654 655 656 657 658
    if(store.state.dag.connects.length ===this.JspInstance.getConnections().length) {
      _.map(store.state.dag.connects, u => {
        connects.push({
          endPointSourceId: u.endPointSourceId,
          endPointTargetId: u.endPointTargetId,
          label: u.label
        })
L
ligang 已提交
659
      })
660 661 662 663 664 665 666 667 668 669 670 671 672 673 674 675 676 677 678 679 680 681 682 683 684
    } else if(store.state.dag.connects.length>0 && store.state.dag.connects.length < this.JspInstance.getConnections().length) {
      _.map(this.JspInstance.getConnections(), v => {
        connects.push({
          endPointSourceId: v.sourceId,
          endPointTargetId: v.targetId,
          label: v._jsPlumb.overlays.label.canvas.innerText
        })
      })
      _.map(store.state.dag.connects, u => {
        _.map(connects, v => {
          if(u.label && u.endPointSourceId === v.endPointSourceId && u.endPointTargetId===v.endPointTargetId) {
            v.label = u.label
          }
        })
      })
    } else if(store.state.dag.connects.length===0) {
      _.map(this.JspInstance.getConnections(), v => {
        connects.push({
          endPointSourceId: v.sourceId,
          endPointTargetId: v.targetId,
          label: v._jsPlumb.overlays.label.canvas.innerText
        })
      })
    }
    
L
ligang 已提交
685 686 687 688
    _.map(tasksAll(), v => {
      locations[v.id] = {
        name: v.name,
        targetarr: v.targetarr,
689
        nodenumber: v.nodenumber,
L
ligang 已提交
690 691 692 693 694 695 696 697 698 699 700 701 702 703 704 705 706 707 708 709 710 711
        x: v.x,
        y: v.y
      }
    })

    // Storage node
    store.commit('dag/setTasks', tasks)
    // Store coordinate information
    store.commit('dag/setLocations', locations)
    // Storage line dependence
    store.commit('dag/setConnects', connects)

    resolve({
      connects: connects,
      tasks: tasks,
      locations: locations
    })
  })
}
/**
 * Event processing
 */
712

L
ligang 已提交
713 714
JSP.prototype.handleEvent = function () {
  this.JspInstance.bind('beforeDrop', function (info) {
715 716
    const sourceId = info.sourceId// 出
    const targetId = info.targetId// 入
L
ligang 已提交
717 718 719 720 721
    /**
     * Recursive search for nodes
     */
    let recursiveVal
    const recursiveTargetarr = (arr, targetId) => {
722
      for (const i in arr) {
L
ligang 已提交
723 724 725
        if (arr[i] === targetId) {
          recursiveVal = targetId
        } else {
726
          recursiveTargetarr(rtTargetarrArr(arr[i]), targetId)
L
ligang 已提交
727 728 729 730 731 732 733 734 735 736 737 738 739 740 741
        }
      }
      return recursiveVal
    }

    // Connection to connected nodes is not allowed
    if (_.findIndex(rtTargetarrArr(targetId), v => v === sourceId) !== -1) {
      return false
    }

    // Recursive form to find if the target Targetarr has a sourceId
    if (recursiveTargetarr(rtTargetarrArr(sourceId), targetId)) {
      return false
    }

742
    if ($(`#${sourceId}`).attr('data-tasks-type') === 'CONDITIONS' && $(`#${sourceId}`).attr('data-nodenumber') === 2) {
743 744
      return false
    } else {
745
      $(`#${sourceId}`).attr('data-nodenumber', Number($(`#${sourceId}`).attr('data-nodenumber')) + 1)
746
    }
747

L
ligang 已提交
748 749 750 751 752 753 754 755 756 757 758 759 760 761 762 763 764 765 766
    // Storage node dependency information
    saveTargetarr(sourceId, targetId)

    // Monitor whether to edit DAG
    store.commit('dag/setIsEditDag', true)

    return true
  })
}
/**
 * Backfill data processing
 */
JSP.prototype.jspBackfill = function ({ connects, locations, largeJson }) {
  // Backfill nodes
  this.jsonHandle({
    largeJson: largeJson,
    locations: locations
  })

767
  const wNodes = jsPlumb.getSelector('.statemachine-demo .w')
L
ligang 已提交
768 769 770 771 772 773 774 775 776

  // Backfill line
  this.JspInstance.batch(() => {
    for (let i = 0; i < wNodes.length; i++) {
      this.initNode(wNodes[i])
    }
    _.map(connects, v => {
      let sourceId = v.endPointSourceId.split('-')
      let targetId = v.endPointTargetId.split('-')
777
      let labels = v.label
L
ligang 已提交
778 779 780 781 782 783 784
      if (sourceId.length === 4 && targetId.length === 4) {
        sourceId = `${sourceId[0]}-${sourceId[1]}-${sourceId[2]}`
        targetId = `${targetId[0]}-${targetId[1]}-${targetId[2]}`
      } else {
        sourceId = v.endPointSourceId
        targetId = v.endPointTargetId
      }
785 786 787 788 789 790
      
      if($(`#${sourceId}`).attr('data-tasks-type') === 'CONDITIONS' && $(`#${sourceId}`).attr('data-successnode') === $(`#${targetId}`).find('.name-p').text()) {
        this.JspInstance.connect({
          source: sourceId,
          target: targetId,
          type: 'basic',
B
break60 已提交
791 792
          paintStyle: { strokeWidth: 2, stroke: '#4caf50' },
          HoverPaintStyle: {stroke: '#ccc', strokeWidth: 3},
B
fix  
break60 已提交
793
          overlays:[["Label", { label: i18n.$t('success'), location:0.5, id:"label"} ]]
794 795 796 797 798 799
        })
      } else if($(`#${sourceId}`).attr('data-tasks-type') === 'CONDITIONS' && $(`#${sourceId}`).attr('data-failednode') === $(`#${targetId}`).find('.name-p').text()) {
        this.JspInstance.connect({
          source: sourceId,
          target: targetId,
          type: 'basic',
800
          paintStyle: { strokeWidth: 2, stroke: '#252d39' },
B
break60 已提交
801
          HoverPaintStyle: {stroke: '#ccc', strokeWidth: 3},
B
fix  
break60 已提交
802
          overlays:[["Label", { label: i18n.$t('failed'), location:0.5, id:"label"} ]]
803 804 805 806 807 808
        })
      } else {
        this.JspInstance.connect({
          source: sourceId,
          target: targetId,
          type: 'basic',
B
break60 已提交
809
          paintStyle: { strokeWidth: 2, stroke: '#2d8cf0' },
810 811
          HoverPaintStyle: {stroke: '#ccc', strokeWidth: 3},
          overlays:[["Label", { label: labels} ]]
812 813
        })
      }
L
ligang 已提交
814 815 816 817 818 819 820 821 822 823 824 825 826
    })
  })

  jsPlumb.fire('jsPlumbDemoLoaded', this.JspInstance)

  // Connection monitoring
  this.handleEvent()

  // Drag and drop new nodes
  this.draggable()
}

export default new JSP()