|
| 1 | +import React from 'react'; |
| 2 | + |
| 3 | +import {Flex, Progress, Text} from '@gravity-ui/uikit'; |
| 4 | + |
| 5 | +import {defaultFormatProgressValues} from '../../../../../utils/progress'; |
| 6 | +import type {FormatProgressViewerValues} from '../../../../../utils/progress'; |
| 7 | +import {isNumeric, safeParseNumber} from '../../../../../utils/utils'; |
| 8 | + |
| 9 | +import {DEFAULT_PROGRESS_WIDTH, MAX_PERCENTAGE, MIN_PERCENTAGE, PROGRESS_SIZE} from './constants'; |
| 10 | +import i18n from './i18n'; |
| 11 | + |
| 12 | +interface ProgressWrapperProps { |
| 13 | + value?: number | string; |
| 14 | + capacity?: number | string; |
| 15 | + formatValues?: FormatProgressViewerValues; |
| 16 | + className?: string; |
| 17 | + width?: number; |
| 18 | +} |
| 19 | + |
| 20 | +const isValidValue = (val?: number | string): boolean => |
| 21 | + isNumeric(val) && safeParseNumber(val) >= 0; |
| 22 | + |
| 23 | +export function ProgressWrapper({ |
| 24 | + value, |
| 25 | + capacity, |
| 26 | + formatValues = defaultFormatProgressValues, |
| 27 | + className, |
| 28 | + width = DEFAULT_PROGRESS_WIDTH, |
| 29 | +}: ProgressWrapperProps) { |
| 30 | + if (!isValidValue(value)) { |
| 31 | + return <div className={className}>{i18n('alert_no-data')}</div>; |
| 32 | + } |
| 33 | + |
| 34 | + const numericValue = safeParseNumber(value); |
| 35 | + const numericCapacity = safeParseNumber(capacity); |
| 36 | + |
| 37 | + const rawPercentage = |
| 38 | + numericCapacity > 0 |
| 39 | + ? Math.floor((numericValue / numericCapacity) * MAX_PERCENTAGE) |
| 40 | + : MAX_PERCENTAGE; |
| 41 | + const fillWidth = Math.max(MIN_PERCENTAGE, rawPercentage); |
| 42 | + const clampedFillWidth = Math.min(fillWidth, MAX_PERCENTAGE); |
| 43 | + |
| 44 | + const [valueText, capacityText] = React.useMemo(() => { |
| 45 | + return formatValues(Number(value), Number(capacity)); |
| 46 | + }, [formatValues, value, capacity]); |
| 47 | + |
| 48 | + const displayText = React.useMemo(() => { |
| 49 | + if (numericCapacity <= 0) { |
| 50 | + return String(valueText); |
| 51 | + } |
| 52 | + return i18n('context_capacity-usage', {value: valueText, capacity: capacityText}); |
| 53 | + }, [valueText, capacityText, numericCapacity]); |
| 54 | + |
| 55 | + const validatedWidth = Math.max(0, width); |
| 56 | + |
| 57 | + return ( |
| 58 | + <Flex alignItems="center" gap="2" className={className}> |
| 59 | + <div style={{width: `${validatedWidth}px`}}> |
| 60 | + <Progress value={clampedFillWidth} theme="success" size={PROGRESS_SIZE} /> |
| 61 | + </div> |
| 62 | + <Text variant="body-1" color="secondary"> |
| 63 | + {displayText} |
| 64 | + </Text> |
| 65 | + </Flex> |
| 66 | + ); |
| 67 | +} |
0 commit comments