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

92.86% Statements 91/98
86.15% Branches 112/130
81.82% Functions 18/22
92.86% Lines 91/98

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 480 481 482 483 484 485 486 487 488              539x 539x 539x                           539x 539x 539x 539x 539x 539x 539x                                                                       539x 539x 539x 539x                         539x 539x   539x 539x 539x   539x 7x 7x       4x 1x   3x   3x 3x   7x                       539x 12x 12x               4x         4x 4x 4x       4x         4x                       4x 2x 2x 2x 1x               3x                   5x         1x       4x           18x       18x                             539x 22x 22x 22x                                                                                                                                     14x 13x 13x 13x 13x   13x 1x 1x   12x 12x 12x 12x 12x 12x 12x 1x 11x 4x   12x       12x                             12x           1x             7x 7x 7x       46x                                                                                                                                       1x                               539x                           421x 421x 421x 421x 13x                                 421x 138x     421x   9x 9x         421x                                      
/*
 * 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, { CSSProperties } from 'react'
import { defaultTo } from 'lodash-es'
import {
  Button,
  Formik,
  Text,
  FormInput,
  SelectOption,
  MultiSelectOption,
  Layout,
  RUNTIME_INPUT_VALUE,
  ButtonVariation,
  useToaster,
  Popover,
  Container
} from '@wings-software/uicore'
import { Dialog, Classes, FormGroup, Position, PopoverInteractionKind } from '@blueprintjs/core'
import * as Yup from 'yup'
import cx from 'classnames'
import isEmpty from 'lodash/isEmpty'
import { useModalHook } from '@harness/use-modal'
import { useStrings, String } from 'framework/strings'
import css from './ConfigureOptions.module.scss'
 
export interface ConfigureOptionsProps {
  value: string
  isRequired?: boolean
  defaultValue?: string | number
  variableName: string
  type: string | JSX.Element
  onChange?: (value: string, defaultValue?: string | number, isRequired?: boolean) => void
  showDefaultField?: boolean
  showRequiredField?: boolean
  showAdvanced?: boolean
  className?: string
  fetchValues?: (done: (response: SelectOption[] | MultiSelectOption[]) => void) => void
  style?: CSSProperties
  isReadonly?: boolean
}
 
export interface ConfigureOptionsDialogProps {
  value: string
  isRequired?: boolean
  defaultValue?: string | number
  variableName: string
  type: string | JSX.Element
  showDefaultField?: boolean
  showRequiredField?: boolean
  showAdvanced: boolean
  fetchValues?: (done: (response: SelectOption[] | MultiSelectOption[]) => void) => void
  isReadonly: boolean
  closeModal: (
    str?: string | undefined,
    defaultStr?: string | number | undefined,
    required?: boolean | undefined
  ) => void
}
 
export enum Validation {
  None = 'None',
  AllowedValues = 'AllowedValues',
  Regex = 'Regex'
}
 
export interface FormValues {
  isRequired?: boolean
  defaultValue?: string | number
  allowedValues: string[]
  regExValues: string
  validation: Validation
  isAdvanced: boolean
  advancedValue: string
}
 
export const AllowedExpression = 'allowedValues'
export const RegexExpression = 'regex'
// eslint-disable-next-line no-useless-escape
export const RegExInputExpression = /^\<\+input\>\.?(?:allowedValues\((.*?)\)|regex\((.*?)\))?$/
const RegExpression = /jexl\((.*?)\)/
const JEXL = 'jexl'
 
const getInputStr = (data: FormValues): string => {
  let inputStr = RUNTIME_INPUT_VALUE
  if (
    data.validation === Validation.AllowedValues &&
    (data.allowedValues?.length > 0 || data.advancedValue.length > 0)
  ) {
    if (data.isAdvanced) {
      inputStr += `.${AllowedExpression}(${JEXL}(${data.advancedValue}))`
    } else {
      inputStr += `.${AllowedExpression}(${data.allowedValues.join(',')})`
    }
  } /* istanbul ignore else */ else Eif (data.validation === Validation.Regex && data.regExValues?.length > 0) {
    inputStr += `.${RegexExpression}(${data.regExValues})`
  }
  return inputStr
}
 
