All files / modules/70-pipeline/components/ExecutionStageDiagram ExecutionStageDiagram.tsx

86.49% Statements 96/111
68.37% Branches 67/98
93.55% Functions 29/31
85.98% Lines 92/107

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 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344              2x 2x 2x     2x 2x     2x           2x             2x 2x 2x             3x 3x 3x                 2x 2x 2x       2x   1x       2x   1x       2x   2x       2x   1x                                                                 2x                                               11x     10x           10x 10x 10x   10x                                 10x 4x             10x 4x 4x     10x 1x 1x 1x       1x         10x   4x             10x 10x 10x 10x     10x 4x 4x     4x           10x 4x 1x               4x 2x         4x       4x 4x       10x     1x 1x   1x 1x     1x 1x         1x 1x       1x   1x     10x 1x   1x 1x 1x       1x 1x 1x         10x 4x     10x 4x     10x 4x 4x       10x 10x                                                 10x 10x   10x       1x                 1x              
/*
 * 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 React from 'react'
import classNames from 'classnames'
import { noop, isNil, debounce } from 'lodash-es'
import type { NodeModelListener } from '@projectstorm/react-diagrams-core'
import type { BaseModelListener } from '@projectstorm/react-canvas-core'
import { GraphCanvasState, useExecutionContext } from '@pipeline/context/ExecutionContext'
import { useDeepCompareEffect, useUpdateQueryParams } from '@common/hooks'
import type { ExecutionPageQueryParams } from '@pipeline/utils/types'
import type { ExecutionPipeline, ExecutionPipelineGroupInfo, ExecutionPipelineItem } from './ExecutionPipelineModel'
import {
  ExecutionStageDiagramConfiguration,
  ExecutionStageDiagramModel,
  GridStyleInterface,
  NodeStyleInterface
} from './ExecutionStageDiagramModel'
import {
  focusRunningNode,
  getGroupsFromData,
  getStageFromDiagramEvent,
  GroupState,
  moveStageToFocusDelayed
} from './ExecutionStageDiagramUtils'
import { CanvasButtons, CanvasButtonsActions } from '../CanvasButtons/CanvasButtons'
import * as Diagram from '../Diagram'
import css from './ExecutionStageDiagram.module.scss'
 
abstract class ItemEvent<T> extends Event {
  readonly stage: ExecutionPipelineItem<T>
  readonly stageTarget: HTMLElement
 
  constructor(eventName: string, stage: ExecutionPipelineItem<T>, target: HTMLElement) {
    super(eventName)
    this.stage = stage
    this.stageTarget = target
  }
}
 
abstract class GroupEvent<T> extends Event {
  readonly group: ExecutionPipelineGroupInfo<T>
  readonly stageTarget: HTMLElement
 
  constructor(eventName: string, group: ExecutionPipelineGroupInfo<T>, target: HTMLElement) {
    super(eventName)
    this.group = group
    this.stageTarget = target
  }
}
 
export class ItemClickEvent<T> extends ItemEvent<T> {
  constructor(stage: ExecutionPipelineItem<T>, target: HTMLElement) {
    super('ItemClickEvent', stage, target)
  }
}
 
export class ItemMouseEnterEvent<T> extends ItemEvent<T> {
  constructor(stage: ExecutionPipelineItem<T>, target: HTMLElement) {
    super('ItemMouseEnterEvent', stage, target)
  }
}
 
export class GroupMouseEnterEvent<T> extends GroupEvent<T> {
  constructor(group: ExecutionPipelineGroupInfo<T>, target: HTMLElement) {
    super('GroupMouseEnterEvent', group, target)
  }
}
 
export class ItemMouseLeaveEvent<T> extends ItemEvent<T> {
  constructor(stage: ExecutionPipelineItem<T>, target: HTMLElement) {
    super('ItemMouseLeaveEvent', stage, target)
  }
}
 
export interface ExecutionStageDiagramProps<T> {
  /** pipeline definition */
  data: ExecutionPipeline<T>
  /** selected item id */
  selectedIdentifier: string // TODO: 1. add node style for each type/shape 2. add default value
  /** node style  */
  nodeStyle?: NodeStyleInterface
  /** grid style */
  gridStyle: GridStyleInterface
  graphConfiguration?: Partial<ExecutionStageDiagramConfiguration>
  loading?: boolean
  showStartEndNode?: boolean // Default: true
  showEndNode?: boolean // Default: true
  diagramContainerHeight?: number
  itemClickHandler?: (event: ItemClickEvent<T>) => void
  itemMouseEnter?: (event: ItemMouseEnterEvent<T>) => void
  itemMouseLeave?: (event: ItemMouseLeaveEvent<T>) => void
  mouseEnterStepGroupTitle?: (event: GroupMouseEnterEvent<T>) => void
  mouseLeaveStepGroupTitle?: (event: GroupMouseEnterEvent<T>) => void
  canvasListener?: (action: CanvasButtonsActions) => void
  isWhiteBackground?: boolean // Default: false
  className?: string
  canvasBtnsClass?: string
  graphCanvasState?: GraphCanvasState
  setGraphCanvasState?: (state: GraphCanvasState) => void
  disableCollapseButton?: boolean
  isStepView?: boolean
}
 
