All files / modules/85-cv/components/CVSetupSourcesView/SetupSourceTabs SetupSourceTabs.tsx

94.55% Statements 104/110
86.08% Branches 68/79
93.33% Functions 28/30
96.04% Lines 97/101

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              48x 48x 48x   48x 48x 48x 48x 48x                                                                                               48x                         87x 87x 117x 117x     87x     48x 8x     2x   6x       48x 7x     2x   5x       48x 3x 1x     2x 4x 4x     2x 1x   1x     2x       3x 1x         2x 1x             1x     48x           3x             3x       3x   1x 1x   1x 1x   1x 1x     3x     48x         200x         200x 200x 200x   200x       200x 101x       7x   7x 2x 2x 1x 1x                             1x                 5x 5x 5x       5x 2x 2x 2x     3x 3x                         200x 85x 74x 3x 3x                   200x 85x     200x             2x 3x       48x 206x 200x     48x 209x 200x 200x 200x         200x 200x   200x         3x 3x             2x     350x                          
/*
 * 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, { createContext, useEffect, useMemo, useState } from 'react'
import { Container, Tab, Tabs } from '@wings-software/uicore'
import { useHistory, useParams } from 'react-router-dom'
import type { ProjectPathProps } from '@common/interfaces/RouteInterfaces'
import routes from '@common/RouteDefinitions'
import { getRoutePathByType } from '@cv/utils/routeUtils'
import { CVObjectStoreNames, useIndexedDBHook } from '@cv/hooks/IndexedDBHook/IndexedDBHook'
import { OnboardingEntites } from './SetupSourceTabs.constants'
import css from './SetupSourceTabs.module.scss'
 
type TabStatus = 'SUCCESS' | 'WARNING' | 'ERROR' | 'NO_STATUS'
 
type TabInfo = {
  tabStatus?: TabStatus
}
 
export interface SetupSourceTabsProps<T> {
  data: T
  children: JSX.Element[] | JSX.Element
  tabTitles: string[]
  determineMaxTab?: (data: T) => number
  disableCache?: boolean
}
 
export interface SetupSourceTabsProviderProps<T> {
  sourceData: T
  tabsInfo?: TabInfo[]
  onPrevious: (updatedData?: T, updatedTabInfo?: TabInfo) => Promise<void>
  onNext: (updatedData: T, updatedTabInfo?: TabInfo) => Promise<void>
  children: React.ReactNode
}
 
type CachedSourceObject = {
  type: string
  name: string
  identifier: string
  routeUrl: string
}
 
type CachedSetupObject = {
  setupID: string
  monitoringSources?: CachedSourceObject[]
  changeSources?: CachedSourceObject[]
  verificationJobs?: CachedSourceObject[]
}
 
type UseSetupSourceTabsHookReturnValues = {
  isInitializingDB: boolean
  sourceData: any
  tabsInfo: TabInfo[]
  activeTabIndex: number
  onSwitchTab: (updatedData: any, newTabIndex: number, updatedTabInfo?: TabInfo) => Promise<void>
  onPrevious: (updatedData?: any, updatedTabInfo?: TabInfo) => Promise<void>
  onNext: (updatedData: any, updatedTabInfo?: TabInfo) => Promise<void>
}
 
export const SetupSourceTabsContext = createContext<{
  tabsInfo?: TabInfo[]
  sourceData: any
  onNext: (updatedData: any, updatedTabInfo?: TabInfo) => Promise<void>
  onPrevious: (updatedData?: any, updatedTabInfo?: TabInfo) => Promise<void>
}>({
  tabsInfo: [],
  sourceData: {},
  onNext: () => Promise.resolve(),
  onPrevious: () => Promise.resolve()
})
 
function initializeTabsInfo(tabTitles: string[]): TabInfo[] {
  const tabsInfo: TabInfo[] = []
  tabTitles?.forEach(tabTitle => {
    Eif (tabTitle?.length) {
      tabsInfo.push({ tabStatus: 'NO_STATUS' })
    }
  })
  return tabsInfo
}
 
export function typeToSetupSourceType(type: any): string {
  switch (type) {
    case 'KUBERNETES':
    case 'HARNESS_CD10':
      return OnboardingEntites.CHANGE_SOURCE
    default:
      return OnboardingEntites.MONITORING_SOURCE
  }
}
 
export function getSetupSourceRoutingIndex(type: any): number {
  switch (type) {
    case 'KUBERNETES':
    case 'HARNESS_CD10':
      return 1
    default:
      return 2
  }
}
 
export function addItemToCache(sources: CachedSourceObject[], item: CachedSourceObject): CachedSourceObject[] {
  if (!sources?.length) {
    return [item]
  }
 
  const existingIndex = sources.findIndex(source => {
    Iif (!source.identifier) return
    return source.identifier === item.identifier
  })
 
  if (existingIndex !== -1) {
    sources[existingIndex] = item
  } else {
    sources.push(item)
  }
 
  return sources
}
 
function getRouteUrlForOnboarding(type: any, sourceType: string, identifier: string, params: ProjectPathProps): string {
  if (sourceType === OnboardingEntites.CHANGE_SOURCE) {
    return routes.toCVActivitySourceEditSetup({
      ...params,
      activitySource: getRoutePathByType(type),
      activitySourceId: identifier
    })
  } else if (sourceType === OnboardingEntites.MONITORING_SOURCE) {
    return routes.toCVAdminSetupMonitoringSourceEdit({
      ...params,
      monitoringSource: getRoutePathByType(type),
      identifier
    })
  }
 
  return ''
}
 
export function buildObjectToStore(
  data: any,
  savedData: CachedSetupObject,
  sourceType: string,
  params: ProjectPathProps
): CachedSetupObject {
  const dataToSave: CachedSourceObject = {
    type: data.type,
    name: data.monitoringSourceName || data.name,
    identifier: data.identifier,
    routeUrl: getRouteUrlForOnboarding(data.type, sourceType, data.identifier, params)
  }
 
  const objectToStore: CachedSetupObject = {
    ...savedData,
    setupID: `${params.accountId}-${params.orgIdentifier}-${params.projectIdentifier}`
  }
  switch (sourceType) {
    case OnboardingEntites.MONITORING_SOURCE:
      objectToStore.monitoringSources = addItemToCache(objectToStore.monitoringSources || [], dataToSave)
      break
    case OnboardingEntites.CHANGE_SOURCE:
      objectToStore.changeSources = addItemToCache(objectToStore.changeSources || [], dataToSave)
      break
    case OnboardingEntites.VERIFICATION_JOBS:
      objectToStore.verificationJobs = addItemToCache(objectToStore.verificationJobs || [], dataToSave)
      break
  }
 
  return objectToStore
}
 
export function useSetupSourceTabsHook<T>(
  data: T,
  tabsInformation: TabInfo[],
  disableCache = false
): UseSetupSourceTabsHookReturnValues {
  const [{ activeTabIndex, sourceData, tabsInfo }, setTabsState] = useState({
    activeTabIndex: 0,
    sourceData: data,
    tabsInfo: tabsInformation
  })
  const { projectIdentifier, orgIdentifier, accountId } = useParams<ProjectPathProps>()
  const history = useHistory()
  const indexedDBEntryKey = `${accountId}-${orgIdentifier}-${projectIdentifier}`
 
  const { isInitializingDB, dbInstance } = useIndexedDBHook({
    clearStroreList: [CVObjectStoreNames.ONBOARDING_SOURCES]
  })
 
  useEffect(() => {
    setTabsState(currentTabsState => ({ ...currentTabsState, tabsInfo: tabsInformation }))
  }, [tabsInfo])
 
  async function onSwitchTab<U>(updatedData: U, newTabIndex: number, updatedTabInfo?: TabInfo): Promise<void> {
    Iif (!dbInstance) return
 
    if (newTabIndex > tabsInfo.length - 1) {
      const setupSourceType = typeToSetupSourceType((updatedData as any).type as any)
      dbInstance.get(CVObjectStoreNames.SETUP, indexedDBEntryKey)?.then(async (savedData: CachedSetupObject) => {
        try {
          await Promise.all([
            dbInstance.put(
              CVObjectStoreNames.SETUP,
              buildObjectToStore(updatedData, savedData, setupSourceType, {
                projectIdentifier,
                orgIdentifier,
                accountId
              })
            ),
            dbInstance.clear(CVObjectStoreNames.ONBOARDING_SOURCES)
          ])
        } catch (e) {
          // eslint-disable-next-line no-console
          console.error(`IDBP, saving on last tab - `, e)
        }
        history.push(
          `${routes.toCVAdminSetup({
            accountId,
            projectIdentifier,
            orgIdentifier
          })}?step=${getSetupSourceRoutingIndex((updatedData as any).type as any)}`
        )
      })
    } else {
      setTabsState(currentState => {
        if (updatedTabInfo) currentState.tabsInfo[activeTabIndex] = updatedTabInfo
        return { activeTabIndex: newTabIndex, sourceData: updatedData as any, tabsInfo: [...currentState.tabsInfo] }
      })
 
      // on first page and hit previous, go back to previous page
      if (newTabIndex === -1) {
        dbInstance.clear(CVObjectStoreNames.ONBOARDING_SOURCES)
        history.goBack()
        return
      }
 
      try {
        await dbInstance.put(CVObjectStoreNames.ONBOARDING_SOURCES, {
          sourceID: indexedDBEntryKey,
          sourceData: updatedData,
          tabsInfo,
          currentTabIndex: newTabIndex
        })
      } catch (e) {
        // eslint-disable-next-line no-console
        console.error(`IDBP, saving on tab currentTabIndex: ${newTabIndex}`, e)
      }
    }
  }
 
  useEffect(() => {
    if (!isInitializingDB && dbInstance && !disableCache) {
      dbInstance.get(CVObjectStoreNames.ONBOARDING_SOURCES, indexedDBEntryKey)?.then(cachedData => {
        Eif (cachedData) {
          setTabsState({
            activeTabIndex: cachedData.currentTabIndex,
            sourceData: cachedData.sourceData,
            tabsInfo: cachedData.tabsInfo
          })
        }
      })
    }
  }, [isInitializingDB, dbInstance, indexedDBEntryKey])
 
  useEffect(() => {
    Eif (data) setTabsState(previousState => ({ ...previousState, tabsData: data }))
  }, [data])
 
  return {
    isInitializingDB,
    sourceData,
    tabsInfo,
    activeTabIndex,
    onSwitchTab,
    onPrevious: (updatedData, updatedTabInfo) =>
      onSwitchTab(updatedData || sourceData, activeTabIndex - 1, updatedTabInfo),
    onNext: (updatedData, updatedTabInfo) => onSwitchTab(updatedData, activeTabIndex + 1, updatedTabInfo)
  }
}
 
export function SetupSourceTabsProvider<T>(props: SetupSourceTabsProviderProps<T>): JSX.Element {
  const { children, ...restProps } = props
  return <SetupSourceTabsContext.Provider value={restProps}>{children}</SetupSourceTabsContext.Provider>
}
 
export function SetupSourceTabs<T>(props: SetupSourceTabsProps<T>): JSX.Element {
  const { data, tabTitles, children, determineMaxTab, disableCache } = props
  const [tabsLength, setTabsLength] = useState<number>(0)
  const tabInfo = useMemo(() => initializeTabsInfo(tabTitles), [tabTitles])
  const { sourceData, activeTabIndex, onSwitchTab, onNext, onPrevious } = useSetupSourceTabsHook(
    data,
    tabInfo,
    disableCache
  )
  const maxEnabledTab = determineMaxTab?.(sourceData)
  const updatedChildren = useMemo(() => (Array.isArray(children) ? children : [children]), [children])
 
  return (
    <SetupSourceTabsProvider
      sourceData={sourceData}
      onPrevious={onPrevious}
      onNext={async (updatedData: any, updatedTabInfo?: TabInfo | undefined) => {
        setTabsLength(tabsL => (tabsL > tabTitles.length ? tabTitles.length : tabsL + 1))
        await onNext(updatedData, updatedTabInfo)
      }}
    >
      <Container className={css.tabWrapper}>
        <Tabs
          id="setup-sources"
          selectedTabId={activeTabIndex}
          onChange={(newTabId: number) => onSwitchTab(sourceData, newTabId)}
        >
          {updatedChildren.map((child, index) => (
            <Tab
              key={tabTitles[index]}
              id={index}
              title={tabTitles[index]}
              disabled={index > (maxEnabledTab ? maxEnabledTab : tabsLength)}
              panel={child}
            />
          ))}
        </Tabs>
      </Container>
    </SetupSourceTabsProvider>
  )
}