interface ValidationSchemaReturnType {
  validation: Yup.StringSchema<string>
  regExValues: Yup.StringSchema<string | undefined>
  defaultValue: Yup.StringSchema<string | undefined>
  isAdvanced: Yup.BooleanSchema<boolean | undefined>
  advancedValue: Yup.StringSchema<string | undefined>
  allowedValues: Yup.NotRequiredArraySchema<string | undefined>
}
 
const ValidationSchema = (): ValidationSchemaReturnType => {
  const { getString } = useStrings()
  return {
    validation: Yup.string().required(),
    regExValues: Yup.string().when('validation', {
      is: Validation.Regex,
      then: Yup.string()
        .trim()
        .test({
          test(val: string): boolean | Yup.ValidationError {
            Iif (isEmpty(val)) {
              return this.createError({
                message: getString('common.configureOptions.validationErrors.regExIsRequired')
              })
            }
            let isValid = true
            try {
              val?.length > 0 && new RegExp(val)
            } catch (_e) {
              isValid = false
            }
            Iif (!isValid) {
              return this.createError({
                message: getString('common.configureOptions.validationErrors.regExNotValid')
              })
            }
            return true
          }
        })
    }),
    defaultValue: Yup.string()
      .trim()
      .when('validation', {
        is: Validation.Regex,
        then: Yup.string()
          .trim()
          .test({
            test(val: string): boolean | Yup.ValidationError {
              if (!isEmpty(this.parent.regExValues) && val?.length > 0 && !this.parent.isAdvanced) {
                try {
                  const reg = new RegExp(this.parent.regExValues)
                  if (!reg.test(val)) {
                    return this.createError({
                      message: getString('common.configureOptions.validationErrors.defaultRegExValid')
                    })
                  }
                } catch (_e) {
                  // Do nothing
                }
              }
              return true
            }
          })
      })
      .when('validation', {
        is: Validation.AllowedValues,
        then: Yup.string()
          .trim()
          .test({
            test(val: string): boolean | Yup.ValidationError {
              if (
                this.parent.allowedValues?.length > 0 &&
                !isEmpty(val) &&
                this.parent.allowedValues.indexOf(val) === -1
              ) {
                return this.createError({
                  message: getString('common.configureOptions.validationErrors.defaultAllowedValid')
                })
              }
              return true
            }
          })
      }),
    isAdvanced: Yup.boolean(),
    advancedValue: Yup.string().when(['validation', 'isAdvanced'], {
      is: (validation: Validation, isAdv: boolean) => validation === Validation.AllowedValues && isAdv,
      then: Yup.string().required(getString('common.configureOptions.validationErrors.jexlExpressionRequired'))
    }),
    allowedValues: Yup.array(Yup.string()).when(['validation', 'isAdvanced'], {
      is: (validation: Validation, isAdv: boolean) => validation === Validation.AllowedValues && !isAdv,
      then: Yup.array(Yup.string()).min(1, getString('common.configureOptions.validationErrors.minOneAllowedValue'))
    })
  }
}
 
interface AllowedValuesFieldsProps {
  values: FormValues
  showAdvanced: boolean
  setFieldValue: (field: string, value: any) => void
  isReadonly: boolean
  fetchValues?: (done: (response: SelectOption[] | MultiSelectOption[]) => void) => void
  options: SelectOption[] | MultiSelectOption[]
}
 