export default function ExecutionStageDiagram<T>(props: ExecutionStageDiagramProps<T>): React.ReactElement {
  const {
    data,
    className,
    selectedIdentifier,
    nodeStyle = { width: 50, height: 50 },
    graphConfiguration = {},
    gridStyle,
    diagramContainerHeight,
    showStartEndNode = true,
    showEndNode = true,
    itemClickHandler = noop,
    itemMouseEnter = noop,
    itemMouseLeave = noop,
    mouseEnterStepGroupTitle = noop,
    mouseLeaveStepGroupTitle = noop,
    canvasListener = noop,
    loading = false,
    isWhiteBackground = false,
    canvasBtnsClass = '',
    graphCanvasState,
    setGraphCanvasState,
    disableCollapseButton,
    isStepView = false
  } = props
 
  // eslint-disable-next-line react-hooks/exhaustive-deps
  const debounceSetGraphCanvasState = React.useCallback(
    debounce((values: GraphCanvasState) => {
      return setGraphCanvasState?.(values)
    }, 250),
    []
  )
  const { queryParams, selectedStageId, selectedStepId } = useExecutionContext()
  const { replaceQueryParams } = useUpdateQueryParams<ExecutionPageQueryParams>()
  const [autoPosition, setAutoPosition] = React.useState(true)
 
  const [groupState, setGroupState] = React.useState<Map<string, GroupState<T>>>()
 
  function stopAutoSelection(): void {
    // istanbul ignore else
    Iif (queryParams.stage && queryParams.step) {
      return
    }
    // istanbul ignore else
    Iif (selectedStageId && selectedStepId) {
      replaceQueryParams({
        ...queryParams,
        stage: selectedStageId,
        step: selectedStepId
      })
    }
  }
 
  React.useEffect(() => {
    Iif (isStepView) {
      engine.getModel().setZoomLevel(100)
      engine.zoomToFit()
    }
    // eslint-disable-next-line react-hooks/exhaustive-deps
  }, [selectedStageId, isStepView])
 
  useDeepCompareEffect(() => {
    const stageData = getGroupsFromData(data.items)
    setGroupState(stageData)
  }, [data])
 
  const updateGroupStage = (event: Diagram.DefaultNodeEvent): void => {
    const group = groupState?.get(event.entity.getIdentifier())
    Eif (group && groupState) {
      groupState?.set(event.entity.getIdentifier(), {
        ...group,
        collapsed: !group.collapsed
      })
      setGroupState(new Map([...groupState]))
    }
  }
 
  //setup the diagram engine
  const engine = React.useMemo(
    () =>
      Diagram.createEngine({
        registerDefaultZoomCanvasAction: false
      }),
    []
  )
 
  //setup the diagram model
  const model = React.useMemo(() => new ExecutionStageDiagramModel(), [])
  model.setDefaultNodeStyle(nodeStyle)
  model.setGraphConfiguration(graphConfiguration)
  model.setGridStyle(gridStyle)
 
  // Graph position and zoom set (set values from context)
  React.useEffect(() => {
    const { offsetX, offsetY, zoom } = graphCanvasState || {}
    Iif (!isNil(offsetX) && offsetX !== model.getOffsetX() && !isNil(offsetY) && offsetY !== model.getOffsetY()) {
      model.setOffset(offsetX, offsetY)
    }
    Iif (!isNil(zoom) && zoom !== model.getZoomLevel()) {
      model.setZoomLevel(zoom)
    }
  }, [graphCanvasState, model])
 
  // Graph position and zoom change - event handling (update context value)
  React.useEffect(() => {
    const offsetUpdateHandler = function (event: any): void {
      Iif (graphCanvasState) {
        graphCanvasState.offsetX = event.offsetX
        graphCanvasState.offsetY = event.offsetY
        debounceSetGraphCanvasState({
          ...graphCanvasState
        })
      }
    }
    const zoomUpdateHandler = function (event: any): void {
      Iif (graphCanvasState) {
        graphCanvasState.zoom = event.zoom
        debounceSetGraphCanvasState({ ...graphCanvasState })
      }
    }
    const listenerHandle = model.registerListener({
      [Diagram.Event.OffsetUpdated]: offsetUpdateHandler,
      [Diagram.Event.ZoomUpdated]: zoomUpdateHandler
    })
    return () => {
      model.deregisterListener(listenerHandle)
    }
  }, [model])
 
  const nodeListeners: NodeModelListener = {
    // eslint-disable-next-line @typescript-eslint/no-explicit-any
    [Diagram.Event.ClickNode]: (event: any) => {
      /* istanbul ignore else */ if (autoPosition) {
        setAutoPosition(false)
      }
      const group = groupState?.get(event.entity.getIdentifier())
      Iif (group && group.collapsed) {
        updateGroupStage(event)
      } else {
        const stage = getStageFromDiagramEvent(event, data)
        /* istanbul ignore else */ if (stage) itemClickHandler(new ItemClickEvent(stage, event.target))
      }
    },
    // eslint-disable-next-line @typescript-eslint/no-explicit-any
    [Diagram.Event.MouseEnterNode]: (event: any) => {
      const stage = getStageFromDiagramEvent(event, data)
      /* istanbul ignore else */ if (stage) itemMouseEnter(new ItemMouseEnterEvent(stage, event.target))
    },
    // eslint-disable-next-line @typescript-eslint/no-explicit-any
    [Diagram.Event.MouseLeaveNode]: (event: any) => {
      const stage = getStageFromDiagramEvent(event, data)
      // dynamicPopoverHandler?.hide()
      /* istanbul ignore else */ if (stage) itemMouseLeave(new ItemMouseLeaveEvent(stage, event.target))
    }
  }
  const layerListeners: BaseModelListener = {
    [Diagram.Event.StepGroupCollapsed]: (event: any) => updateGroupStage(event),
    [Diagram.Event.MouseEnterStepGroupTitle]: (event: any) => {
      const groupData = groupState?.get(event.entity.getIdentifier())
      Eif (groupData?.group) {
        mouseEnterStepGroupTitle(new GroupMouseEnterEvent(groupData?.group, event.target))
      }
    },
    [Diagram.Event.MouseLeaveStepGroupTitle]: (event: any) => {
      const groupData = groupState?.get(event.entity.getIdentifier())
      Eif (groupData?.group) {
        mouseLeaveStepGroupTitle(new GroupMouseEnterEvent(groupData?.group, event.target))
      }
    }
  }
 
  React.useEffect(() => {
    setAutoPosition(true)
  }, [data.identifier])
 
  React.useEffect(() => {
    moveStageToFocusDelayed(engine, selectedIdentifier, true)
  }, [selectedIdentifier])
 
  React.useEffect(() => {
    model.clearAllNodesAndLinks()
    engine.repaintCanvas()
    // eslint-disable-next-line react-hooks/exhaustive-deps
  }, [data.identifier])
 
  React.useEffect(() => {
    !loading &&
      model.addUpdateGraph(
        data,
        { nodeListeners: nodeListeners, linkListeners: {}, layerListeners },
        selectedIdentifier,
        diagramContainerHeight,
        showStartEndNode,
        showEndNode,
        groupState,
        disableCollapseButton
      )
  }, [
    data,
    diagramContainerHeight,
    groupState,
    layerListeners,
    loading,
    model,
    nodeListeners,
    selectedIdentifier,
    showStartEndNode,
    showEndNode
  ])
 
  //Load model into engine
  engine.setModel(model)
  autoPosition && focusRunningNode(engine, data)
 
  return (
    <div
      className={classNames(css.main, { [css.whiteBackground]: isWhiteBackground }, className)}
      onMouseDown={() => {
        setAutoPosition(false)
      }}
      onClick={stopAutoSelection}
    >
      <Diagram.CanvasWidget engine={engine} className={css.canvas} />
      <CanvasButtons
        engine={engine}
        className={canvasBtnsClass}
        callback={action => {
          canvasListener(action)
        }}
        tooltipPosition="right"
      />
    </div>
  )
}