All files / modules/85-cv/components/MetricDashboardWidgetNav MetricDashboardWidgetNav.tsx

79.19% Statements 137/173
67.74% Branches 210/310
82.61% Functions 19/23
79.52% Lines 132/166

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 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 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 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 477 478 479              25x 25x 25x 25x 25x 25x 25x 25x 25x 25x       25x                 25x   25x         25x           25x                 25x                                                 94x       2x       2x 2x 2x 4x 4x 2x           246x   103x                     20x                     26x                     94x                                               3x                               94x   94x 103x 103x         94x     94x 2x 2x       94x 89x 89x   5x 1x 1x     94x               10x       10x 10x 10x 10x 23x 23x 3x     20x             20x 26x 26x       26x         26x 10x 10x 10x   26x     20x     10x       67x 67x                         25x                     94x   94x 94x     94x 94x 103x   94x 94x 94x 94x     94x   94x 13x       28x           94x 24x 13x 2x   11x 1x 1x 1x 1x 1x   10x         10x 10x 10x 10x 10x 10x 10x               10x                           94x 47x 42x                             94x 13x 1x               94x     1x                                                 1x 1x 1x                                               1x     1x 1x 1x 1x               1x       1x               1x 1x 1x 3x   1x 1x 1x 1x 1x   1x 1x 1x   1x            
/*
 * Copyright 2022 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, { useEffect, useMemo, useState } from 'react'
import { Container, Link, Text, Utils } from '@wings-software/uicore'
import { Color } from '@harness/design-system'
import { Classes, ITreeNode, PopoverInteractionKind, Tree } from '@blueprintjs/core'
import { useParams } from 'react-router-dom'
import cx from 'classnames'
import { useToaster } from '@common/exports'
import { getErrorMessage } from '@cv/utils/CommonUtils'
import { String, useStrings } from 'framework/strings'
import {
  MANUAL_INPUT_QUERY,
  ManualInputQueryModal
} from '@cv/pages/health-source/connectors/GCOMetricsHealthSource/components/ManualInputQueryModal/ManualInputQueryModal'
import { PageSpinner } from '@common/components'
import type { ProjectPathProps } from '@common/interfaces/RouteInterfaces'
import type {
  MetricDashboardItem,
  MetricDashboardWidgetNavProps,
  MetricWidget,
  NodeDataType,
  TreeNodeLabelProps
} from '@cv/components/MetricDashboardWidgetNav/MetricDashboardWidgetNav.type'
import css from '@cv/components/MetricDashboardWidgetNav/MetricDashboardWidgetNav.module.scss'
 
const NodeDepth = {
  METRIC: 3,
  WIDGET: 2,
  DASHBOARD: 1
}
const LabelWidth = {
  FIRST_LEVEL: 192,
  SECOND_LEVEL: 170,
  THIRD_LEVEL: 140
}
 
const NodeType = {
  MANUAL_INPUT_METRIC: 'ManuallyInputQueryMetric',
  MANUAL_INPUT_QUERY: 'ManuualyInputQuery',
  DASHBOARD: 'Dashboard',
  WIDGET: 'Widget',
  METRIC: 'Metric',
  LABEL: 'Label'
}
 
const LoadingSkeleton = [
  {
    id: 1,
    isExpanded: true,
    disabled: true,
    label: <Container className={Classes.SKELETON} width={177} height={15} />,
    childNodes: [
      { id: 2, label: <Container className={Classes.SKELETON} width={155} height={15} /> },
      { id: 3, label: <Container className={Classes.SKELETON} width={155} height={15} /> },
      {
        id: 4,
        label: <Container className={Classes.SKELETON} width={155} height={15} />
      }
    ]
  },
  {
    id: 2,
    isExpanded: false,
    disabled: true,
    label: <Container className={Classes.SKELETON} width={177} height={15} />,
    hasCaret: true
  }
]
 
function initializeSelectedMetric(dashboardWidgetItems?: MetricDashboardItem[]): number[] | undefined {
  return dashboardWidgetItems?.length ? [1, 0, 0] : [0, 0]
}
 
function deselectMetric(navContent: ITreeNode[], nodePath?: number[]): void {
  Iif (!nodePath?.length) {
    return
  }
 
  let currNode = navContent[nodePath[0]]
  navContent[nodePath[0]] = currNode
  for (let pathIndex = 1; pathIndex < nodePath.length; pathIndex++) {
    currNode = currNode.childNodes?.[nodePath[pathIndex]] || ({} as ITreeNode)
    if (currNode && pathIndex === nodePath.length - 1) {
      currNode.isSelected = false
    }
  }
}
 
function generateTreeNode(type: string, data: any, id: string, isExpanded = false): ITreeNode<NodeDataType> {
  switch (type) {
    case NodeType.DASHBOARD:
      return {
        id,
        hasCaret: true,
        label: <TreeNodeLabel width={LabelWidth.FIRST_LEVEL} label={data.name} />,
        childNodes: [],
        nodeData: {
          data,
          type: NodeType.DASHBOARD
        }
      }
    case NodeType.WIDGET:
      return {
        id: id,
        hasCaret: true,
        isExpanded: isExpanded,
        label: <TreeNodeLabel width={LabelWidth.SECOND_LEVEL} label={id} />,
        childNodes: [],
        nodeData: {
          type: NodeType.WIDGET
        }
      }
    case NodeType.METRIC:
      return {
        id: id,
        label: <TreeNodeLabel width={LabelWidth.THIRD_LEVEL} label={data.metric} />,
        hasCaret: false,
        isExpanded: false,
        nodeData: {
          data,
          type: NodeType.METRIC
        }
      }
    case NodeType.MANUAL_INPUT_QUERY:
      return {
        id: MANUAL_INPUT_QUERY,
        hasCaret: true,
        label: (
          <TreeNodeLabel
            width={LabelWidth.FIRST_LEVEL}
            label={<String stringID="cv.monitoringSources.gco.mapMetricsToServicesPage.manuallyInputQueriesLabel" />}
          />
        ),
        childNodes: [],
        nodeData: {
          type: NodeType.MANUAL_INPUT_QUERY
        }
      }
    case NodeType.LABEL:
      return {
        id: id,
        label: <TreeNodeLabel width={LabelWidth.SECOND_LEVEL} label={data.label} />,
        hasCaret: false,
        isExpanded: false,
        isSelected: false
      }
    case NodeType.MANUAL_INPUT_METRIC:
    default:
      return {
        id,
        hasCaret: false,
        label: <TreeNodeLabel width={LabelWidth.SECOND_LEVEL} label={id} />,
        childNodes: [],
        nodeData: {
          type: NodeType.MANUAL_INPUT_METRIC
        }
      }
  }
}
 
function transformDashboardsToTreeNodes(
  dashboardWidgetItems: MetricDashboardItem[],
  manuallyInputQueries: string[]
): ITreeNode<NodeDataType>[] {
  const treeNodes: ITreeNode<NodeDataType>[] = []
 
  for (const dashboard of dashboardWidgetItems || []) {
    Eif (dashboard?.title && dashboard.itemId) {
      treeNodes.push(generateTreeNode(NodeType.DASHBOARD, { name: dashboard.title }, dashboard.itemId))
    }
  }
 
  // create manually input queries tree node
  treeNodes.unshift(generateTreeNode(NodeType.MANUAL_INPUT_QUERY, undefined, MANUAL_INPUT_QUERY))
 
  // insert all manual metrics into manually input queries node
  for (const metric of manuallyInputQueries || []) {
    Eif (metric) {
      treeNodes[0]?.childNodes?.push(generateTreeNode(NodeType.MANUAL_INPUT_METRIC, undefined, metric))
    }
  }
 
  if (treeNodes[1]) {
    treeNodes[1].isExpanded = true
    treeNodes[1].childNodes = LoadingSkeleton
    // when there are no selected dashboards and only a manual query
  } else if (treeNodes[0].childNodes?.length) {
    treeNodes[0].childNodes[0].isSelected = true
    treeNodes[0].isExpanded = true
  }
 
  return treeNodes
}
 
function transformWidgetsToTreeNodes(
  metricWidgets: MetricWidget[],
  isFirstLoad: boolean,
  dashboardIndex: number
): { treeNodes: ITreeNode<NodeDataType>[]; selectedMetricPath?: number[]; selectedMetric?: ITreeNode<NodeDataType> } {
  Iif (!metricWidgets?.length) {
    return { treeNodes: [] }
  }
 
  const treeNodes: ITreeNode<NodeDataType>[] = []
  let selectedMetricPath: number[] = []
  let selectedMetric: ITreeNode<NodeDataType> = {} as ITreeNode<NodeDataType>
  for (let widgetIndex = 0; widgetIndex < metricWidgets.length; widgetIndex++) {
    const widget = metricWidgets[widgetIndex]
    if (!widget || !widget.widgetName || !widget.dataSets?.length) {
      continue
    }
 
    const treeNode: ITreeNode<NodeDataType> = generateTreeNode(
      NodeType.WIDGET,
      undefined,
      widget.widgetName,
      widgetIndex === 0
    )
 
    for (let dataSetIndex = 0; dataSetIndex < widget.dataSets.length; dataSetIndex++) {
      const dataSet = widget.dataSets[dataSetIndex]
      Iif (!dataSet || !dataSet.name || !dataSet.query) {
        continue
      }
 
      const metric: ITreeNode<NodeDataType> = generateTreeNode(
        NodeType.METRIC,
        { metric: dataSet.name, widget: widget.widgetName, query: dataSet.query },
        dataSet.id
      )
      if (isFirstLoad && dataSetIndex === 0 && widgetIndex === 0) {
        metric.isSelected = true
        selectedMetricPath = [dashboardIndex, 0, 0]
        selectedMetric = metric
      }
      treeNode.childNodes?.push(metric)
    }
 
    treeNodes.push(treeNode)
  }
 
  return { treeNodes, selectedMetricPath, selectedMetric }
}
 
function TreeNodeLabel(props: TreeNodeLabelProps): JSX.Element {
  const { width, label } = props
  return (
    <Text
      color={Color.BLACK}
      width={width}
      lineClamp={1}
      className={css.textOverflow}
      tooltipProps={{ interactionKind: PopoverInteractionKind.HOVER_TARGET_ONLY }}
    >
      {label}
    </Text>
  )
}
 
export default function MetricDashboardWidgetNav<T>(props: MetricDashboardWidgetNavProps<T>): JSX.Element {
  const {
    className,
    connectorIdentifier,
    dashboards,
    onSelectMetric,
    showSpinnerOnLoad,
    manuallyInputQueries = [],
    dashboardWidgetMapper,
    dashboardDetailsRequest,
    addManualQueryTitle
  } = props
 
  const { projectIdentifier, accountId, orgIdentifier } = useParams<ProjectPathProps>()
  const [selectedMetricPath, setSelectedMetricPath] = useState<number[] | undefined>(
    initializeSelectedMetric(dashboards)
  )
  const [isFirstLoad, setIsFirstLoad] = useState(true)
  const [selectedDashboard, setSelectedDashboard] = useState<MetricDashboardItem | undefined>(
    dashboards?.filter(dashboard => dashboard?.itemId && dashboard.title)[0]
  )
  const { getString } = useStrings()
  const { showError } = useToaster()
  const [isModalOpen, setIsModalOpen] = useState(false)
  const [navContent, setNavContent] = useState<ITreeNode<NodeDataType>[]>(
    transformDashboardsToTreeNodes(dashboards, manuallyInputQueries)
  )
  const { error, loading, data: dashboardWidgetsData, refetch: fetchDetails } = dashboardDetailsRequest
 
  const metricWidgets: MetricWidget[] = useMemo(() => {
    return (
      (dashboardWidgetsData?.data &&
        Array.isArray(dashboardWidgetsData.data) &&
        dashboardWidgetsData.data.map((widgetToMap: any) => {
          return dashboardWidgetMapper(selectedDashboard?.itemId || '', widgetToMap)
        })) ||
      []
    )
  }, [dashboardWidgetsData, dashboardWidgetMapper])
 
  useEffect(() => {
    const selectedDashIndex = navContent.findIndex(treeNode => treeNode.id === selectedDashboard?.itemId)
    if (selectedDashIndex === -1 || loading) {
      return
    }
    if (error?.data) {
      navContent[selectedDashIndex].isExpanded = false
      navContent[selectedDashIndex].childNodes = []
      setNavContent([...navContent])
      Eif (error?.data) {
        showError(getErrorMessage(error), 5000)
      }
    } else Eif (metricWidgets.length) {
      const {
        treeNodes,
        selectedMetricPath: metricPath,
        selectedMetric: metric
      } = transformWidgetsToTreeNodes(metricWidgets, isFirstLoad, selectedDashIndex)
      navContent[selectedDashIndex].childNodes = treeNodes
      setNavContent([...navContent])
      const { data: datum } = metric?.nodeData || {}
      Eif (isFirstLoad) {
        setSelectedMetricPath(metricPath)
        onSelectMetric(
          metric?.id as string,
          metric?.nodeData?.data?.metric,
          datum?.query,
          datum?.widget,
          selectedDashboard?.itemId,
          selectedDashboard?.title as string
        )
        setIsFirstLoad(false)
      }
    } else if (dashboardWidgetsData?.data && !metricWidgets.length) {
      navContent[selectedDashIndex].childNodes = [
        generateTreeNode(
          NodeType.LABEL,
          { label: getString('cv.monitoringSources.datadog.noMetricsWidgets') },
          'no_data_label_id'
        )
      ]
      setNavContent([...navContent])
    }
  }, [metricWidgets, loading])
 
  useEffect(() => {
    if (selectedDashboard?.itemId) {
      fetchDetails({
        queryParams: {
          projectIdentifier,
          orgIdentifier,
          accountId,
          connectorIdentifier,
          tracingId: Utils.randomId(),
          dashboardId: selectedDashboard.itemId,
          path: selectedDashboard.itemId
        }
      })
    }
  }, [selectedDashboard?.itemId, projectIdentifier, orgIdentifier, accountId, connectorIdentifier, fetchDetails])
 
  // when only manually input query is selected on load, run this hook
  useEffect(() => {
    if (!loading && isFirstLoad && selectedMetricPath?.toString() === '0,0' && navContent[0]?.childNodes?.[0]) {
      onSelectMetric(
        navContent[0]?.childNodes?.[0]?.id as string,
        navContent[0]?.childNodes?.[0]?.id as string,
        MANUAL_INPUT_QUERY
      )
    }
  }, [])
 
  return (
    <Container width={300} className={cx(css.main, className)}>
      {loading && showSpinnerOnLoad && <PageSpinner />}
      <Link withoutHref onClick={() => setIsModalOpen(true)} className={css.inputQueryLink}>
        {getString('cv.monitoringSources.gco.addManualInputQuery')}
      </Link>
      <Tree
        className={css.treeNodeContainer}
        contents={navContent}
        onNodeExpand={(node, nodePath) => {
          const { type, data: datum } = node.nodeData || {}
          if (
            nodePath.length === NodeDepth.DASHBOARD &&
            !node.childNodes?.length &&
            type !== NodeType.MANUAL_INPUT_QUERY
          ) {
            navContent.forEach(dashboard => (dashboard.isExpanded = false))
            node.childNodes = LoadingSkeleton
            setSelectedDashboard({ title: datum.name, itemId: node.id as string })
          }
          node.isExpanded = true
          setNavContent([...navContent])
        }}
        onNodeCollapse={node => {
          node.isExpanded = false
          setNavContent([...navContent])
        }}
        onNodeClick={(node, nodePath) => {
          const { isExpanded = false, id, childNodes, nodeData } = node
          const { data: datum, type } = nodeData || {}
          switch (nodePath.length) {
            case NodeDepth.DASHBOARD:
              navContent.forEach(dashboard => (dashboard.isExpanded = false))
              node.isExpanded = !isExpanded
              if (type !== NodeType.MANUAL_INPUT_QUERY && node.isExpanded && !childNodes?.length) {
                node.childNodes = LoadingSkeleton
                setSelectedDashboard({ title: nodeData?.data.name as string, itemId: id as string })
              }
              break
            case NodeDepth.WIDGET:
              if (nodePath.toString() === selectedMetricPath?.toString()) {
                return
              }
              if (type === NodeType.MANUAL_INPUT_METRIC) {
                node.isSelected = true
                deselectMetric(navContent, selectedMetricPath)
                setSelectedMetricPath(nodePath)
                setSelectedDashboard(undefined)
                onSelectMetric(node.id as string, node.id as string, MANUAL_INPUT_QUERY)
              } else {
                node.isExpanded = !isExpanded
              }
              break
            case NodeDepth.METRIC:
              Iif (nodePath.toString() === selectedMetricPath?.toString()) {
                return
              }
              node.isSelected = true
              deselectMetric(navContent, selectedMetricPath)
              setSelectedMetricPath(nodePath)
              onSelectMetric(
                id as string,
                datum.metric,
                datum.query,
                datum.widget,
                selectedDashboard?.itemId,
                selectedDashboard?.title as string
              )
              break
            default:
              break
          }
          setNavContent([...navContent])
        }}
      />
      {isModalOpen && (
        <ManualInputQueryModal
          title={addManualQueryTitle}
          manuallyInputQueries={manuallyInputQueries}
          onSubmit={values => {
            Eif (navContent.length > 0) {
              deselectMetric(navContent, selectedMetricPath)
              setSelectedDashboard(undefined)
              navContent.forEach(dashboard => (dashboard.isExpanded = false))
            }
            Eif (navContent[0]?.nodeData?.type === NodeType.MANUAL_INPUT_QUERY) {
              const newMetric = generateTreeNode(NodeType.MANUAL_INPUT_METRIC, undefined, values.metricName)
              newMetric.isSelected = true
              navContent[0].childNodes?.unshift(newMetric)
              navContent[0].isExpanded = true
            }
            setNavContent([...navContent])
            setSelectedMetricPath([0, 0])
            onSelectMetric(values.metricName, values.metricName, MANUAL_INPUT_QUERY)
          }}
          closeModal={() => setIsModalOpen(false)}
        />
      )}
    </Container>
  )
}