const AllowedValuesFields = (props: AllowedValuesFieldsProps): JSX.Element => {
  const { values, showAdvanced, setFieldValue, isReadonly, fetchValues, options } = props
  const { getString } = useStrings()
  return (
    <div className={css.allowedOptions}>
      {showAdvanced ? (
        <span className={css.advancedBtn}>
          <Button
            variation={ButtonVariation.LINK}
            tooltip={
              values.isAdvanced ? undefined : (
                <Layout.Horizontal padding="medium">
                  <String stringID="common.configureOptions.advancedHelp" useRichText={true} />
                </Layout.Horizontal>
              )
            }
            tooltipProps={{ position: Position.RIGHT }}
            text={values.isAdvanced ? getString('common.configureOptions.returnToBasic') : getString('advancedTitle')}
            onClick={() => {
              setFieldValue('isAdvanced', !values.isAdvanced)
            }}
            disabled={isReadonly}
          />
        </span>
      ) : /* istanbul ignore next */ null}
      {values.isAdvanced ? (
        <FormInput.TextArea
          name="advancedValue"
          className={css.secondColumn}
          label={getString('common.configureOptions.jexlLabel')}
          placeholder={getString('inputTypes.EXPRESSION')}
          disabled={isReadonly}
        />
      ) : (
        <>
          {!fetchValues ? (
            <FormInput.KVTagInput
              className={css.secondColumn}
              label={getString('allowedValues')}
              name="allowedValues"
              isArray={true}
              disabled={isReadonly}
            />
          ) : (
            <FormInput.MultiSelect
              className={css.secondColumn}
              items={options}
              label={getString('common.configureOptions.values')}
              name="allowedValues"
              disabled={isReadonly}
            />
          )}
        </>
      )}
    </div>
  )
}
function ConfigureOptionsDialog(props: ConfigureOptionsDialogProps): JSX.Element | null {
  const {
    value,
    isRequired,
    defaultValue,
    showDefaultField = true,
    variableName,
    type,
    showRequiredField = false,
    showAdvanced = false,
    fetchValues,
    isReadonly = false,
    closeModal
  } = props
  const [input, setInput] = React.useState(value)
  const { showError } = useToaster()
  const [options, setOptions] = React.useState<SelectOption[] | MultiSelectOption[]>([])
  const { getString } = useStrings()
 
  if (!RegExInputExpression.test(input)) {
    showError(getString('common.configureOptions.notValidExpression'))
    return null
  }
  const response = input.match(RegExInputExpression)
  const allowedValueStr = defaultTo(response?.[1], '')
  let allowedValues: string[] = []
  const regExValues = defaultTo(response?.[2], '')
  const isAdvanced = RegExpression.test(input)
  let advancedValue = ''
  if (isAdvanced) {
    advancedValue = defaultTo(allowedValueStr.match(RegExpression)?.[1], /* istanbul ignore next */ '')
  } else if (allowedValueStr.length > 0) {
    allowedValues = allowedValueStr.split(',')
  }
  fetchValues?.(data => {
    setOptions(data)
  })
 
  const inputValues: FormValues = {
    isRequired,
    defaultValue,
    allowedValues,
    regExValues,
    isAdvanced,
    advancedValue,
    validation:
      allowedValues.length > 0 || isAdvanced
        ? Validation.AllowedValues
        : regExValues.length > 0
        ? Validation.Regex
        : Validation.None
  }
 
  return (
    <Dialog
      isOpen={true}
      title={getString('common.configureOptions.configureOptions')}
      enforceFocus={false}
      className={cx(css.dialog, Classes.DIALOG, 'padded-dialog')}
      onClose={() => closeModal()}
    >
      <Formik
        initialValues={inputValues}
        formName="configureOptionsForm"
        validationSchema={Yup.object().shape(ValidationSchema())}
        onSubmit={data => {
          const inputStr = getInputStr(data)
          setInput(inputStr)
          closeModal(inputStr, data.defaultValue, data.isRequired)
        }}
      >
        {({ submitForm, values, setFieldValue }) => (
          <>
            <div>
              <FormGroup className={css.label} label={getString('variableLabel')} inline>
                <Text lineClamp={1}>{variableName}</Text>
              </FormGroup>
              <FormGroup className={css.label} label={getString('typeLabel')} inline>
                {typeof type === 'string' ? <Text>{type}</Text> : type}
              </FormGroup>
              {showDefaultField &&
                (fetchValues ? (
                  <FormInput.Select
                    items={options}
                    label={getString('common.configureOptions.defaultValue')}
                    name="defaultValue"
                    disabled={isReadonly}
                  />
                ) : (
                  <FormInput.Text
                    inputGroup={{ type: type === 'Number' ? 'number' : 'text' }}
                    label={getString('common.configureOptions.defaultValue')}
                    name="defaultValue"
                    disabled={isReadonly}
                  />
                ))}
              {showRequiredField && (
                <FormInput.CheckBox
                  className={css.checkbox}
                  label={getString('common.configureOptions.requiredDuringExecution')}
                  name="isRequired"
                  disabled={isReadonly}
                />
              )}
              <div className={css.split}>
                <FormInput.RadioGroup
                  disabled={isReadonly}
                  name="validation"
                  label={getString('common.configureOptions.validation')}
                  items={[
                    { label: getString('none'), value: Validation.None },
                    { label: getString('allowedValues'), value: Validation.AllowedValues },
                    { label: getString('common.configureOptions.regex'), value: Validation.Regex }
                  ]}
                />
                {values.validation !== Validation.None && <div className={css.line} />}
                {values.validation === Validation.AllowedValues && (
                  <AllowedValuesFields
                    values={values}
                    showAdvanced={showAdvanced}
                    setFieldValue={setFieldValue}
                    fetchValues={fetchValues}
                    isReadonly={isReadonly}
                    options={options}
                  />
                )}
                {values.validation === Validation.Regex && (
                  <FormInput.TextArea
                    className={css.secondColumn}
                    label={getString('common.configureOptions.regex')}
                    name="regExValues"
                    disabled={isReadonly}
                  />
                )}
              </div>
            </div>
            <Layout.Horizontal spacing="xxlarge" margin={{ top: 'medium' }}>
              <Button
                variation={ButtonVariation.SECONDARY}
                text={<String stringID="cancel" />}
                onClick={() => closeModal()}
              />
              <Button
                variation={ButtonVariation.PRIMARY}
                text={<String stringID="submit" />}
                onClick={submitForm}
                disabled={isReadonly}
              />{' '}
            </Layout.Horizontal>
          </>
        )}
      </Formik>
    </Dialog>
  )
}
 
