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

87.65% Statements 71/81
71.63% Branches 101/141
75% Functions 9/12
87.5% Lines 70/80

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              186x 186x 186x 186x                             186x 186x 186x 186x 186x 186x   186x 1024x           649x   649x             22x                                   186x                 672x   672x     672x                     672x                                                                             186x                   672x 672x 672x 672x 672x 672x               672x   672x 672x     22x     22x 22x 22x         672x                         672x                   672x   672x 672x                           186x                   186x     373x   373x 1x     372x 1x     371x   378x   378x   285x 16x     269x 6x     263x 263x 263x   263x 91x           172x 172x 172x   172x 3x           169x                                 186x 1x   1x             1x               1x                                 186x  
/*
 * 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 { FormGroup, IFormGroupProps, Intent, InputGroup, IInputGroupProps, HTMLInputProps } from '@blueprintjs/core'
import { connect, FormikContext } from 'formik'
import {
  ExpressionAndRuntimeType,
  ExpressionAndRuntimeTypeProps,
  MultiTypeInputValue,
  FixedTypeComponentProps,
  DurationInputHelpers,
  parseStringToTime,
  timeToDisplayText,
  getMultiTypeFromValue,
  MultiTypeInputType,
  DataTooltipInterface,
  HarnessDocTooltip,
  FormError,
  FormikTooltipContext
} from '@wings-software/uicore'
import { get } from 'lodash-es'
import * as Yup from 'yup'
import { useStrings } from 'framework/strings'
import { ConfigureOptions, ConfigureOptionsProps } from '@common/components/ConfigureOptions/ConfigureOptions'
import { errorCheck } from '@common/utils/formikHelpers'
import css from './MultiTypeDuration.module.scss'
 
export function isValidTimeString(value: string): boolean {
  return !DurationInputHelpers.UNIT_LESS_REGEX.test(value) && DurationInputHelpers.VALID_SYNTAX_REGEX.test(value)
}
 
function MultiTypeDurationFixedTypeComponent(
  props: FixedTypeComponentProps & MultiTypeDurationProps['inputGroupProps']
): React.ReactElement {
  const { onChange, value, disabled, ...inputGroupProps } = props
 
  return (
    <InputGroup
      fill
      {...inputGroupProps}
      disabled={disabled}
      value={value as string}
      onChange={(event: React.ChangeEvent<HTMLInputElement>) => {
        onChange?.(event.target.value, MultiTypeInputValue.STRING, MultiTypeInputType.FIXED)
      }}
    />
  )
}
 
interface MultiTypeDurationConfigureOptionsProps
  extends Omit<ConfigureOptionsProps, 'value' | 'type' | 'variableName' | 'onChange'> {
  variableName?: ConfigureOptionsProps['variableName']
}
 
export interface MultiTypeDurationProps
  extends Omit<ExpressionAndRuntimeTypeProps, 'fixedTypeComponent' | 'fixedTypeComponentProps'> {
  inputGroupProps?: Omit<IInputGroupProps & HTMLInputProps, 'onChange' | 'value'>
  enableConfigureOptions?: boolean
  configureOptionsProps?: MultiTypeDurationConfigureOptionsProps
}
 
export function MultiTypeDuration(props: MultiTypeDurationProps): React.ReactElement {
  const {
    name,
    value,
    onChange,
    enableConfigureOptions = true,
    configureOptionsProps,
    inputGroupProps,
    ...rest
  } = props
 
  const { getString } = useStrings()
 
  const expressionAndRuntimeTypeComponent = (
    <ExpressionAndRuntimeType
      name={name}
      value={value}
      onChange={onChange}
      style={{ flexGrow: 1 }}
      {...rest}
      fixedTypeComponentProps={inputGroupProps}
      fixedTypeComponent={MultiTypeDurationFixedTypeComponent}
    />
  )
 
  return (
    <>
      {enableConfigureOptions ? (
        <div className={css.container}>
          {expressionAndRuntimeTypeComponent}
          {getMultiTypeFromValue(value) === MultiTypeInputType.RUNTIME && (
            <ConfigureOptions
              value={value as string}
              type={getString('string')}
              variableName={name}
              showRequiredField={false}
              showDefaultField={false}
              showAdvanced={true}
              onChange={val => onChange?.(val, MultiTypeInputValue.STRING, MultiTypeInputType.RUNTIME)}
              style={{ marginLeft: 'var(--spacing-medium)' }}
              {...configureOptionsProps}
              isReadonly={props.disabled}
            />
          )}
        </div>
      ) : (
        expressionAndRuntimeTypeComponent
      )}
    </>
  )
}
 
export interface FormMultiTypeDurationProps extends Omit<IFormGroupProps, 'label' | 'placeholder'> {
  label: string | React.ReactElement
  name: string
  placeholder?: string
  formik?: FormikContext<unknown>
  skipErrorsIf?(formik?: FormikContext<unknown>): boolean
  multiTypeDurationProps?: Omit<MultiTypeDurationProps, 'name' | 'onChange' | 'value'>
  onChange?: MultiTypeDurationProps['onChange']
  tooltipProps?: DataTooltipInterface
  isOptional?: boolean
}
 
export function FormMultiTypeDuration(props: FormMultiTypeDurationProps): React.ReactElement {
  const {
    label,
    multiTypeDurationProps,
    formik,
    name,
    onChange,
    skipErrorsIf,
    isOptional = false,
    ...restProps
  } = props
  const { getString } = useStrings()
  const optionalLabel = getString('common.optionalLabel')
  const labelText = !isOptional ? label : `${label} ${optionalLabel}`
  const hideErrors = typeof skipErrorsIf === 'function' ? skipErrorsIf(formik) : false
  const hasError = !hideErrors && errorCheck(name, formik)
 
  const {
    intent = hasError ? Intent.DANGER : Intent.NONE,
    helperText = hasError ? <FormError name={name} errorMessage={get(formik?.errors, name)} /> : null,
    disabled,
    tooltipProps,
    ...rest
  } = restProps
 
  const value: string = get(formik?.values, name, '')
  const handleChange: MultiTypeDurationProps['onChange'] = React.useCallback(
    (val, valueType, type) => {
      const correctVal =
        type === MultiTypeInputType.FIXED && typeof val === 'string'
          ? val.replace(DurationInputHelpers.TEXT_LIMIT_REGEX, '')
          : val
      formik?.setFieldValue(name, correctVal)
      formik?.setFieldTouched(name, true)
      onChange?.(correctVal, valueType, type)
    },
    [formik?.setFieldTouched, formik?.setFieldValue, name, onChange]
  )
 
  const handleBlur = (): void => {
    formik?.setFieldTouched(name, true)
 
    if (getMultiTypeFromValue(value) !== MultiTypeInputType.FIXED || !isValidTimeString(value)) {
      return
    }
 
    const time = parseStringToTime(value)
    const strVal = timeToDisplayText(time)
 
    formik?.setFieldValue(name, strVal)
  }
 
  const customProps: MultiTypeDurationProps = {
    ...multiTypeDurationProps,
    name,
    inputGroupProps: {
      placeholder: 'Enter w/d/h/m/s/ms',
      ...multiTypeDurationProps?.inputGroupProps,
      name,
      onBlur: handleBlur
    }
  }
  const tooltipContext = React.useContext(FormikTooltipContext)
  const dataTooltipId =
    props.tooltipProps?.dataTooltipId || (tooltipContext?.formName ? `${tooltipContext?.formName}_${name}` : '')
  return (
    <FormGroup
      {...rest}
      labelFor={name}
      helperText={helperText}
      intent={intent}
      disabled={disabled}
      label={labelText ? <HarnessDocTooltip tooltipId={dataTooltipId} labelText={labelText} /> : labelText}
    >
      <MultiTypeDuration {...customProps} value={value} onChange={handleChange} disabled={disabled} />
    </FormGroup>
  )
}
 
export const FormMultiTypeDurationField = connect(FormMultiTypeDuration)
 
export interface GetDurationValidationSchemaProps {
  minimum?: string
  maximum?: string
  inValidSyntaxMessage?: string
  minimumErrorMessage?: string
  maximumErrorMessage?: string
}
 
export function getDurationValidationSchema(
  props: GetDurationValidationSchemaProps = {}
): Yup.StringSchema<string | undefined> {
  const { minimum = '1s', maximum = '53w' } = props
 
  if (typeof minimum === 'string' && !isValidTimeString(minimum)) {
    throw new Error(`Invalid format "${minimum}" provided for minimum value`)
  }
 
  if (typeof maximum === 'string' && !isValidTimeString(maximum)) {
    throw new Error(`Invalid format "${maximum}" provided for maximum value`)
  }
 
  return Yup.string().test({
    test(value: string): boolean | Yup.ValidationError {
      const { inValidSyntaxMessage, maximumErrorMessage, minimumErrorMessage } = props
 
      if (!value) return true
 
      if (getMultiTypeFromValue(value) !== MultiTypeInputType.FIXED) {
        return true
      }
 
      if (typeof value === 'string' && !isValidTimeString(value)) {
        return this.createError({ message: inValidSyntaxMessage || 'Invalid syntax provided' })
      }
 
      Eif (typeof minimum === 'string') {
        const minTime = parseStringToTime(minimum)
        const time = parseStringToTime(value)
 
        if (time < minTime) {
          return this.createError({
            message: minimumErrorMessage || `Value must be greater than or equal to "${timeToDisplayText(minTime)}"`
          })
        }
      }
 
      Eif (typeof maximum === 'string') {
        const maxTime = parseStringToTime(maximum)
        const time = parseStringToTime(value)
 
        if (time > maxTime) {
          return this.createError({
            message: maximumErrorMessage || `Value must be less than or equal to "${timeToDisplayText(maxTime)}"`
          })
        }
      }
 
      return true
    }
  })
}
 
export interface DurationInputForInputSetProps extends Omit<IFormGroupProps, 'label' | 'placeholder'> {
  onChange?(str: string): void
  name: string
  label?: React.ReactNode
  inputProps?: Omit<IInputGroupProps & HTMLInputProps, 'onChange' | 'value'>
}
 
export interface ConnectedDurationInputForInputSetProps extends DurationInputForInputSetProps {
  // eslint-disable-next-line @typescript-eslint/no-explicit-any
  formik: FormikContext<any>
}
 
export function DurationInputForInputSet(props: ConnectedDurationInputForInputSetProps): React.ReactElement {
  const { formik, onChange, name, label, inputProps, ...restProps } = props
 
  const hasError = errorCheck(name, formik)
 
  const {
    intent = hasError ? Intent.DANGER : Intent.NONE,
    helperText = hasError ? <FormError name={name} errorMessage={get(formik?.errors, name)} /> : null,
    disabled,
    ...rest
  } = restProps
 
  function handleChange(e: React.ChangeEvent<HTMLInputElement>): void {
    const correctVal = e.currentTarget.value.replace(DurationInputHelpers.TEXT_LIMIT_REGEX, '')
    formik.setFieldValue(e.currentTarget.name, correctVal)
    onChange?.(correctVal)
  }
 
  return (
    <FormGroup {...rest} labelFor={name} helperText={helperText} intent={intent} disabled={disabled} label={label}>
      <InputGroup
        fill
        placeholder="Enter w/d/h/m/s/ms"
        {...inputProps}
        disabled={disabled}
        name={name}
        intent={intent}
        value={get(formik.values, name)}
        onChange={handleChange}
        onBlur={formik.handleBlur}
      />
    </FormGroup>
  )
}
 
export const DurationInputFieldForInputSet = connect<DurationInputForInputSetProps>(DurationInputForInputSet)