UNPKG

@yandex/ui

Version:

Yandex UI components

66 lines (65 loc) 2.43 kB
"use strict"; Object.defineProperty(exports, "__esModule", { value: true }); exports.useButtonGroupState = void 0; var tslib_1 = require("tslib"); var react_1 = require("react"); /** * Функция, возвращающая детей в `array` по индексам `indices` * * @example * * const indices = [1, 3, 4] * const array = ['a', 'b', 'c', {}, []] * * const res = indicesToArray(indices, array) * // ['b', {}, []] * * @param indices number[] Получает на вход массив индексов, по которым должны выбраться поля * @param array any[] Откуда забираются данные */ var indicesToArray = function (indices, array) { var e_1, _a; var res = []; try { for (var indices_1 = tslib_1.__values(indices), indices_1_1 = indices_1.next(); !indices_1_1.done; indices_1_1 = indices_1.next()) { var index = indices_1_1.value; res.push(array[index]); } } catch (e_1_1) { e_1 = { error: e_1_1 }; } finally { try { if (indices_1_1 && !indices_1_1.done && (_a = indices_1.return)) _a.call(indices_1); } finally { if (e_1) throw e_1.error; } } return res; }; /** * Реакт-хук состояния для компонента ButtonGroup. * * * @example * * const state = useButtonGroupState({ type: 'radio' }) * return <ButtonGroup {...state} /> */ function useButtonGroupState(_a) { var type = _a.type, value = _a.value, mappings = _a.mappings; var _b = tslib_1.__read(react_1.useState(value || []), 2), selected = _b[0], setSelected = _b[1]; var _c = tslib_1.__read(react_1.useState(indicesToArray(selected, mappings || [])), 2), mapped = _c[0], setMapped = _c[1]; var onClick = react_1.useCallback(function (_event, nextValue) { var includes = selected.includes(nextValue); var indices = []; if (type === 'radio') { indices = includes ? [] : [nextValue]; } else { indices = includes ? selected.filter(function (el) { return el !== nextValue; }) : tslib_1.__spread(selected, [nextValue]); } setSelected(indices); setMapped(indicesToArray(indices, mappings || [])); }, [mappings, selected, type]); return { onClick: onClick, selected: selected, mapped: mapped }; } exports.useButtonGroupState = useButtonGroupState;