All files / modules/10-common/components/MultiSelectEntityReference MultiSelectEntityReference.tsx

82.17% Statements 106/129
75.73% Branches 78/103
74.19% Functions 23/31
82.03% Lines 105/128

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              625x 625x 625x                         625x 625x 625x 625x     625x 625x                               625x 3x   3x     3x                                                                                           625x               625x 24x             625x     25x                             24x 24x 24x     24x 24x 24x 24x 24x   24x 24x 2x 2x 2x 1x         2x 3x   2x   24x 6x 2x 2x 2x 2x 2x 2x         1x 1x       2x 1x   2x     24x 4x 1x 1x 1x 1x   1x     24x               24x 4x 4x 4x 4x 4x 2x 2x                 2x       24x 4x     24x         24x       24x 24x 24x 24x       24x           24x 2x 2x 2x               2x             24x   14x 6x           14x             14x 4x     18x 12x   18x                 2x                           14x 4x           14x     24x 24x     24x     24x             72x 72x 10x                             72x                                 24x 2x         2x         2x                 24x                                                                                                    
/*
 * 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, { useState, useEffect, useCallback, useRef } from 'react'
import cx from 'classnames'
import {
  Container,
  TextInput,
  Button,
  Layout,
  Text,
  Tabs,
  Tab,
  Icon,
  IconName,
  Checkbox,
  PageError
} from '@wings-software/uicore'
import { Color } from '@harness/design-system'
import { debounce, isEmpty, isEqual } from 'lodash-es'
import { Scope } from '@common/interfaces/SecretsInterface'
import { useStrings } from 'framework/strings'
import type { StringKeys } from 'framework/strings'
import type { EntityReferenceResponse } from '../EntityReference/EntityReference'
import { disableItems } from './utils'
import css from './MultiSelectEntityReference.module.scss'
 
export interface Identifier {
  identifier: string
}
export interface ScopedObjectDTO extends Identifier {
  accountIdentifier?: string
  orgIdentifier?: string
  projectIdentifier?: string
}
export interface ScopeUpdatedWithPreviousData {
  [Scope.ACCOUNT]: boolean
  [Scope.ORG]: boolean
  [Scope.PROJECT]: boolean
}
 
export function getScopeFromDTO<T extends ScopedObjectDTO>(obj: T): Scope {
  Iif (obj.projectIdentifier) {
    return Scope.PROJECT
  } else Iif (obj.orgIdentifier) {
    return Scope.ORG
  }
  return Scope.ACCOUNT
}
 
export type ScopeAndIdentifier = {
  scope: Scope
  identifier: string
}
type CheckedItemsData<T> = {
  items: T[]
  scopedItemsTotal: number
  updatedWithOldData: boolean
}
 
type CheckedItems<T> = {
  [Scope.PROJECT]: CheckedItemsData<T>
  [Scope.ORG]: CheckedItemsData<T>
  [Scope.ACCOUNT]: CheckedItemsData<T>
  total: number
}
 
type SelectDTO<T> = {
  selectedData: T[]
  previousSelectedItemsUuidAndScope: ScopeAndIdentifier[] | undefined
  scopesUpdatedWithPreviousData: ScopeUpdatedWithPreviousData
}
 
export interface MultiSelectEntityReferenceProps<T> {
  fetchRecords: (
    scope: Scope,
    searchTerm: string | undefined,
    done: (records: EntityReferenceResponse<T>[]) => void
  ) => void
  recordRender: (args: { item: EntityReferenceResponse<T>; selectedScope: Scope; selected?: boolean }) => JSX.Element
  recordClassName?: string
  className?: string
  projectIdentifier?: string
  noRecordsText?: string
  orgIdentifier?: string
  defaultScope?: Scope
  searchInlineComponent?: JSX.Element
  selectedItemsUuidAndScope?: ScopeAndIdentifier[]
  onMultiSelect: (payLoad: ScopeAndIdentifier[]) => void
  onlyCurrentScope?: boolean
  disablePreSelectedItems?: boolean
}
 
export function getDefaultScope(orgIdentifier?: string, projectIdentifier?: string): Scope {
  if (!isEmpty(projectIdentifier)) {
    return Scope.PROJECT
  } else if (!isEmpty(orgIdentifier)) {
    return Scope.ORG
  }
  return Scope.ACCOUNT
}
const intializeCheckedList = () => {
  return {
    [Scope.PROJECT]: { items: [], scopedItemsTotal: 0, updatedWithOldData: false },
    [Scope.ORG]: { items: [], scopedItemsTotal: 0, updatedWithOldData: false },
    [Scope.ACCOUNT]: { items: [], scopedItemsTotal: 0, updatedWithOldData: false },
    total: 0
  }
}
export function MultiSelectEntityReference<T extends Identifier>(
  props: MultiSelectEntityReferenceProps<T>
): JSX.Element {
  const { getString } = useStrings()
  const {
    defaultScope,
    projectIdentifier,
    orgIdentifier,
    fetchRecords,
    className = '',
    recordRender,
    recordClassName = '',
    noRecordsText = getString('entityReference.noRecordFound'),
    searchInlineComponent,
    selectedItemsUuidAndScope,
    disablePreSelectedItems = false,
    onMultiSelect,
    onlyCurrentScope
  } = props
  const [searchTerm, setSearchTerm] = useState<string | undefined>()
  const [selectedScope, setSelectedScope] = useState<Scope>(
    defaultScope || getDefaultScope(orgIdentifier, projectIdentifier)
  )
  const [data, setData] = useState<EntityReferenceResponse<T>[]>([])
  const [loading, setLoading] = useState<boolean>(false)
  const [error, setError] = useState<string | null>()
  const [selectedRecord, setSelectedRecord] = useState<T>()
  const [renderedList, setRenderedList] = useState<JSX.Element>()
 
  const [checkedItems, setCheckedItems] = useState<CheckedItems<T>>(intializeCheckedList())
  const getScopeAndUuidFromSelectDTO = (onSelectDTO: SelectDTO<T>): ScopeAndIdentifier[] => {
    const scopeAndUuidArray: ScopeAndIdentifier[] = []
    Eif (onSelectDTO?.scopesUpdatedWithPreviousData) {
      onSelectDTO.previousSelectedItemsUuidAndScope?.forEach((el: ScopeAndIdentifier) => {
        Iif (!onSelectDTO.scopesUpdatedWithPreviousData[el.scope]) {
          scopeAndUuidArray.push(el)
        }
      })
    }
    onSelectDTO?.selectedData.forEach(el => {
      scopeAndUuidArray.push({ scope: getScopeFromDTO(el), identifier: el.identifier })
    })
    return scopeAndUuidArray
  }
  useEffect(() => {
    if (selectedItemsUuidAndScope && data) {
      const tempCheckedItems: CheckedItems<T> = checkedItems
      let isItemListUpdated = false
      selectedItemsUuidAndScope.forEach(el => {
        Eif (el.scope === selectedScope) {
          const item = data.find(_el => _el.identifier === el.identifier)?.record
          if (
            item &&
            tempCheckedItems[el.scope].items.findIndex(_el => _el.identifier === item.identifier) === -1 &&
            !tempCheckedItems[el.scope].updatedWithOldData
          ) {
            tempCheckedItems[el.scope].items.push(item)
            isItemListUpdated = true
          }
        }
      })
      if (isItemListUpdated) {
        tempCheckedItems[selectedScope].updatedWithOldData = isItemListUpdated
      }
      setCheckedItems(tempCheckedItems)
    }
  }, [data])
  useEffect(() => {
    if (selectedItemsUuidAndScope) {
      const tempCheckedItems: CheckedItems<T> = checkedItems
      selectedItemsUuidAndScope.forEach(el => {
        tempCheckedItems[el.scope].scopedItemsTotal++
        tempCheckedItems.total++
      })
      setCheckedItems(tempCheckedItems)
    }
  }, [selectedItemsUuidAndScope])
  const delayedFetchRecords = useRef(
    debounce((scope: Scope, search: string | undefined, done: (records: EntityReferenceResponse<T>[]) => void) => {
      setLoading(true)
      setSelectedRecord(undefined)
      fetchRecords(scope, search, done)
    }, 300)
  ).current
 
  const fetchData = useCallback(() => {
    try {
      setError(null)
      Eif (!searchTerm) {
        setLoading(true)
        fetchRecords(selectedScope, searchTerm, records => {
          setData(records)
          setLoading(false)
        })
      } else {
        delayedFetchRecords(selectedScope, searchTerm, records => {
          setData(records)
          setLoading(false)
        })
      }
    } catch (msg) {
      setError(msg)
    }
  }, [selectedScope, delayedFetchRecords, searchTerm, searchInlineComponent])
 
  useEffect(() => {
    fetchData()
  }, [fetchData])
 
  const onScopeChange = (scope: Scope): void => {
    setSelectedRecord(undefined)
    setSelectedScope(scope)
  }
 
  const iconProps = {
    size: 16
  }
 
  const enum TAB_ID {
    PROJECT = 'project',
    ORGANIZATION = 'organization',
    ACCOUNT = 'account'
  }
 
  const defaultTab =
    selectedScope === Scope.ORG
      ? TAB_ID.ORGANIZATION
      : selectedScope === Scope.PROJECT
      ? TAB_ID.PROJECT
      : TAB_ID.ACCOUNT
 
  const onCheckboxChange = (checked: boolean, item: T) => {
    const tempCheckedItems: T[] = [...(checkedItems[selectedScope].items || [])]
    Eif (checked) {
      tempCheckedItems.push(item)
    } else {
      tempCheckedItems.splice(
        tempCheckedItems.findIndex(el => isEqual(el, item)),
        1
      )
    }
 
    setCheckedItems({
      ...checkedItems,
      [selectedScope]: { items: tempCheckedItems, scopedItemsTotal: tempCheckedItems.length, updatedWithOldData: true },
      total: checked ? checkedItems.total + 1 : checkedItems.total - 1
    })
  }
 
  useEffect(() => {
    let renderedListTemp
    if (loading) {
      renderedListTemp = (
        <Container flex={{ align: 'center-center' }} padding="small">
          <Icon name="spinner" size={24} color={Color.PRIMARY_7} />
        </Container>
      )
    }
    Iif (!loading && error) {
      renderedListTemp = (
        <Container>
          <PageError message={error} onClick={fetchData} />
        </Container>
      )
    }
    if (!loading && !error && data.length) {
      renderedListTemp = (
        <div className={cx(css.referenceList, { [css.referenceListOverflow]: data.length > 5 })}>
          {data.map((item: EntityReferenceResponse<T>) => {
            const checked = !!checkedItems[selectedScope]?.items.find(el => {
              return isEqual(el, item.record)
            })
            return (
              <Layout.Horizontal
                key={item.identifier}
                className={cx(css.listItem, recordClassName, {
                  [css.selectedItem]: checked
                })}
                flex={{ alignItems: 'center', justifyContent: 'flex-start' }}
              >
                <Checkbox
                  onChange={e => onCheckboxChange((e.target as any).checked, item.record)}
                  data-testid={`Checkbox-${item.identifier}`}
                  disabled={disableItems(item.record['identifier'], disablePreSelectedItems, selectedItemsUuidAndScope)}
                  className={css.checkbox}
                  checked={checked}
                  large
                  labelElement={recordRender({ item, selectedScope, selected: checked })}
                />
              </Layout.Horizontal>
            )
          })}
        </div>
      )
    }
    if (!loading && !error && !data.length) {
      renderedListTemp = (
        <Container padding={{ top: 'xlarge' }} flex={{ align: 'center-center' }}>
          <Text>{noRecordsText}</Text>
        </Container>
      )
    }
    setRenderedList(renderedListTemp)
  }, [selectedScope, loading, error, data, checkedItems, checkedItems.total, selectedRecord])
 
  const canRenderTab = (scope: Scope): boolean => {
    Iif (onlyCurrentScope && !isEqual(scope, defaultScope)) {
      return false
    }
    return true
  }
 
  const renderTab = (
    show: boolean,
    id: string,
    scope: Scope,
    icon: IconName,
    title: StringKeys
  ): React.ReactElement | null => {
    let multiSelectCount = null
    if (checkedItems[scope]?.scopedItemsTotal) {
      multiSelectCount = (
        <Text
          inline
          height={19}
          margin={{ left: 'small' }}
          padding={{ left: 'xsmall', right: 'xsmall' }}
          flex={{ align: 'center-center' }}
          background={Color.PRIMARY_7}
          color={Color.WHITE}
          border={{ radius: 100 }}
        >
          {checkedItems[scope].scopedItemsTotal}
        </Text>
      )
    }
    return show && canRenderTab(scope) ? (
      <Tab
        id={id}
        title={
          <Layout.Horizontal onClick={() => onScopeChange(scope)} padding={'medium'} flex={{ alignItems: 'center' }}>
            <Text>
              <Icon name={icon} {...iconProps} className={css.iconMargin} />
              {getString(title)}
            </Text>
            {multiSelectCount}
          </Layout.Horizontal>
        }
        panel={renderedList}
      />
    ) : null
  }
 
  const onSelect = () => {
    const allCheckedItems: T[] = [
      ...checkedItems[Scope.PROJECT].items,
      ...checkedItems[Scope.ORG].items,
      ...checkedItems[Scope.ACCOUNT].items
    ]
    const scopesWhichUpdatedWithPreviousSelectedData = {
      [Scope.PROJECT]: checkedItems[Scope.PROJECT].updatedWithOldData,
      [Scope.ACCOUNT]: checkedItems[Scope.ACCOUNT].updatedWithOldData,
      [Scope.ORG]: checkedItems[Scope.ORG].updatedWithOldData
    }
    onMultiSelect?.(
      getScopeAndUuidFromSelectDTO({
        selectedData: allCheckedItems,
        previousSelectedItemsUuidAndScope: selectedItemsUuidAndScope,
        scopesUpdatedWithPreviousData: scopesWhichUpdatedWithPreviousSelectedData
      })
    )
  }
 
  return (
    <Container className={cx(css.container, className)}>
      <Layout.Vertical spacing="medium">
        <div className={css.searchBox}>
          <TextInput
            wrapperClassName={css.search}
            placeholder={getString('search')}
            leftIcon="search"
            value={searchTerm}
            autoFocus
            onChange={(e: React.ChangeEvent<HTMLInputElement>) => setSearchTerm(e.target.value)}
          />
          {searchInlineComponent}
        </div>
      </Layout.Vertical>
      <div className={cx(css.tabsContainer, [css.tabWidth])}>
        <Tabs id={'selectScope'} vertical defaultSelectedTabId={defaultTab}>
          {renderTab(!!projectIdentifier, TAB_ID.PROJECT, Scope.PROJECT, 'cube', 'projectLabel')}
          {renderTab(!!orgIdentifier, TAB_ID.ORGANIZATION, Scope.ORG, 'diagram-tree', 'orgLabel')}
          {renderTab(true, TAB_ID.ACCOUNT, Scope.ACCOUNT, 'layers', 'account')}
        </Tabs>
      </div>
      <Layout.Horizontal flex={{ justifyContent: 'space-between' }}>
        <Layout.Horizontal spacing="medium">
          <Button
            intent="primary"
            text={getString('entityReference.apply')}
            onClick={onSelect}
            disabled={!checkedItems || checkedItems.total < 1}
          />
        </Layout.Horizontal>
        <Layout.Horizontal spacing={'small'}>
          <Text inline>{getString('common.totalSelected')}</Text>
          <Text
            inline
            padding={{ left: 'xsmall', right: 'xsmall' }}
            flex={{ align: 'center-center' }}
            background={Color.PRIMARY_7}
            color={Color.WHITE}
            border={{ radius: 100 }}
          >
            {checkedItems.total}
          </Text>
        </Layout.Horizontal>
      </Layout.Horizontal>
    </Container>
  )
}
 
export default MultiSelectEntityReferenceProps