import React from 'react'; import { SEGMENTED_BAR_ERRORS } from '../constants'; import { assert } from '../../../../utils/helpers'; import type { SegmentedBarLegendConfig, SegmentedBarLegendDisplayValue, SegmentedBarData, SegmentedBarStyleConfig, } from '../types'; export const useValidateSegmentedBarData = ({ values, dataLength, }: { dataLength: number; values: number[]; }) => { const { hasNegativeValue, negativeValue } = React.useMemo(() => { const foundNegativeValue = values.find((value) => value < 0); return { hasNegativeValue: foundNegativeValue !== undefined, negativeValue: foundNegativeValue, }; }, [dataLength, values]); assert( !hasNegativeValue, SEGMENTED_BAR_ERRORS.negativeValue.replace('$value', String(negativeValue)) ); }; export const useValidateSegmentedBarLegendDisplayValues = ({ dataLength, legendConfig, fallbackValues, }: { dataLength: number; legendConfig: SegmentedBarLegendConfig | undefined; fallbackValues: ReadonlyArray; }): ReadonlyArray => { const displayValues = legendConfig?.displayValues; const { valuesToUse, hasLengthMismatch, hasEmptyEntry } = React.useMemo(() => { if (displayValues === undefined) { return { valuesToUse: fallbackValues, hasLengthMismatch: false, hasEmptyEntry: false, }; } const isLengthMismatch = displayValues.length !== dataLength; const isEmptyEntry = displayValues.some( (value) => value === undefined || value === null ); return { valuesToUse: displayValues, hasLengthMismatch: isLengthMismatch, hasEmptyEntry: isEmptyEntry, }; }, [dataLength, displayValues, fallbackValues]); assert( !(hasLengthMismatch || hasEmptyEntry), SEGMENTED_BAR_ERRORS.legendDisplayValues ); return valuesToUse; }; export const useValidateSegmentedBarStyleConfig = ({ dataSeries, customSeries, }: { dataSeries: SegmentedBarData; customSeries: SegmentedBarStyleConfig['series']; }): void => { const { hasInvalidLength, hasMissingColor, hasMissingLabel } = React.useMemo(() => { if (!customSeries || dataSeries.length === 0) { return { hasInvalidLength: false, hasMissingColor: false, hasMissingLabel: false, }; } const invalidLength = !Array.isArray(customSeries) || customSeries.length !== dataSeries.length; if (invalidLength) { return { hasInvalidLength: invalidLength, hasMissingColor: false, hasMissingLabel: false, }; } const missingColor = customSeries.some((item) => !item?.color); const providedLabels = new Set(customSeries.map((item) => item.label)); const missingLabel = dataSeries.some( ({ label }) => !providedLabels.has(label) ); return { hasInvalidLength: invalidLength, hasMissingColor: missingColor, hasMissingLabel: missingLabel, }; }, [customSeries, dataSeries]); assert( !(hasInvalidLength || hasMissingColor || hasMissingLabel), SEGMENTED_BAR_ERRORS.customColorsInvalid ); };