All files / modules/75-cf/components/EditFlagTabs PercentageRollout.tsx

85% Statements 51/60
70.73% Branches 58/82
81.82% Functions 18/22
84.91% Lines 45/53

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              4x 4x 4x   4x 4x 4x 4x   4x 4x                                   4x               25x   25x 25x   25x 141x   72x                     25x   25x 12x   12x 12x           36x   12x 12x       25x 18x   51x             25x 25x 25x 64x   25x 64x     25x     25x           25x 13x     25x 13x 3x       25x                                                                                             72x                             72x                                           12x                                     4x  
/*
 * 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, useMemo } from 'react'
import { Layout, Text, Container, Select } from '@wings-software/uicore'
import { sumBy, clamp } from 'lodash-es'
import type { Distribution, WeightedVariation, Variation } from 'services/cf'
import { useStrings } from 'framework/strings'
import { useBucketByItems } from '@cf/utils/CFUtils'
import { CFVariationColors } from '@cf/constants'
import { useTargetAttributes } from '@cf/hooks/useTargetAttributes'
import type { Option } from '@cf/utils/sortOptions'
import { sortOptions } from '@cf/utils/sortOptions'
import css from './TabTargeting.module.scss'
 
interface PercentageValues {
  id: string
  displayName: string
  value: number
  color: string
}
 
interface PercentageRolloutProps {
  editing: boolean
  bucketBy?: string
  variations: Variation[]
  weightedVariations: WeightedVariation[]
  onSetPercentageValues?(value: Distribution): void
  style?: React.CSSProperties
}
 
const PercentageRollout: React.FC<PercentageRolloutProps> = ({
  editing,
  bucketBy,
  weightedVariations,
  variations,
  onSetPercentageValues,
  style
}) => {
  const [bucketByValue, setBucketByValue] = useState<string>(bucketBy || 'identifier')
 
  const [percentageError, setPercentageError] = useState(false)
  const { getString } = useStrings()
 
  const variationsToPercentage = variations?.map((elem, i) => {
    const weightedVariation = weightedVariations.find(wvElem => wvElem.variation === elem.identifier)
 
    return {
      id: elem.identifier,
      displayName: elem.name || elem.value,
      value:
        weightedVariation?.weight || weightedVariation?.weight === 0
          ? weightedVariation?.weight
          : Math.floor(100 / (variations?.length ?? 1)),
      color: CFVariationColors[i % CFVariationColors.length]
    }
  })
 
  const [percentageValues, setPercentageValues] = useState<PercentageValues[]>(() => variationsToPercentage)
 
  const changeColorWidthSlider = (e: React.ChangeEvent<HTMLInputElement>, id: string): void => {
    Eif (percentageValues) {
      let updatedPercentages: PercentageValues[]
      const newValue = Math.floor(clamp(Number(e.target.value), 0, 100))
      Iif (percentageValues.length === 2) {
        updatedPercentages = percentageValues.map(elem => ({
          ...elem,
          value: elem.id === id ? newValue : 100 - newValue
        }))
      } else {
        updatedPercentages = percentageValues.map(elem => (elem.id === id ? { ...elem, value: newValue } : elem))
      }
      setPercentageError(sumBy(updatedPercentages, 'value') > 100)
      setPercentageValues(updatedPercentages)
    }
  }
 
  useEffect(() => {
    onSetPercentageValues?.({
      bucketBy: bucketByValue,
      variations: percentageValues.map(elem => ({
        variation: elem.id,
        weight: elem.value
      }))
    })
  }, [bucketByValue, percentageValues])
 
  const { bucketByItems, addBucketByItem } = useBucketByItems()
  const { targetAttributes } = useTargetAttributes()
  const bucketBySelectValue = useMemo(() => {
    return bucketByItems.find(item => item.value === bucketByValue)
  }, [bucketByItems, bucketByValue])
  const bucketByDisplayName = useMemo(() => {
    return bucketByItems.find(item => item.value === bucketByValue)?.label
  }, [bucketByItems, bucketByValue])
 
  const sortedBucketByItems = useMemo<Option[]>(() => sortOptions(bucketByItems), [bucketByItems])
 
  type InputEventType = { target: { value: string } }
  const onSelectEvent = (event: InputEventType): void => {
    const { value } = event.target
    setBucketByValue(value)
    addBucketByItem(value)
  }
 
  useEffect(() => {
    addBucketByItem(bucketBy as string)
  }, [bucketBy, addBucketByItem])
 
  useEffect(() => {
    if (targetAttributes.length) {
      targetAttributes.forEach(addBucketByItem)
    }
  }, [targetAttributes, addBucketByItem])
 
  return (
    <Container margin={{ left: editing ? 'small' : 'xsmall' }} style={style}>
      <Layout.Horizontal
        margin={{ bottom: 'small' }}
        style={{ alignItems: 'baseline', marginTop: editing ? 'var(--spacing-small)' : 0 }}
      >
        <Text margin={{ right: 'small' }} style={{ fontSize: '14px', lineHeight: '24px', whiteSpace: 'nowrap' }}>
          <span
            dangerouslySetInnerHTML={{
              __html: getString('cf.featureFlags.bucketBy', {
                targetField: editing ? undefined : bucketByDisplayName || bucketBy
              })
            }}
          />
        </Text>
        {editing && (
          <Select
            data-testid="bucket-by"
            name="bucketBy"
            value={bucketBySelectValue}
            items={sortedBucketByItems}
            onChange={({ value }) => {
              addBucketByItem(value as string)
              setBucketByValue(value as string)
            }}
            inputProps={{
              onBlur: onSelectEvent,
              onKeyUp: event => {
                if (event.keyCode === 13) {
                  onSelectEvent(event as unknown as InputEventType)
                }
              }
            }}
            allowCreatingNewItems
          />
        )}
      </Layout.Horizontal>
      <div
        style={{
          borderRadius: '10px',
          width: '300px',
          height: '11px',
          display: 'flex',
          overflow: 'hidden'
        }}
      >
        {percentageValues?.map(elem => (
          <span
            key={elem.id}
            data-testid={`${elem.id}-bar-percentage`}
            style={{
              width: `${elem.value}%`,
              backgroundColor: elem.color,
              display: 'inline-block',
              height: '11px'
            }}
          />
        ))}
      </div>
      <Container margin={{ top: 'medium' }}>
        {percentageValues?.length &&
          percentageValues?.map((elem, i) => (
            <Layout.Horizontal
              key={`${elem.id}-${i}`}
              data-testid={`${elem.id}-percentage`}
              margin={{ bottom: 'medium' }}
              style={{ alignItems: 'baseline' }}
            >
              <span
                className={css.circle}
                style={{
                  backgroundColor: percentageValues[i].color,
                  marginRight: '10px',
                  transform: 'translateY(1px)'
                }}
              ></span>
              <Text margin={{ right: 'medium' }} width={editing ? 198 : 237}>
                {elem.displayName}
              </Text>
              {editing ? (
                <Text>
                  <input
                    type="number"
                    data-testid={`${elem.id}-percentage-value`}
                    onChange={e => changeColorWidthSlider(e, elem.id)}
                    style={{ width: '50px', marginRight: 'var(--spacing-xsmall)' }}
                    value={elem.value}
                    min={0}
                    max={100}
                  />
                  %
                </Text>
              ) : (
                <Text>{elem.value}%</Text>
              )}
            </Layout.Horizontal>
          ))}
        {percentageError && <Text intent="danger">{getString('cf.featureFlags.bucketOverflow')}</Text>}
      </Container>
    </Container>
  )
}
 
export default PercentageRollout