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

81.18% Statements 69/85
62.35% Branches 53/85
68% Functions 17/25
81.18% Lines 69/85

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            35x 35x 35x 35x                     35x 35x 35x 35x       35x 35x 35x 35x 35x   35x     58x       34x               34x   2x 1x 1x                 34x 2x   2x               34x 2x 1x   1x           34x                                 35x                   35x 34x 34x   34x 34x 34x 34x 34x 34x 34x 34x 34x   34x             34x 24x 24x   24x                                     34x 30x                         34x 23x 23x       23x       23x 23x   23x 18x 18x       34x 34x   34x                                                                                                                                                         35x   15x 15x                     15x         19x                     19x       35x 6x   6x            
/*
 * 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 { Link, useParams } from 'react-router-dom'
import cx from 'classnames'
import {
  Button,
  ButtonSize,
  ButtonVariation,
  ExpandingSearchInput,
  ExpandingSearchInputHandle,
  Icon,
  Text
} from '@wings-software/uicore'
import type { GroupedVirtuosoHandle, VirtuosoHandle } from 'react-virtuoso'
 
import routes from '@common/RouteDefinitions'
import { String as StrTemplate, useStrings } from 'framework/strings'
import { useExecutionContext } from '@pipeline/context/ExecutionContext'
import { useGlobalEventListener } from '@common/hooks'
import type { ConsoleViewStepDetailProps } from '@pipeline/factories/ExecutionFactory/types'
import type { ExecutionPageQueryParams } from '@pipeline/utils/types'
import type { ModulePathParams, ExecutionPathProps } from '@common/interfaces/RouteInterfaces'
import { addHotJarSuppressionAttribute } from '@common/utils/utils'
import { isExecutionComplete } from '@pipeline/utils/statusHelpers'
import { useLogsContent } from './useLogsContent'
import { GroupedLogsWithRef as GroupedLogs } from './components/GroupedLogs'
import { SingleSectionLogsWithRef as SingleSectionLogs } from './components/SingleSectionLogs'
import type { UseActionCreatorReturn } from './LogsState/actions'
import css from './LogsContent.module.scss'
 
function resolveCurrentStep(selectedStepId: string, queryParams: ExecutionPageQueryParams): string {
  return queryParams.retryStep ? queryParams.retryStep : selectedStepId
}
 
function isStepSelected(selectedStageId?: string, selectedStepId?: string): boolean {
  return !!(selectedStageId && selectedStepId)
}
 
function isPositiveNumber(index: unknown): index is number {
  return typeof index === 'number' && index >= 0
}
 
function handleKeyDown(actions: UseActionCreatorReturn) {
  return (e: React.KeyboardEvent<HTMLElement>): void => {
    /* istanbul ignore else */
    if (e.key === 'ArrowUp') {
      e.preventDefault()
      actions.goToPrevSearchResult()
    } else if (e.key === 'ArrowDown') {
      e.preventDefault()
      actions.goToNextSearchResult()
    }
  }
}
 
function getKeyDownListener(searchRef: React.MutableRefObject<ExpandingSearchInputHandle | undefined>) {
  return (e: KeyboardEvent) => {
    const isMetaKey = navigator.userAgent.includes('Mac') ? e.metaKey : e.ctrlKey
 
    Iif (e.key === 'f' && isMetaKey && searchRef.current) {
      e.preventDefault()
      searchRef.current.focus()
    }
  }
}
 
function handleSearchChange(actions: UseActionCreatorReturn) {
  return (term: string): void => {
    if (term) {
      actions.search(term)
    } else {
      actions.resetSearch()
    }
  }
}
 
function handleFullScreen(rootRef: React.MutableRefObject<HTMLDivElement | null>, isFullScreen: boolean) {
  return async (): Promise<void> => {
    if (!rootRef.current) {
      return
    }
 
    try {
      if (isFullScreen) {
        await document.exitFullscreen()
      } else {
        await rootRef.current.requestFullscreen()
      }
    } catch (_e) {
      // catch any errors and do nothing
    }
  }
}
 