export function ConfigureOptions(props: ConfigureOptionsProps): JSX.Element {
  const {
    value,
    isRequired,
    defaultValue,
    onChange,
    showDefaultField = true,
    variableName,
    type,
    showRequiredField = false,
    showAdvanced = false,
    fetchValues,
    className,
    isReadonly = false
  } = props
  const [input, setInput] = React.useState(value)
  const [isHover, setIsHover] = React.useState<boolean>()
  const [showModal, hideModal] = useModalHook(() => {
    return (
      <ConfigureOptionsDialog
        closeModal={closeModal}
        isRequired={isRequired}
        isReadonly={isReadonly}
        value={value}
        variableName={variableName}
        type={type}
        showDefaultField={showDefaultField}
        defaultValue={defaultValue}
        showRequiredField={showRequiredField}
        showAdvanced={showAdvanced}
        fetchValues={fetchValues}
      />
    )
  }, [value, showDefaultField, variableName, type, showRequiredField, showAdvanced, fetchValues, defaultValue, type])
 
  React.useEffect(() => {
    setInput(value)
  }, [value])
 
  const closeModal = React.useCallback(
    (str?: string, defaultStr?: string | number, required?: boolean) => {
      hideModal()
      onChange?.(str ?? input, defaultStr ?? defaultValue, required)
    },
    [hideModal, onChange, input, defaultValue]
  )
 
  return (
    <Popover interactionKind={PopoverInteractionKind.HOVER} position={Position.TOP} className={Classes.DARK}>
      <Button
        style={{ color: isHover ? 'var(--primary-6)' : 'var(--grey-400)', ...props.style }}
        className={className}
        minimal
        rightIcon="cog"
        // To avoid non unique IDs ina  asingle form
        id={`configureOptions_${variableName}`}
        onClick={showModal}
        onMouseEnter={() => setIsHover(true)}
        onMouseLeave={() => setIsHover(false)}
      />
      <Container className={css.cogBtnTooltipContainer} padding="medium">
        <Text color={'white'}>{'Configure runtime input options'}</Text>
      </Container>
    </Popover>
  )
}