All files / modules/70-pipeline/components/Diagram/model DiagramModel.ts

73.29% Statements 118/161
44.94% Branches 40/89
73.08% Functions 19/26
72.96% Lines 116/159

Press n or j to go to the next uncovered block, b, p or k for the previous block.

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 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 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 250 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 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309                        207x 207x               207x 207x 207x 207x 207x 207x                           207x           21x     21x 21x 21x 21x 21x 21x 21x 21x       12x 12x 6x 6x 12x 12x 12x 5x 5x 5x 5x       6x         4x 4x 2x 2x 2x 2x         1x 1x 1x 1x 1x 1x 4x 4x   1x 1x     1x         40x 40x 40x 40x 40x 51x 51x           10x 10x 10x 10x 10x 10x 84x       10x 10x 10x 10x 10x 10x 6x 6x       10x 3x       40x   40x 40x 40x 40x 40x 71x       40x       40x       44x 44x       4x 2x 2x   4x       4x 4x 4x 4x                                     301x 301x 301x 301x 143x 143x 143x 77x 77x       301x 224x 224x 224x 224x 224x 224x 224x 224x                                                                                                                                                 11x       166x 166x 369x 203x 203x 97x       166x      
/*
 * Copyright 2021 Harness Inc. All rights reserved.
 * Use of this source code is governed by the PolyForm Shield 1.0.0 license
 * that can be found in the licenses directory at the root of this repository, also available at
 * https://polyformproject.org/wp-content/uploads/2020/06/PolyForm-Shield-1.0.0.txt.
 */
 
import type {
  DiagramModelOptions as DiagramModelCoreOptions,
  BaseModel,
  LayerModel
} from '@projectstorm/react-canvas-core'
import { isNil } from 'lodash-es'
import {
  DiagramModel as DiagramModelCore,
  DiagramModelGenerics as DiagramModelGenericsCore,
  NodeLayerModel,
  PortModel,
  PortModelGenerics
} from '@projectstorm/react-diagrams-core'
import type { Point } from '@projectstorm/geometry'
import { DefaultLinkModel } from '../link/DefaultLinkModel'
import { DefaultNodeModel } from '../node/DefaultNodeModel'
import { StepGroupNodeLayerModel } from '../node-layer/StepGroupNodeLayerModel'
import { EmptyNodeModel } from '../node/EmptyNode/EmptyNodeModel'
import { PortName } from '../Constants'
import css from './DiagramModel.module.scss'
 
export interface DiagramModelOptions extends DiagramModelCoreOptions {
  autoPosition?: boolean
  startX?: number
  startY?: number
  gapX?: number
  gapY?: number
}
 
export interface DiagramModelGenerics extends DiagramModelGenericsCore {
  OPTIONS: DiagramModelOptions
}
 
export class DiagramModel<G extends DiagramModelGenerics = DiagramModelGenerics> extends DiagramModelCore<G> {
  autoPosition: boolean
  startX: number
  startY: number
  gapX: number
  gapY: number
  stepGroupLayers: StepGroupNodeLayerModel[] = []
 
  constructor(options: G['OPTIONS'] = {}) {
    super(options)
    options.gridSize = 100
    this.autoPosition = options.autoPosition || true
    this.startX = options.startX || 100
    this.startY = options.startY || 100
    this.gapX = options.gapX || 200
    this.gapY = options.gapY || 140
    this.stepGroupLayers = []
  }
 
  clearAllLinksForNodeAndNode(id: string): void {
    const node = this.getNodeFromId(id)
    if (node) {
      const ports = node.getPorts()
      for (const portKey in ports) {
        const port = ports[portKey]
        const links = port.getLinks()
        for (const keyLink in links) {
          const link = links[keyLink]
          link.getSourcePort().removeLink(link)
          link.getTargetPort().removeLink(link)
          this.removeLink(link)
        }
      }
 
      this.removeNode(node)
    }
  }
 
