UNPKG

mui-chip-select

Version:

A react component for building selectable MUI Chips

56 lines 3.14 kB
"use strict"; Object.defineProperty(exports, "__esModule", { value: true }); var tslib_1 = require("tslib"); var react_1 = tslib_1.__importStar(require("react")); var Chip_1 = tslib_1.__importDefault(require("@mui/material/Chip")); var Stack_1 = tslib_1.__importDefault(require("@mui/material/Stack")); var CheckCircle_1 = tslib_1.__importDefault(require("@mui/icons-material/CheckCircle")); function MuiChipSelect(_a) { var options = _a.options, onChange = _a.onChange, chipProps = _a.chipProps, className = _a.className; var _b = (0, react_1.useState)([]), selected = _b[0], setSelected = _b[1]; function handleChipClick(option) { var newSelected = []; if (typeof option === 'string') { var selectedIndex = selected.indexOf(option); if (selectedIndex === -1) { newSelected = tslib_1.__spreadArray(tslib_1.__spreadArray([], selected, true), [option], false); } else if (selectedIndex === 0) { newSelected = selected.slice(1); } else if (selectedIndex === selected.length - 1) { newSelected = selected.slice(0, -1); } else if (selectedIndex > 0) { newSelected = tslib_1.__spreadArray(tslib_1.__spreadArray([], selected.slice(0, selectedIndex), true), selected.slice(selectedIndex + 1), true); } } else { var selectedIndex = selected.findIndex(function (opt) { return typeof opt === 'string' ? opt === option.label : opt.value === option.value; }); if (selectedIndex === -1) { newSelected = tslib_1.__spreadArray(tslib_1.__spreadArray([], selected, true), [option], false); } else if (selectedIndex === 0) { newSelected = selected.slice(1); } else if (selectedIndex === selected.length - 1) { newSelected = selected.slice(0, -1); } else if (selectedIndex > 0) { newSelected = tslib_1.__spreadArray(tslib_1.__spreadArray([], selected.slice(0, selectedIndex), true), selected.slice(selectedIndex + 1), true); } } setSelected(newSelected); onChange(newSelected); } var optionList = options.map(function (option) { return (typeof option === 'string' ? { label: option, value: option } : option); }); return (react_1.default.createElement(Stack_1.default, { direction: 'row', spacing: 1, className: className }, optionList.map(function (option) { return (react_1.default.createElement(Chip_1.default, tslib_1.__assign({ key: option.value, label: option.label, clickable: true, icon: react_1.default.createElement(CheckCircle_1.default, null), onClick: function () { return handleChipClick(option); }, color: selected.findIndex(function (opt) { return typeof opt === 'string' ? opt === option.label : opt.value === option.value; }) !== -1 ? 'primary' : 'default' }, chipProps))); }))); } exports.default = MuiChipSelect; //# sourceMappingURL=App.js.map