nishant-design-system
Version:
Sense UI components library
82 lines (66 loc) • 1.88 kB
Flow
// @flow strict
import * as React from 'react';
import type {MenuOption} from '../components/Menu';
export const getSelectedKeysFromSelectedOption = (
currentOption?: MenuOption,
currentSelectedKeys?: Array<string>,
): Array<string> => {
if (!Array.isArray(currentSelectedKeys) || !currentOption?.key) {
return [];
}
let newSelectedKeys = [];
if (currentSelectedKeys.includes(currentOption.key)) {
newSelectedKeys = currentSelectedKeys.filter(
(item) => item !== currentOption.key,
);
} else {
newSelectedKeys = [...currentSelectedKeys, currentOption.key];
}
return newSelectedKeys;
};
export const getTextLabelFromSelectedKeys = (
currentSelectedKeys?: Array<string>,
options?: MenuOption[],
): string => {
if (!Array.isArray(currentSelectedKeys) || !Array.isArray(options)) {
return '';
}
const selectedOptions = getOptionsFromKeys(options, currentSelectedKeys);
return selectedOptions.map((option) => option.label).join(', ');
};
export const getButtonLabelFromSelectedKeys = (
currentSelectedKeys?: Array<string>,
label?: React.Node,
): React.Node => {
if (
!Array.isArray(currentSelectedKeys) ||
typeof label !== 'string' ||
!currentSelectedKeys.length
) {
return label;
}
return `(${currentSelectedKeys.length}) ${label}`;
};
export const getOptionFromKey = (
options?: MenuOption[],
key?: string,
): ?MenuOption => {
if (!Array.isArray(options) || !key || !options.length) {
return null;
}
return options.find((option) => option.key === key);
};
export const getOptionsFromKeys = (
options?: MenuOption[],
keys?: Array<string>,
): Array<MenuOption> => {
if (
!Array.isArray(options) ||
!Array.isArray(keys) ||
!options.length ||
!keys.length
) {
return [];
}
return options.filter((option) => keys.includes(option.key));
};