  clearLinksForPort(port: PortModel<PortModelGenerics>): void {
    const links = port.getLinks()
    for (const keyLink in links) {
      const link = links[keyLink]
      link.getSourcePort().removeLink(link)
      link.getTargetPort().removeLink(link)
      this.removeLink(link)
    }
  }
 
  clearAllLinksForGroupLayer(id: string): void {
    const layer = this.getGroupLayer(id)
    Eif (layer) {
      const groupNodes = layer.getNodes()
      this.clearAllLinksForNodeAndNode(layer.startNode.getID())
      this.clearAllLinksForNodeAndNode(layer.endNode.getID())
      for (const key in groupNodes) {
        const node = groupNodes[key]
        this.clearAllLinksForNodeAndNode(node.getID())
      }
      this.stepGroupLayers.splice(
        this.stepGroupLayers.findIndex(item => item.getID() === id),
        1
      )
      layer.remove()
    }
  }
 
  clearAllLinks(): void {
    const linkLayers = this.getLinkLayers()
    for (const layerKey in linkLayers) {
      const linkLayer = linkLayers[layerKey]
      const links = linkLayer.getLinks()
      for (const key in links) {
        const link = links[key]
        this.removeLink(link)
      }
    }
  }
 
  clearAllListeners(): void {
    const nodeLayers = this.getNodeLayers()
    for (const key in nodeLayers) {
      const nodeLayer = nodeLayers[key]
      nodeLayer.clearListeners()
      const nodes = nodeLayer.getNodes()
      for (const nodeKey in nodes) {
        nodes[nodeKey].clearListeners()
      }
    }
 
    const linkLayers = this.getLinkLayers()
    for (const layerKey in linkLayers) {
      const linkLayer = linkLayers[layerKey]
      linkLayer.clearListeners()
      const links = linkLayer.getLinks()
      for (const key in links) {
        const link = links[key]
        link.clearListeners()
      }
    }
 
    this.stepGroupLayers.forEach(layer => {
      layer.clearListeners()
    })
  }
  clearAllNodesAndLinks(): void {
    this.clearAllLinks()
 
    const nodeLayers = this.getNodeLayers()
    for (const key in nodeLayers) {
      const nodeLayer = nodeLayers[key]
      const nodes = nodeLayer.getNodes()
      for (const nodeKey in nodes) {
        this.removeNode(nodes[nodeKey])
      }
    }
 
    this.stepGroupLayers.forEach(layer => {
      layer.clearListeners()
      layer.remove()
    })
    this.stepGroupLayers = []
  }
 
  addLayer(layer: LayerModel): void {
    super.addLayer(layer)
    this.layers = this.layers.sort((lay: LayerModel) => (lay.getOptions().isSvg ? 1 : -1))
  }
 
  useStepGroupLayer(stepGroupLayers: StepGroupNodeLayerModel): void {
    if (this.stepGroupLayers.indexOf(stepGroupLayers) === -1) {
      this.stepGroupLayers.push(stepGroupLayers)
      this.addLayer(stepGroupLayers)
    }
    this.activeNodeLayer = stepGroupLayers as any
  }
 
  useNormalLayer(): void {
    const layers = this.getNodeLayers()
    layers.forEach(layer => {
      Eif (layer instanceof NodeLayerModel) {
        this.activeNodeLayer = layer
      }
    })
  }
 
  checkNodeNotAdded(node: DefaultNodeModel | undefined): boolean {
    const nodeId = node?.getID()
    const nodeRendered = this.getNode(nodeId || '')
    return isNil(nodeRendered)
  }
 