const isDocumentFullScreen = (elem: HTMLDivElement | null): boolean =>
  !!(document.fullscreenElement && document.fullscreenElement === elem)
 
export interface LogsContentProps {
  mode: 'step-details' | 'console-view'
  toConsoleView?: string
  errorMessage?: string
  isWarning?: boolean
}
 
export function LogsContent(props: LogsContentProps): React.ReactElement {
  const { mode, toConsoleView = '', errorMessage, isWarning } = props
  const pathParams = useParams<ExecutionPathProps & ModulePathParams>()
  const { pipelineStagesMap, selectedStageId, allNodeMap, selectedStepId, pipelineExecutionDetail, queryParams } =
    useExecutionContext()
  const { state, actions } = useLogsContent()
  const { getString } = useStrings()
  const { linesWithResults, currentIndex } = state.searchData
  const searchRef = React.useRef<ExpandingSearchInputHandle>()
  const rootRef = React.useRef<HTMLDivElement | null>(null)
  const [isFullScreen, setIsFullScreen] = React.useState(false)
  const hasLogs = state.units.length > 0
  const isSingleSectionLogs = state.units.length === 1
 
  const virtuosoRef = React.useRef<null | GroupedVirtuosoHandle | VirtuosoHandle>(null)
 
  /* istanbul ignore next */
  function getSectionName(index: number): string {
    return getString('pipeline.logs.sectionName', { index })
  }
 
  React.useEffect(() => {
    const currentStepId1 = resolveCurrentStep(selectedStepId, queryParams)
    const selectedStep = allNodeMap[currentStepId1]
 
    actions.createSections({
      node: selectedStep,
      selectedStep: selectedStepId,
      selectedStage: selectedStageId,
      getSectionName
    })
    // eslint-disable-next-line react-hooks/exhaustive-deps
  }, [
    queryParams.retryStep,
    mode,
    selectedStepId,
    allNodeMap,
    pipelineStagesMap,
    selectedStageId,
    // eslint-disable-next-line react-hooks/exhaustive-deps
    pipelineExecutionDetail?.pipelineExecutionSummary?.runSequence
  ])
 
  // scroll to current search result
  React.useEffect(() => {
    const index = linesWithResults[currentIndex]
 
    /* istanbul ignore next */
    if (virtuosoRef.current && isPositiveNumber(index)) {
      virtuosoRef.current.scrollToIndex(index)
    }
  }, [currentIndex, linesWithResults])
 
  /* istanbul ignore next */
  useGlobalEventListener('keydown', getKeyDownListener(searchRef))
 
  // we need to update `isFullScreen` flag based on event,
  // as it can be changed via keyboard too
  React.useEffect(() => {
    const elem = rootRef.current
    const callback = (): void => {
      setIsFullScreen(isDocumentFullScreen(elem))
    }
 
    const errCallback = (): void => {
      setIsFullScreen(false)
    }
 
    elem?.addEventListener('fullscreenchange', callback)
    elem?.addEventListener('fullscreenerror', errCallback)
 
    return () => {
      elem?.removeEventListener('fullscreenchange', callback)
      elem?.removeEventListener('fullscreenerror', errCallback)
    }
  }, [])
 
  const currentStepId = resolveCurrentStep(selectedStepId, queryParams)
  const currentStep = allNodeMap[currentStepId]
 
  return (
    <div ref={rootRef} className={cx(css.main, { [css.hasErrorMessage]: !!errorMessage })} data-mode={mode}>
      <div className={css.header}>
        <StrTemplate
          tagName="div"
          stringID={mode === 'console-view' ? 'execution.consoleLogs' : 'execution.stepLogs'}
        />
        <div className={css.rhs} onKeyDown={handleKeyDown(actions)}>
          <ExpandingSearchInput
            onChange={handleSearchChange(actions)}
            ref={searchRef}
            showPrevNextButtons
            flip
            theme={'dark'}
            className={css.search}
            fixedText={`${Math.min(currentIndex + 1, linesWithResults.length)} / ${linesWithResults.length}`}
            onNext={/* istanbul ignore next */ () => actions.goToNextSearchResult()}
            onPrev={/* istanbul ignore next */ () => actions.goToPrevSearchResult()}
            onEnter={/* istanbul ignore next */ () => actions.goToNextSearchResult()}
          />
          <Button
            icon={isFullScreen ? 'full-screen-exit' : 'full-screen'}
            iconProps={{ size: 22 }}
            className={css.fullScreen}
            variation={ButtonVariation.ICON}
            withoutCurrentColor
            onClick={handleFullScreen(rootRef, isFullScreen)}
          />
          {isStepSelected(selectedStageId, currentStepId) && isExecutionComplete(currentStep?.status) ? (
            <Link
              className={css.newTab}
              to={routes.toPipelineLogs({
                stepIndentifier: currentStepId,
                stageIdentifier: selectedStageId,
                ...pathParams
              })}
              target="_blank"
              rel="noopener noreferer"
            >
              <Icon name="launch" size={16} />
            </Link>
          ) : null}
          {mode === 'step-details' ? (
            <Link className={css.toConsoleView} to={toConsoleView}>
              <StrTemplate stringID="consoleView" />
            </Link>
          ) : null}
        </div>
      </div>
      {hasLogs ? (
        isSingleSectionLogs ? (
          <SingleSectionLogs ref={virtuosoRef} state={state} actions={actions} />
        ) : (
          <GroupedLogs ref={virtuosoRef} state={state} actions={actions} />
        )
      ) : (
        <pre className={css.container} {...addHotJarSuppressionAttribute()}>
          <StrTemplate tagName="div" className={css.noLogs} stringID="common.logs.noLogsText" />
        </pre>
      )}
      {mode === 'console-view' && errorMessage ? (
        <div className={cx(css.errorMessage, { [css.isWarning]: isWarning })}>
          <StrTemplate className={css.summary} tagName="div" stringID="summary" />
          <div className={css.error}>
            <Icon name={isWarning ? 'warning-sign' : 'circle-cross'} />
            <Text lineClamp={1}>{errorMessage}</Text>
          </div>
        </div>
      ) : null}
    </div>
  )
}
 
