All files / modules/75-cf/pages/target-management/targets CreateTargetModal.tsx

72.45% Statements 71/98
80% Branches 36/45
50% Functions 17/34
72.34% Lines 68/94

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              2x 2x 2x 2x 2x   2x 2x 2x 2x 2x 2x   2x 2x 2x       27x                 2x 15x 32x 2x   15x   15x                       16x   16x                                                                               1x                       2x 1x 1x 1x 1x 1x         1x                                             1x     1x                         1x                                                                                                     2x 26x               2x 24x 24x 24x 24x 24x 24x 24x 22x 24x   24x   24x                   24x 2x 2x     24x 1x     24x 1x 1x     24x 2x 2x     24x 1x 1x 1x             24x           24x 11x                                                                                               24x                           2x  
/*
 * 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 } from 'react'
import { Button, Container, FlexExpander, Layout, SimpleTagInput, Text, TextInput } from '@wings-software/uicore'
import { useModalHook } from '@harness/use-modal'
import { Color } from '@harness/design-system'
import { Dialog, Radio, RadioGroup, Spinner } from '@blueprintjs/core'
import type { StringKeys } from 'framework/strings'
import { useStrings } from 'framework/strings'
import RbacButton from '@rbac/components/Button/Button'
import { ResourceType } from '@rbac/interfaces/ResourceType'
import { PermissionIdentifier } from '@rbac/interfaces/PermissionIdentifier'
import usePlanEnforcement from '@cf/hooks/usePlanEnforcement'
import { FeatureIdentifier } from 'framework/featureStore/FeatureIdentifier'
import type { Target } from 'services/cf'
import useActiveEnvironment from '@cf/hooks/useActiveEnvironment'
import uploadImageUrl from './upload.svg'
import css from './TargetsPage.module.scss'
 
export type TargetData = Pick<Target, 'name' | 'identifier'>
 
const emptyTarget = (): TargetData => ({ name: '', identifier: '' })
 
interface TargetListProps {
  onAdd: () => void
  onRemove: (index: number) => void
  onChange: (idx: number, newData: TargetData) => void
  targets: TargetData[]
}
 
const TargetList: React.FC<TargetListProps> = ({ targets, onAdd, onRemove, onChange }) => {
  const { getString } = useStrings()
  const handleChange = (idx: number, attr: keyof TargetData) => (e: any) => {
    onChange(idx, { ...targets[idx], [attr]: e.target.value })
  }
  const fieldWidth = 285
 
  return (
    <Layout.Vertical spacing="xsmall" margin={{ top: 'small', bottom: 'medium' }} style={{ paddingLeft: '28px' }}>
      <Layout.Horizontal spacing="small">
        <Text style={{ color: '#22222A', fontWeight: 500 }} width={fieldWidth}>
          {getString('name')}
        </Text>
        <Text style={{ color: '#22222A', fontWeight: 500 }} width={fieldWidth}>
          {getString('identifier')}
        </Text>
        <FlexExpander />
      </Layout.Horizontal>
      {targets.map((target: TargetData, idx: number) => {
        const lastItem = idx === targets.length - 1
 
        return (
          <Layout.Horizontal key={idx + '-target-row'} spacing="small">
            <TextInput
              placeholder={getString('cf.targets.enterName')}
              value={target.name}
              onChange={handleChange(idx, 'name')}
              style={{ width: `${fieldWidth}px` }}
            />
            <TextInput
              placeholder={getString('cf.targets.enterValue')}
              value={target.identifier}
              onChange={handleChange(idx, 'identifier')}
              style={{ width: `${fieldWidth}px` }}
            />
            {lastItem && idx !== 0 && (
              <Button
                minimal
                intent="primary"
                icon={'minus'}
                iconProps={{
                  size: 16,
                  style: { alignSelf: 'center' }
                }}
                onClick={() => {
                  onRemove(idx)
                }}
              />
            )}
            <Button
              minimal
              intent="primary"
              icon={lastItem ? 'plus' : 'minus'}
              iconProps={{
                size: 16,
                style: { alignSelf: 'center' }
              }}
              onClick={
                lastItem
                  ? onAdd
                  : () => {
                      onRemove(idx)
                    }
              }
              style={{ transform: `translateX(${lastItem && idx ? -10 : 0}px)` }}
            />
          </Layout.Horizontal>
        )
      })}
    </Layout.Vertical>
  )
}
 
const FileUpload: React.FC<{ onChange: (targets: TargetData[]) => void }> = ({ onChange }) => {
  const { getString } = useStrings()
  const uploadContainerHeight = 260
  const [targets, setTargets] = useState<TargetData[]>([])
  const [tagItems, setTagItems] = useState<{ label: string; value: string }[]>([])
  const handleRemove = (): void => {
    setTargets([])
    onChange([])
    setTagItems([])
  }
  const handleUpload = (file: File): void => {
    file
      .text()
      .then((str: string) => {
        return str
          .split(/\r?\n/)
          .filter(value => !!value?.length)
          .map(row => row.split(',').map(x => x.trim()))
          .map(([name, identifier]) => ({ name, identifier } as TargetData))
      })
      .then((targetData: TargetData[]) => {
        return filterTargets(targetData)
      })
      .then((targetData: TargetData[]) => {
        setTagItems(
          targetData.map(
            ({ name, identifier }) => ({ label: identifier, value: name } as { label: string; value: string })
          )
        )
        setTargets(targetData)
        onChange(targetData)
      })
  }
  const handleChange = (e: any) => {
    handleUpload(e.target.files[0])
  }
  const onTagChanged: React.ComponentProps<typeof SimpleTagInput>['onChange'] = (
    selectedItems,
    _createdItems,
    _items
  ) => {
    const updatedTargets = selectedItems.map(arg => {
      const { label, value } = arg as { label: string; value: string }
      return { name: value, identifier: label }
    })
    setTargets(updatedTargets)
    onChange(updatedTargets)
  }
 
  return (
    <>
      {!targets?.length ? (
        <>
          <label htmlFor="bulk" className={css.upload}>
            <Layout.Vertical
              flex={{ align: 'center-center' }}
              height={uploadContainerHeight}
              style={{ border: '1px solid #D9DAE6', borderRadius: '4px', background: '#FAFBFC', margin: '0 28px' }}
            >
              <img src={uploadImageUrl} width={100} height={100} alt="upload" />
              <Text padding={{ top: 'large' }} color={Color.BLUE_500} style={{ fontSize: '14px' }}>
                {getString('cf.targets.uploadYourFile')}
              </Text>
            </Layout.Vertical>
          </label>
          <input type="file" id="bulk" name="bulk-upload" style={{ display: 'none' }} onChange={handleChange} />
        </>
      ) : (
        <Container>
          <Layout.Horizontal
            margin={{ right: 'xxlarge', bottom: 'small', left: 'xlarge' }}
            style={{ alignItems: 'center' }}
          >
            <Text>
              <span
                dangerouslySetInnerHTML={{ __html: getString('cf.targets.uploadStats', { count: targets.length }) }}
              />
            </Text>
            <FlexExpander />
            <Button intent="primary" text={getString('filters.clearAll')} onClick={handleRemove} minimal />
          </Layout.Horizontal>
          <Container
            style={{
              border: '1px solid #D9DAE6',
              borderRadius: '4px',
              margin: '0 28px',
              overflow: 'auto'
            }}
            height={220}
            padding="xsmall"
            className={css.uploadTargetContainer}
          >
            <SimpleTagInput noInputBorder selectedItems={tagItems} items={tagItems} onChange={onTagChanged} />
          </Container>
        </Container>
      )}
    </>
  )
}
 
const filterTargets = (targets: TargetData[]): TargetData[] =>
  targets.filter(t => t.name?.length && t.identifier?.length)
 
export interface CreateTargetModalProps {
  loading: boolean
  onSubmitTargets: (targets: TargetData[], hideModal: () => void) => void
  onSubmitUpload: (file: File, hideModal: () => void) => void
}
 
const CreateTargetModal: React.FC<CreateTargetModalProps> = ({ loading, onSubmitTargets }) => {
  const LIST = 'list'
  const UPLOAD = 'upload'
  const [isList, setIsList] = useState(true)
  const [targets, setTargets] = useState<TargetData[]>([emptyTarget()])
  const addDisabled = filterTargets(targets).length === 0
  const { getString } = useStrings()
  const getPageString = (key: string): string =>
    getString(`cf.targets.${key}` as StringKeys /* TODO: fix this by using a map */)
  const { activeEnvironment } = useActiveEnvironment()
 
  const { isPlanEnforcementEnabled } = usePlanEnforcement()
 
  const planEnforcementProps = isPlanEnforcementEnabled
    ? {
        featuresProps: {
          featuresRequest: {
            featureNames: [FeatureIdentifier.MAUS]
          }
        }
      }
    : undefined
 
  const handleChange = (e: React.FormEvent<HTMLInputElement>): void => {
    setIsList((e.target as HTMLInputElement).value === LIST)
    setTargets([emptyTarget()])
  }
 
  const handleTargetAdd = (): void => {
    setTargets([...targets, emptyTarget()])
  }
 
  const handleTargetRemove = (index: number): void => {
    targets.splice(index, 1)
    setTargets([...targets])
  }
 
  const handleTargetChange = (idx: number, newData: TargetData): void => {
    targets[idx] = newData
    setTargets([...targets])
  }
 
  const handleSubmit = (): void => {
    const filteredTargets = filterTargets(targets)
    Eif (filteredTargets.length) {
      onSubmitTargets(filteredTargets, () => {
        hideModal()
        setTargets([emptyTarget()])
      })
    }
  }
 
  const handleCancel = (): void => {
    setIsList(true)
    setTargets([emptyTarget()])
    hideModal()
  }
 
  const [openModal, hideModal] = useModalHook(() => {
    return (
      <Dialog
        isOpen
        enforceFocus={false}
        onClose={hideModal}
        title={getString('cf.targets.addTargetsLabel')}
        className={css.modal}
      >
        <Layout.Vertical padding="medium" height={450}>
          <Container style={{ flexGrow: 1, overflow: 'auto' }} padding={{ top: 'small' }}>
            <RadioGroup name="modalVariant" selectedValue={isList ? LIST : UPLOAD} onChange={handleChange}>
              <Radio name="modalVariant" label={getPageString('list')} value={LIST} />
              {isList && (
                <TargetList
                  targets={targets}
                  onAdd={handleTargetAdd}
                  onRemove={handleTargetRemove}
                  onChange={handleTargetChange}
                />
              )}
              <Radio name="modalVariant" label={getPageString('upload')} value={UPLOAD} />
              {!isList && (
                <Layout.Vertical spacing="small">
                  <Text style={{ padding: 'var(--spacing-xsmall) var(--spacing-xsmall) var(--spacing-xsmall) 27px' }}>
                    <span dangerouslySetInnerHTML={{ __html: getString('cf.targets.uploadHeadline') }} />
                    <Text
                      rightIcon="question"
                      inline
                      tooltip={getString('cf.targets.uploadHelp')}
                      style={{ transform: 'translateY(2px)', cursor: 'pointer' }}
                    />
                  </Text>
                  <FileUpload onChange={_targets => setTargets(_targets)} />
                </Layout.Vertical>
              )}
            </RadioGroup>
          </Container>
          {/* Buttons */}
          <Layout.Horizontal height={34} spacing="small">
            <Button disabled={addDisabled || loading} text={getString('add')} intent="primary" onClick={handleSubmit} />
            <Button disabled={loading} text={getString('cancel')} minimal onClick={handleCancel} />
            {loading && <Spinner size={16} />}
          </Layout.Horizontal>
        </Layout.Vertical>
      </Dialog>
    )
  }, [isList, targets, loading, addDisabled])
 
  return (
    <RbacButton
      intent="primary"
      text={getString('cf.targets.create')}
      onClick={openModal}
      permission={{
        resource: { resourceType: ResourceType.ENVIRONMENT, resourceIdentifier: activeEnvironment },
        permission: PermissionIdentifier.EDIT_FF_TARGETGROUP
      }}
      {...planEnforcementProps}
    />
  )
}
 
export default CreateTargetModal