  protected connectedParentToNode(
    node: DefaultNodeModel,
    parent: DefaultNodeModel,
    allowAdd = true,
    strokeDasharray = 0,
    color = 'var(--diagram-link)',
    maxLinePartLength?: { type: 'in' | 'out'; size: number }
  ): void {
    const inPort = node.getPort(PortName.In) || node.addInPort(PortName.In)
    const links = inPort.getLinks()
    let isConnectedToParent = false
    for (const linkId in links) {
      const link = links[linkId] as DefaultLinkModel
      const nodeId = link.getSourcePort().getNode().getID()
      if (nodeId === parent.getID()) {
        isConnectedToParent = true
        link.setColorOfLink(color)
      }
    }
    // NOTE: parent.getOutPorts().length === 0 solve the issue with missing line at the end of graph
    if (!isConnectedToParent || parent.getOutPorts().length === 0) {
      const parentPort = parent.getPort(PortName.Out) || parent.addOutPort(PortName.Out)
      Eif (parentPort && inPort) {
        const link = new DefaultLinkModel({ allowAdd, strokeDasharray, color, maxLinePartLength: maxLinePartLength })
        link.setSourcePort(parentPort)
        link.setTargetPort(inPort)
        inPort.reportPosition()
        parentPort.reportPosition()
        this.addLink(link)
      }
    }
  }
 
  protected connectMultipleParentsToNode(
    node: DefaultNodeModel,
    parents: DefaultNodeModel[],
    allowAdd = true,
    strokeDasharray = 0,
    color = 'var(--diagram-link)',
    maxLinePartLength?: { type: 'in' | 'out'; size: number }
  ): void {
    let highestMidX = 0
    parents.forEach(parent => {
      const inPort = node.getPort(PortName.In) || node.addInPort(PortName.In)
      const parentPort = parent.getPort(PortName.Out) || parent.addOutPort(PortName.Out)
      const midX =
        parent instanceof EmptyNodeModel
          ? (inPort.getPosition().x + parentPort.getPosition().x) / 2
          : (inPort.getPosition().x + parentPort.getPosition().x + this.gapX / 2) / 2
      if (midX > highestMidX) {
        highestMidX = midX
      }
    })
    parents.forEach(parent => {
      this.connectedParentToNode(node, parent, allowAdd, strokeDasharray, color, maxLinePartLength)
    })
  }
 
  getNodeLinkAtPosition(position: Point): BaseModel | undefined {
    const nodes = this.getActiveNodeLayer().getNodes()
    const nearByNodes: DefaultNodeModel[] = []
    for (const key in nodes) {
      const node = nodes[key] as DefaultNodeModel
      const dom = document.querySelector(`[data-nodeid="${node.getID()}"]`)
      if (node.getBoundingBox().containsPoint(position)) {
        nearByNodes.push(node)
      }
      dom?.classList.remove(css.selected)
    }
 
    const links = this.getActiveLinkLayer().getLinks()
    const nearByLinks: DefaultLinkModel[] = []
    for (const key in links) {
      const link = links[key] as DefaultLinkModel
      const dom = document.querySelector(`[data-linkid="${link.getID()}"]`)
      if (link.getBoundingBox().containsPoint(position)) {
        nearByLinks.push(link)
      }
      dom?.classList.remove(css.selectedLink)
    }
    if (nearByNodes.length === 1) {
      return nearByNodes[0]
    } else if (nearByLinks.length === 1) {
      return nearByLinks[0]
    }
    return undefined
  }
 
  highlightNodesAndLink(position: Point): BaseModel | undefined {
    const nodeLink = this.getNodeLinkAtPosition(position)
    if (nodeLink instanceof DefaultNodeModel) {
      const dom = document.querySelector(`[data-nodeid="${nodeLink.getID()}"]`)
      dom?.classList.add(css.selected)
    } else if (nodeLink instanceof DefaultLinkModel) {
      const dom = document.querySelector(`[data-linkid="${nodeLink.getID()}"]`)
      dom?.classList.add(css.selectedLink)
    }
    return nodeLink
  }
 
  getGroupLayer(id: string): StepGroupNodeLayerModel | undefined {
    return this.stepGroupLayers.filter(layer => layer.getID() === id)[0]
  }
 
  getNodeFromId(id: string): DefaultNodeModel | undefined {
    let node: DefaultNodeModel | undefined = undefined
    this.layers.forEach(layer => {
      if (layer instanceof NodeLayerModel || layer instanceof StepGroupNodeLayerModel) {
        const nodes = layer.getNodes()
        if (nodes[id]) {
          node = nodes[id]
        }
      }
    })
    return node
  }
}