export interface LogsContentState {
  hasError: boolean
}
 
export class LogsContentWithErrorBoundary extends React.Component<LogsContentProps, LogsContentState> {
  constructor(props: LogsContentProps) {
    super(props)
    this.state = { hasError: false }
  }
 
  static getDerivedStateFromError(): LogsContentState {
    return { hasError: true }
  }
 
  componentDidCatch(error: unknown): void {
    window?.bugsnagClient?.notify?.(error)
  }
 
  handleRetry = (): void => {
    this.setState({ hasError: false })
  }
 
  render(): React.ReactElement {
    Iif (this.state.hasError) {
      return (
        <div className={css.errorContainer}>
          <StrTemplate tagName="div" className={css.txt} stringID="pipeline.logs.errorText" />
          <Button onClick={this.handleRetry} variation={ButtonVariation.PRIMARY} size={ButtonSize.SMALL}>
            <StrTemplate stringID="pipeline.logs.retry" />
          </Button>
        </div>
      )
    }
 
    return <LogsContent {...this.props} />
  }
}
 
export function DefaultConsoleViewStepDetails(props: ConsoleViewStepDetailProps): React.ReactElement {
  const { errorMessage, isSkipped } = props
 
  return (
    <div className={css.logViewer}>
      <LogsContentWithErrorBoundary mode="console-view" errorMessage={errorMessage} isWarning={isSkipped} />
    </div>
  )
}